diff --git a/packages/core/src/audio/audioFxAutomation.clamping.test.ts b/packages/core/src/audio/audioFxAutomation.clamping.test.ts index 5f8b45ae96..f47d469566 100644 --- a/packages/core/src/audio/audioFxAutomation.clamping.test.ts +++ b/packages/core/src/audio/audioFxAutomation.clamping.test.ts @@ -74,19 +74,19 @@ const lane: HfAutomationLane = { ], }; -it("finishes the lane when clamping a curve also blocks its fallback ramp", () => { +it("finishes the lane with ramps when the audio clock is already past its start", () => { const param = new ClampedParam(0.032); expect(() => scheduleParamLane([{ param }], lane, "linear", { scheduledAt: 0, elapsed: 0, rate: 1 }), ).not.toThrow(); - expect(param.ramps).toBe(3); expect(param.curves).toHaveLength(0); + expect(param.ramps).toBeGreaterThan(0); expect(param.value).toBeCloseTo(0.7); }); -it("retains each bend when the curves are scheduled ahead of the audio clock", () => { +it("books each bend as ramps ahead of the audio clock too, never a value curve", () => { const param = new ClampedParam(0.032); scheduleParamLane([{ param }], lane, "linear", { scheduledAt: 1, elapsed: 0, rate: 1 }); - expect(param.curves).toHaveLength(3); - expect(param.ramps).toBe(0); + expect(param.curves).toHaveLength(0); + expect(param.value).toBeCloseTo(0.7); }); diff --git a/packages/core/src/audio/audioFxAutomation.test.ts b/packages/core/src/audio/audioFxAutomation.test.ts index edf0b8548b..6b13bd5781 100644 --- a/packages/core/src/audio/audioFxAutomation.test.ts +++ b/packages/core/src/audio/audioFxAutomation.test.ts @@ -2,14 +2,13 @@ import { describe, expect, it } from "vitest"; import { cancelParamLane, - clearParamLane, scheduleChainAutomation, scheduleParamLane, volumeLane, type AutomationTiming, } from "./audioFxAutomation.js"; import type { FxParamTarget } from "./audioFxGraph.js"; -import type { HfAutomationLane } from "../audioAutomation.js"; +import { sampleAutomationLane, type HfAutomationLane } from "../audioAutomation.js"; import type { HfAudioFxChain } from "../audioFx.js"; /** @@ -72,13 +71,25 @@ const curvedRamp: HfAutomationLane = { ], }; -/** Schedule `curvedRamp` and return the fake param it wrote to — the setup - * three tests below share, each checking something different about the - * curve it produces. */ -function scheduleCurved(): { target: FxParamTarget; param: FakeParam } { - const { target, param } = fake(); - scheduleParamLane([target], curvedRamp, "linear", at(0)); - return { target, param }; +type Booked = Extract; + +function booked(calls: readonly Call[]): Booked[] { + return calls.flatMap((c): Booked[] => { + if (c.op === "set" || c.op === "ramp") return [c]; + if (c.op === "cancel") return []; + throw new Error(`booked a ${c.op}`); + }); +} + +/** What the booked events play at context time `t`, read as the AudioParam would. */ +function valueAt(calls: readonly Call[], t: number): number { + const events = booked(calls); + const i = events.findIndex((c) => c.time > t || (c.time === t && c.op === "set")); + const next = events[i]; + const prev = events[i === -1 ? events.length - 1 : i - 1] ?? next; + if (!next || !prev) return prev?.value ?? Number.NaN; + if (next.op === "set") return next.time === t ? next.value : prev.value; + return prev.value + ((next.value - prev.value) * (t - prev.time)) / (next.time - prev.time); } describe("scheduleParamLane", () => { @@ -86,13 +97,10 @@ describe("scheduleParamLane", () => { const { target, param } = fake(); scheduleParamLane([target], ramp, "linear", at(0)); expect(param.calls).toEqual([ - // Cleared from zero, not held: holding leaves the span of a running curve - // booked, and Chrome refuses the next curve — or a plain `.value` write — - // that lands inside it. The seed below restores the value in the same pass, - // so clearing costs nothing audible. { op: "cancel", time: 0 }, // Before the first point the envelope holds that point's value. { op: "set", value: 0.2, time: 10 }, + { op: "set", value: 0.2, time: 11 }, { op: "ramp", value: 0.8, time: 13 }, ]); }); @@ -119,14 +127,15 @@ describe("scheduleParamLane", () => { scheduleParamLane([target], ramp, "linear", at(-2)); // Clip time 1 is three seconds of context time away. expect(param.calls[1]).toEqual({ op: "set", value: 0.2, time: 10 }); - expect(param.calls[2]).toEqual({ op: "ramp", value: 0.8, time: 15 }); + expect(param.calls[2]).toEqual({ op: "set", value: 0.2, time: 13 }); + expect(param.calls[3]).toEqual({ op: "ramp", value: 0.8, time: 15 }); }); it("compresses the envelope by the playback rate", () => { const { target, param } = fake(); scheduleParamLane([target], ramp, "linear", at(0, 2)); // Clip time 3 arrives after 1.5 s of context time at double speed. - expect(param.calls[2]).toEqual({ op: "ramp", value: 0.8, time: 11.5 }); + expect(param.calls[3]).toEqual({ op: "ramp", value: 0.8, time: 11.5 }); }); it("sets a constant lane once instead of scheduling it", () => { @@ -150,16 +159,12 @@ describe("scheduleParamLane", () => { }); it("samples a curved segment rather than ramping through the bend", () => { - const { param } = scheduleCurved(); - const curve = param.calls.find((c) => c.op === "curve"); - expect(curve).toBeTruthy(); - if (curve?.op !== "curve") throw new Error("expected a curve"); - expect(curve.time).toBe(10); - expect(curve.duration).toBe(2); - expect(curve.values[0]).toBeCloseTo(0, 6); - expect(curve.values[curve.values.length - 1]).toBeCloseTo(1, 6); + const { target, param } = fake(); + scheduleParamLane([target], curvedRamp, "linear", at(0)); + expect(valueAt(param.calls, 10)).toBeCloseTo(0, 6); + expect(valueAt(param.calls, 12)).toBeCloseTo(1, 6); // Curved, so the midpoint is not halfway. - expect(curve.values[Math.floor(curve.values.length / 2)]).toBeLessThan(0.4); + expect(valueAt(param.calls, 11)).toBeLessThan(0.4); }); it("samples a segment bent by a via point, not just one bent by `curve`", () => { @@ -180,11 +185,8 @@ describe("scheduleParamLane", () => { "linear", at(0), ); - const curve = param.calls.find((c) => c.op === "curve"); - expect(curve, "a via-bent segment must be sampled, not ramped").toBeTruthy(); - if (curve?.op !== "curve") throw new Error("expected a curve"); // Through the via point: 90% of the way up at the halfway mark. - expect(curve.values[Math.floor(curve.values.length / 2)]).toBeGreaterThan(0.8); + expect(valueAt(param.calls, 11)).toBeGreaterThan(0.8); }); it("samples a log-scaled sweep, which a linear ramp would get wrong", () => { @@ -201,24 +203,8 @@ describe("scheduleParamLane", () => { "log", at(0), ); - const curve = param.calls.find((c) => c.op === "curve"); - if (curve?.op !== "curve") throw new Error("expected a curve"); - // Halfway is the geometric mean, not the arithmetic one. The array has an - // even length so no sample sits exactly on it; both neighbours bracket it. - const half = curve.values.length / 2; - const geometric = Math.sqrt(200 * 8000); - expect(curve.values[half - 1] ?? 0).toBeLessThan(geometric); - expect(curve.values[half] ?? 0).toBeGreaterThan(geometric); - expect((curve.values[half] ?? 0) / geometric).toBeCloseTo(1, 1); - // A linear ramp would have been at 4100 by now — nowhere near. - expect(curve.values[half] ?? 0).toBeLessThan(2000); - }); - - it("does not seed on top of a curve that starts at the same instant", () => { - const { param } = scheduleCurved(); - // A value curve may not overlap another event, so there is no set at 10. - expect(param.calls.filter((c) => c.op === "set")).toEqual([]); - expect(param.calls[1]?.op).toBe("curve"); + // Halfway is the geometric mean; one linear ramp would have been at 4100. + expect(valueAt(param.calls, 11) / Math.sqrt(200 * 8000)).toBeCloseTo(1, 1); }); it("writes every AudioParam behind one knob, each through its own mapping", () => { @@ -240,12 +226,9 @@ describe("scheduleParamLane", () => { at(0), ); expect(wet.calls[1]).toEqual({ op: "set", value: 0.25, time: 10 }); - // The dry side moves the opposite way. A mapping may be non-linear, so the - // segment is sampled rather than ramped. - const dryCurve = dry.calls.find((c) => c.op === "curve"); - if (dryCurve?.op !== "curve") throw new Error("expected a curve"); - expect(dryCurve.values[0]).toBeCloseTo(0.75, 6); - expect(dryCurve.values[dryCurve.values.length - 1]).toBeCloseTo(0.25, 6); + // The dry side moves the opposite way. + expect(valueAt(dry.calls, 10)).toBeCloseTo(0.75, 6); + expect(valueAt(dry.calls, 14)).toBeCloseTo(0.25, 6); }); it("ignores an empty lane", () => { @@ -255,235 +238,39 @@ describe("scheduleParamLane", () => { }); }); -/** - * An AudioParam with Chrome's own overlap rule, and its own cancel semantics. - * - * The distinction that matters: `cancelScheduledValues(t)` drops events at or - * after `t` but leaves a value curve that is already running — the spec only - * special-cases an in-progress curve for `cancelAndHoldAtTime`, which truncates - * it. Schedule a curve inside one that is still live and the browser throws. - */ -class OverlapAwareParam { - curves: { time: number; duration: number }[] = []; - value = 0; - setValueAtTime(): void {} - linearRampToValueAtTime(): void {} - setValueCurveAtTime(_values: Float32Array, time: number, duration: number): void { - const clash = this.curves.find((c) => time < c.time + c.duration && time + duration > c.time); - if (clash) { - throw new Error( - `Failed to execute 'setValueCurveAtTime' on 'AudioParam': ` + - `setValueCurveAtTime(..., ${time}, ${duration}) overlaps ` + - `setValueCurveAtTime(..., ${clash.time}, ${clash.duration})`, - ); - } - this.curves.push({ time, duration }); - } - cancelScheduledValues(time: number): void { - // Events at or after the cancel; a curve already under way is untouched. - this.curves = this.curves.filter((c) => c.time < time); - } - cancelAndHoldAtTime(time: number): void { - this.curves = this.curves - .filter((c) => c.time < time) - .map((c) => ({ time: c.time, duration: Math.min(c.duration, time - c.time) })); - } -} - -describe("rescheduling over a curve that is still playing", () => { - const bent: HfAutomationLane = { - target: "volume", - points: [ - { t: 0, v: 1, curve: 1 }, - { t: 8, v: 0.2, curve: 1 }, - { t: 12, v: 1 }, - ], - }; - - it("takes over from an in-progress curve instead of throwing", () => { - // Two schedule passes a few milliseconds apart is ordinary: an attribute edit - // lands, the graph is re-parameterised, and the envelope is re-aimed at the - // live playhead. The second pass has to displace the curve the first one - // started, which `cancelScheduledValues` does not do for a curve that is - // already running — the browser then refuses the new curve outright. - const param = new OverlapAwareParam(); - const target = { param: param as unknown as AudioParam }; - scheduleParamLane([target], bent, "linear", at(0, 1, 9.109333)); - expect(() => - scheduleParamLane([target], bent, "linear", at(0.005334, 1, 9.114667)), - ).not.toThrow(); - }); - - it("survives a burst of reschedules, as a dragged knob produces", () => { - const param = new OverlapAwareParam(); - const target = { param: param as unknown as AudioParam }; - for (let i = 0; i < 12; i++) { - const when = 9.1 + i * 0.005; - expect(() => - scheduleParamLane([target], bent, "linear", at(i * 0.005, 1, when)), - ).not.toThrow(); +describe("never a value curve", () => { + it("plays consecutive bent segments as ramps through the lane", () => { + const lane: HfAutomationLane = { + target: "fx.n1.frequency", + points: [ + { t: 0, v: 200, curve: 1 }, + { t: 1, v: 4000, curve: -1 }, + { t: 2, v: 500 }, + ], + }; + const { target, param } = fake(); + scheduleParamLane([target], lane, "log", at(0.1)); + expect(param.calls.filter((c) => c.op === "curve")).toEqual([]); + for (const t of [0.1, 0.3, 0.5, 0.9, 1, 1.2, 1.6, 2, 3]) { + const want = sampleAutomationLane(lane, t, "log"); + expect( + Math.abs(valueAt(param.calls, 10 + t - 0.1) / want - 1), + `clip time ${t}`, + ).toBeLessThan(0.02); } }); -}); -describe("a curve the browser refuses", () => { - /** - * A param that rejects any curve overlapping one it has been given, and — like - * Chrome — keeps counting a held curve's original span. Holding stops what is - * audible; it does not free the slot for overlap checking. - */ - class UnforgivingParam { - curves: { time: number; duration: number }[] = []; - ramps: { time: number; value: number }[] = []; - sets: { time: number; value: number }[] = []; - value = 0; - setValueAtTime(value: number, time: number): void { - this.sets.push({ time, value }); + it("holds the first point's value until the clip reaches it", () => { + for (const lane of [ + ramp, + { ...ramp, points: [{ ...ramp.points[0]!, curve: 1 }, ramp.points[1]!] }, + ]) { + const { target, param } = fake(); + scheduleParamLane([target], lane, "linear", at(-2)); + // Clip time 1 is context time 13. + expect(valueAt(param.calls, 12.9)).toBeCloseTo(0.2, 6); + expect(valueAt(param.calls, 15)).toBeCloseTo(0.8, 6); } - linearRampToValueAtTime(value: number, time: number): void { - this.ramps.push({ time, value }); - } - setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void { - const clash = this.curves.find((c) => time < c.time + c.duration && time + duration > c.time); - if (clash) { - throw new Error( - `Failed to execute 'setValueCurveAtTime' on 'AudioParam': ` + - `setValueCurveAtTime(..., ${time}, ${duration}) overlaps ` + - `setValueCurveAtTime(..., ${clash.time}, ${clash.duration})`, - ); - } - this.curves.push({ time, duration }); - } - // Measured against Chrome, in a live running context and in an offline one - // suspended mid-curve: either cancel frees the span of a curve already under - // way, so only a write with no cancel at all is refused. - cancelScheduledValues(time: number): void { - this.curves = this.curves.filter((c) => c.time + c.duration < time); - } - cancelAndHoldAtTime(time: number): void { - this.cancelScheduledValues(time); - } - } - - const bent: HfAutomationLane = { - target: "volume", - points: [ - { t: 0, v: 1, curve: 1 }, - { t: 0.25, v: 0.4, curve: 1 }, - { t: 0.6, v: 1, curve: 1 }, - { t: 1.2, v: 0.3 }, - ], - }; - - it("reschedules mid-playback with its curves intact", () => { - // Applying a carve while the transport runs reschedules into curves that are - // already playing — one render quantum apart is the common case. Cancelling - // the parameter first is what lets the new pass keep its shape instead of - // being refused; this does not discriminate the strength of the cancel, which - // the no-cancel test below is for. - const param = new UnforgivingParam(); - const target = { param: param as unknown as AudioParam }; - scheduleParamLane([target], bent, "linear", at(0, 1, 1492.016)); - const first = param.curves.length; - expect(() => - scheduleParamLane([target], bent, "linear", at(0.005333, 1, 1492.021333)), - ).not.toThrow(); - expect(param.curves.length).toBeGreaterThan(0); - // Curves, not ramps: nothing had to be degraded. - expect(param.ramps).toHaveLength(0); - expect(first).toBeGreaterThan(0); - }); - - it("still degrades to a ramp where the span cannot be freed at all", () => { - // The last line of defence, for a hypothetical param that refuses to give the - // span up. No engine has been measured behaving this way; it stands in for the - // unexplained curve-over-curve refusals reported from the field. The envelope - // loses a bend rather than the exception escaping and abandoning the rest. - class ImmovableParam extends UnforgivingParam { - override cancelScheduledValues(): void { - // Nothing is ever freed. - } - } - const param = new ImmovableParam(); - const target = { param: param as unknown as AudioParam }; - scheduleParamLane([target], bent, "linear", at(0, 1, 100)); - expect(() => - scheduleParamLane([target], bent, "linear", at(0.005333, 1, 100.005333)), - ).not.toThrow(); - expect(param.ramps.length).toBeGreaterThan(0); - }); -}); - -describe("a curve that starts at this very instant", () => { - /** - * Chrome's behaviour at the boundary, which is where this bit: holding at a - * time does not free a curve that *begins* at that time, so both a fresh curve - * and a plain `.value` write at the same instant are refused. Only a cancel - * clears it. - */ - class BoundaryParam { - curves: { time: number; duration: number }[] = []; - #value = 0; - constructor(private clock: { currentTime: number }) {} - get value(): number { - return this.#value; - } - set value(v: number) { - const t = this.clock.currentTime; - const clash = this.curves.find((c) => t >= c.time && t <= c.time + c.duration); - if (clash) { - throw new Error( - `Failed to set the 'value' property on 'AudioParam': setValueAtTime(${v}, ${t}) ` + - `overlaps setValueCurveAtTime(..., ${clash.time}, ${clash.duration})`, - ); - } - this.#value = v; - } - setValueAtTime(v: number): void { - this.#value = v; - } - linearRampToValueAtTime(): void {} - setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void { - this.curves.push({ time, duration }); - } - // As Chrome behaves: either cancel frees a running curve's span. - cancelScheduledValues(time: number): void { - this.curves = this.curves.filter((c) => c.time + c.duration < time); - } - cancelAndHoldAtTime(time: number): void { - this.cancelScheduledValues(time); - } - } - - const bent: HfAutomationLane = { - target: "volume", - points: [ - { t: 0, v: 1, curve: 1 }, - { t: 0.04, v: 0.2, curve: 1 }, - { t: 4, v: 1 }, - ], - }; - - it("clears the booked span so the next pass can schedule at all", () => { - const clock = { currentTime: 91.069 }; - const param = new BoundaryParam(clock); - const target = { param: param as unknown as AudioParam }; - scheduleParamLane([target], bent, "linear", at(0, 1, 91.069)); - expect(() => scheduleParamLane([target], bent, "linear", at(0, 1, 91.069))).not.toThrow(); - }); - - it("leaves the parameter writable, which is what a chain edit does next", () => { - // The re-parameterise after an edit writes every knob straight onto its param. - // Landing inside a span the scheduler booked at this instant is the error the - // console kept reporting, with the gain stage's own unity value in it. - const clock = { currentTime: 91.069 }; - const param = new BoundaryParam(clock); - const target = { param: param as unknown as AudioParam }; - scheduleParamLane([target], bent, "linear", at(0, 1, 91.069)); - clearParamLane([target]); - expect(() => { - (param as unknown as { value: number }).value = 1; - }).not.toThrow(); }); }); diff --git a/packages/core/src/audio/audioFxAutomation.ts b/packages/core/src/audio/audioFxAutomation.ts index 3084dbf4ac..b8ba8f77bf 100644 --- a/packages/core/src/audio/audioFxAutomation.ts +++ b/packages/core/src/audio/audioFxAutomation.ts @@ -2,7 +2,7 @@ * Plays automation envelopes through native AudioParam scheduling. * * Nothing here runs per frame. The envelope is handed to the audio thread once, - * as ramps and curves, so it stays sample-accurate no matter what the main + * as ramps, so it stays sample-accurate no matter what the main * thread is doing — and the offline render schedules it the same way, which is * why preview and render agree by construction rather than by tolerance. */ @@ -32,9 +32,9 @@ export interface AutomationTiming { } /** - * Sampling density for segments that cannot be expressed as a ramp. Dense - * enough that a curve is inaudible from a continuous one, capped so a long - * segment cannot allocate without bound. + * Sampling density for bent segments, played as ramps through these points. Dense + * enough to be inaudible from a continuous bend, capped so a long segment cannot + * allocate without bound. */ const CURVE_POINTS_PER_SEC = 100; const MIN_CURVE_POINTS = 8; @@ -42,10 +42,11 @@ const MAX_CURVE_POINTS = 4096; const identity = (v: number): number => v; -type Op = - | { kind: "set"; time: number; value: number } - | { kind: "ramp"; time: number; value: number } - | { kind: "curve"; time: number; duration: number; values: Float32Array }; +interface Op { + kind: "set" | "ramp"; + time: number; + value: number; +} /** * A segment is a straight line only when nothing bends it: no curvature and no @@ -72,16 +73,17 @@ function curvePointCount(duration: number): number { } /** - * One segment of the envelope, as the event that plays it. Returns null when - * the segment is already behind the playhead. + * One segment of the envelope: a set at its start, then ramps. Bends are ramps + * through sampled points, never `setValueCurveAtTime`: Chromium's audio thread can + * move a curve's start without its end, and the next event then aborts the page. */ -function segmentOp( +function segmentOps( lane: HfAutomationLane, index: number, scale: "linear" | "log", timing: AutomationTiming, map: FxParamTarget["map"], -): Op | null { +): Op[] { const { scheduledAt, elapsed, rate } = timing; const apply = map ?? identity; const toCtx = (t: number): number => scheduledAt + (t - elapsed) / rate; @@ -89,21 +91,22 @@ function segmentOp( const b = lane.points[index + 1]!; const toTime = toCtx(b.t); - if (toTime <= scheduledAt) return null; const fromTime = Math.max(scheduledAt, toCtx(a.t)); - const duration = toTime - fromTime; - if (duration <= 0) return null; - - if (isStraight(a, scale, map)) { - return { kind: "ramp", time: toTime, value: apply(b.v) }; - } - // Sample from wherever the segment is entered, which is mid-segment when the - // playhead landed inside it. - const count = curvePointCount(duration); - const raw = sampleAutomationCurve(lane, Math.max(a.t, elapsed), b.t, count, scale); - const values = new Float32Array(count); - for (let k = 0; k < count; k += 1) values[k] = apply(raw[k] ?? 0); - return { kind: "curve", time: fromTime, duration, values }; + if (toTime <= fromTime) return []; + // Entered wherever the playhead is, which is mid-segment when it landed inside it. + const enter = Math.max(a.t, elapsed); + const values = isStraight(a, scale, map) + ? [sampleAutomationLane(lane, enter, scale), b.v] + : sampleAutomationCurve(lane, enter, b.t, curvePointCount(toTime - fromTime), scale); + const last = values.length - 1; + return Array.from( + values, + (v, k): Op => ({ + kind: k === 0 ? "set" : "ramp", + time: k === last ? toTime : fromTime + ((toTime - fromTime) * k) / last, + value: apply(v), + }), + ); } /** Turn a lane into the events one AudioParam should receive. */ @@ -115,18 +118,12 @@ function planOps( ): Op[] { const ops: Op[] = []; for (let i = 0; i + 1 < lane.points.length; i += 1) { - const op = segmentOp(lane, i, scale, timing, map); - if (op) ops.push(op); + ops.push(...segmentOps(lane, i, scale, timing, map)); } - - // Hold the envelope's value at the moment playback starts. This is what makes - // a lane correct before its first point and after its last, and it gives a - // following ramp something to ramp from. - // - // A value curve may not overlap another event, so the seed is dropped when a - // curve already begins at that instant — the curve sets the value itself. + // Hold the envelope's value from the moment playback starts: before its first + // point, and after its last. const first = ops[0]; - if (!(first?.kind === "curve" && first.time <= timing.scheduledAt)) { + if (!first || first.time > timing.scheduledAt) { ops.unshift({ kind: "set", time: timing.scheduledAt, @@ -136,60 +133,22 @@ function planOps( return ops; } -/** Rebuild a refused plan with ramps so clamped curves cannot replay past audio. */ -function emitRamps(param: AudioParam, ops: readonly Op[]): void { - param.cancelScheduledValues(0); - for (const op of ops) { - if (op.kind === "set") param.setValueAtTime(op.value, op.time); - else if (op.kind === "ramp") param.linearRampToValueAtTime(op.value, op.time); - else { - param.setValueAtTime(op.values[0] ?? 0, op.time); - param.linearRampToValueAtTime(op.values[op.values.length - 1] ?? 0, op.time + op.duration); - } - } -} - -/** - * Hand the plan to the AudioParam. A clamped curve can overlap the next segment. - * On refusal, rebuild the whole lane as ramps: retrying later curves would clamp - * them forward too, replaying values that should already have elapsed. - */ function emit(param: AudioParam, ops: readonly Op[]): void { for (const op of ops) { if (op.kind === "set") param.setValueAtTime(op.value, op.time); - else if (op.kind === "ramp") param.linearRampToValueAtTime(op.value, op.time); - else { - try { - param.setValueCurveAtTime(op.values, op.time, op.duration); - } catch { - emitRamps(param, ops); - return; - } - } + else param.linearRampToValueAtTime(op.value, op.time); } } /** - * Drop every event booked on a parameter, including a curve already under way. - * - * Anything landing inside a running curve is refused — a fresh curve, or the - * plain `.value` write that re-parameterising a chain performs — so the param has - * to be cancelled first. Measured against Chrome, any cancel frees the span; this - * takes the strongest form on purpose, because curve-over-curve refusals were - * reported from the field with a cancel at the new schedule time already in place - * and have never reproduced. Cancelling from zero cannot leave a stale event - * behind whatever that mechanism is. - * - * Safe on these parameters because this scheduler is their only writer: they - * belong to effect nodes it built, and the caller re-seeds the value in the same - * breath, so nothing clicks. + * Drop every event booked on a parameter. Safe because this scheduler is the only + * writer of these parameters and the caller re-seeds the value in the same breath. */ export function clearParamLane(targets: readonly FxParamTarget[]): void { for (const target of targets) target.param.cancelScheduledValues(0); } -/** Stop an envelope, leaving the parameter wherever it currently sits. Held by hand: `cancelAndHoldAtTime` - * crashes the page in Chromium before 160 when the hold lands in a value curve. */ +/** Stop an envelope, leaving the parameter wherever it currently sits. */ export function cancelParamLane(targets: readonly FxParamTarget[]): void { for (const target of targets) { // The value the envelope had reached, not the last one set, which would click. @@ -213,10 +172,6 @@ export function scheduleParamLane( ): void { if (lane.points.length === 0) return; for (const target of targets) { - // Cleared from zero rather than from this instant: a reschedule mid-playback - // lands inside the previous pass's still-running curve, and the field reports - // of that being refused had a cancel at this instant already in place. The - // plan below re-seeds the value here, so clearing costs nothing audible. clearParamLane([target]); if (isConstantLane(lane)) { const value = (target.map ?? identity)(lane.points[0]!.v); diff --git a/packages/core/src/audioAutomation.test.ts b/packages/core/src/audioAutomation.test.ts index ad24477f1c..20b0caad88 100644 --- a/packages/core/src/audioAutomation.test.ts +++ b/packages/core/src/audioAutomation.test.ts @@ -360,7 +360,7 @@ describe("sampling", () => { // A via point pulled out to (5, -3) clamps to (0.999, 0.001) — exactly on the // steady region's edge, where `edge - viaX` is 0 and the conic's weight used // to divide out to Infinity, then NaN a few steps later. NaN reaching - // setValueCurveAtTime silences the node for the rest of the render. + // the AudioParam silences the node for the rest of the render. for (const x of [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]) { const y = shapeProgress(x, { viaX: 5, viaY: -3 }); expect(Number.isFinite(y)).toBe(true); @@ -459,7 +459,7 @@ describe("sampling", () => { }); it("stays monotone for every via point, so a render never sags mid-segment", () => { - // Not cosmetic: a segment is baked into setValueCurveAtTime, and progress + // Not cosmetic: a segment is baked into the AudioParam's ramps, and progress // that dipped backwards is a rising fader audibly dropping. This is the // property the Fritsch-Carlson tangent limit is there to guarantee, so it is // swept rather than spot-checked. diff --git a/packages/core/src/audioAutomation.ts b/packages/core/src/audioAutomation.ts index 1f543c4e6d..ceca239cb7 100644 --- a/packages/core/src/audioAutomation.ts +++ b/packages/core/src/audioAutomation.ts @@ -646,7 +646,7 @@ export function isConstantLane(lane: HfAutomationLane): boolean { /** * Sample a lane onto evenly spaced times, for consumers that want a plain - * curve rather than a breakpoint list: `setValueCurveAtTime`, the render-side + * curve rather than a breakpoint list: the AudioParam scheduler, the render-side * volume envelope, and the lane's own drawing code. */ export function sampleAutomationCurve( diff --git a/packages/core/src/runtime/audioFx.test.ts b/packages/core/src/runtime/audioFx.test.ts index 46a1263b99..05c8bf422f 100644 --- a/packages/core/src/runtime/audioFx.test.ts +++ b/packages/core/src/runtime/audioFx.test.ts @@ -271,9 +271,7 @@ describe("attachElementFxChain", () => { return new SchedNode(); } } - // A gain stage, because its dB-to-linear mapping is what makes the - // scheduler emit a value curve instead of a ramp — and a curve is what a - // `.value` write may not land inside. + // A gain stage, because its dB-to-linear mapping makes the scheduler sample the segment. const chainWith = (freq: number) => ({ version: 1, nodes: [ @@ -282,7 +280,6 @@ describe("attachElementFxChain", () => { ], }); const node = audioEl(chainWith(1000)); - // A bent segment, so the scheduler emits a curve rather than a ramp. node.setAttribute( "data-automation", JSON.stringify({ @@ -397,24 +394,23 @@ describe("attachElementFxChain", () => { describe("a rate change mid-playback", () => { /** Records what was booked and when, without the browser's overlap rules. */ class TimedParam { - curves: { time: number; duration: number }[] = []; - ramps: number[] = []; + spans: { time: number; end?: number }[] = []; value = 0; - setValueAtTime(v: number): void { + setValueAtTime(v: number, t: number): void { this.value = v; + if (this.spans.at(-1)?.end === undefined) this.spans.pop(); + this.spans.push({ time: t }); } linearRampToValueAtTime(v: number, t: number): void { - this.ramps.push(t); this.value = v; - } - setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void { - this.curves.push({ time, duration }); + const span = this.spans.at(-1); + if (span) span.end = t; } cancelScheduledValues(): void {} - cancelAndHoldAtTime(): void {} - /** The last span booked, however the scheduler chose to express it. */ + /** The last span booked: a set and the ramps that follow it. */ last(): { time: number; duration: number } | undefined { - return this.curves.at(-1); + const span = this.spans.filter((s) => s.end !== undefined).at(-1); + return span && { time: span.time, duration: (span.end ?? span.time) - span.time }; } } diff --git a/packages/engine/src/services/audioFxAutomation.browser.test.ts b/packages/engine/src/services/audioFxAutomation.browser.test.ts index 65342d4aea..2018bc61fe 100644 --- a/packages/engine/src/services/audioFxAutomation.browser.test.ts +++ b/packages/engine/src/services/audioFxAutomation.browser.test.ts @@ -4,6 +4,7 @@ import { build } from "esbuild"; import type { Browser } from "puppeteer-core"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { scheduleParamLane } from "../../../core/src/audio/audioFxAutomation.js"; +import { sampleAutomationCurve, type HfAutomationLane } from "../../../core/src/audioAutomation.js"; import { resolveHeadlessShellPath } from "./browserManager.js"; import { closeTestChrome, launchTestChrome } from "./__fixtures__/loopback.js"; @@ -16,6 +17,24 @@ declare global { const chromePath = resolveHeadlessShellPath(); const hasBrowser = chromePath !== undefined && spawnSync(chromePath, ["--version"]).status === 0; +const lane: HfAutomationLane = { + target: "volume", + points: [ + { t: 0, v: 0.1, curve: 0.7 }, + { t: 0.004, v: 0.3, curve: 0.7 }, + { t: 0.008, v: 0.5, curve: 0.7 }, + { t: 0.012, v: 0.7 }, + ], +}; +// The last bend as the scheduler books it: 8 sampled points (its minimum for 4 ms), ramped between. +const bend = sampleAutomationCurve(lane, 0.008, 0.012, 8, "linear"); +const expectedAt = (laneTime: number): number => { + if (laneTime >= 0.012) return 0.7; + const k = ((laneTime - 0.008) / 0.004) * (bend.length - 1); + const i = Math.floor(k); + return bend[i]! + (bend[i + 1]! - bend[i]!) * (k - i); +}; + describe.skipIf(!hasBrowser)("clamped audio automation in WebAudio", () => { let browser: Browser; let scheduler: string; @@ -38,43 +57,37 @@ describe.skipIf(!hasBrowser)("clamped audio automation in WebAudio", () => { }); afterAll(() => closeTestChrome(browser)); - it.each([0, 0.024])("renders the recovered envelope at scheduledAt=%s", async (scheduledAt) => { + it.each([0, 0.024])("renders the envelope, bend kept, at scheduledAt=%s", async (scheduledAt) => { const page = await browser.newPage(); try { await page.addScriptTag({ content: scheduler }); - const samples = await page.evaluate(async (at) => { - const ctx = new OfflineAudioContext(1, 8192, 48000); - const gain = ctx.createGain(); - const source = ctx.createConstantSource(); - source.connect(gain).connect(ctx.destination); - source.start(); - const suspended = ctx.suspend(0.032); - const rendering = ctx.startRendering(); - await suspended; - const firstFrame = Math.round(ctx.currentTime * ctx.sampleRate); - window.hfScheduleParamLane( - [{ param: gain.gain }], - { - target: "volume", - points: [ - { t: 0, v: 0.1, curve: 0.7 }, - { t: 0.004, v: 0.3, curve: 0.7 }, - { t: 0.008, v: 0.5, curve: 0.7 }, - { t: 0.012, v: 0.7 }, - ], - }, - "linear", - { scheduledAt: at, elapsed: 0, rate: 1 }, - ); - await ctx.resume(); - const output = (await rendering).getChannelData(0); - return { firstFrame, values: Array.from(output.slice(firstFrame)) }; - }, scheduledAt); + const samples = await page.evaluate( + async (at, laneArg) => { + const ctx = new OfflineAudioContext(1, 8192, 48000); + const gain = ctx.createGain(); + const source = ctx.createConstantSource(); + source.connect(gain).connect(ctx.destination); + source.start(); + const suspended = ctx.suspend(0.032); + const rendering = ctx.startRendering(); + await suspended; + const firstFrame = Math.round(ctx.currentTime * ctx.sampleRate); + window.hfScheduleParamLane([{ param: gain.gain }], laneArg, "linear", { + scheduledAt: at, + elapsed: 0, + rate: 1, + }); + await ctx.resume(); + const output = (await rendering).getChannelData(0); + return { firstFrame, values: Array.from(output.slice(firstFrame)) }; + }, + scheduledAt, + lane, + ); expect(samples.values.length).toBeGreaterThan(192); const errors = samples.values.map((value, index) => { const laneTime = (samples.firstFrame + index) / 48000 - scheduledAt; - const expected = Math.min(0.7, 0.5 + ((laneTime - 0.008) / 0.004) * 0.2); - return Math.abs(value - expected); + return Math.abs(value - expectedAt(laneTime)); }); expect(Math.max(...errors)).toBeLessThan(0.000001); } finally {