fix(core): give the chorus and phaser LFOs a phase, and unwire them on dispose (#3183)

* fix(studio): drop the unused DomEditSelection import in PropertyPanelFlat

CI caught it on PR #3026 (wa-12-panel-params); a later refactor in the
stack removed the last use of the type here without removing the import.

* fix(studio): close the typecheck and fallow gaps wa-18b-reschedule opened

useAutomationLanes.ts's write() assumed gesture-scoped coalescing and a
preview-only commit that useDomEditAttributeCommits.ts never grew — backported
that option support from its own later commit so the two sides of the API
agree. The paste path and its tests were missing the box selection's v0/v1
bounds a sibling commit added to AutomationSelection. The FX panel's carve
controls still edited the six mechanism numbers (maxCutDb, bands,
intelligibilityBias) after carveProfile() collapsed authoring to one Strength
knob, so those fields no longer existed on HfCarveSettings; UI now edits
strength, and analyseCarveBands is called with carveProfile(strength).

Also closes fallow's complexity, dead-code and duplication findings on this
PR's diff: extracted automationLaneDragMath.ts (pure group/point-move math)
and useAutomationRangeDrag.ts (the marquee-select gesture) out of
useAutomationLaneGestures.ts, pulled a couple of render-loop ternaries and a
resolver into named functions, dropped an export nothing outside its file
used, and shared a step-simplifier between audioCarve's two envelope
builders.

The edge-stretch vs. box-select priority test in TimelineAutomationLane.test
was still pinning the pre-box-select rule (edge wins over a point sitting on
it) that a sibling commit deliberately reversed — a point inside the box is
now selected content, so grabbing it drags the group instead. Updated the
test to the shipped rule instead of the old one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): cap the via conic's weight so an edge-clamped via point can't NaN

A via point pulled out past the segment (viaX: 5, viaY: -3) clamps to
(0.999, 0.001) — exactly on the steady region's edge, where edge - viaX is 0.
viaConic divided by that zero to get an infinite weight, and shapeVia turned
Infinity into NaN a few steps later (Infinity - Infinity in the quadratic
coefficient). NaN reaching setValueCurveAtTime silences the automated
parameter for the rest of the render.

Capped the weight at 1e6 instead of leaving it unbounded — past that point
the arc already reads as touching the via point, so nothing visible is lost.
Also hardened shapeVia's existing denominator guard (`<= 0`) to `!(> 0)`,
since NaN fails the original comparison and fell through it.

Review by Miga (PR #3208).

* fix(studio-server): fingerprint the proactive waveform cache key too

The route already keys the waveform cache on the asset's size and mtime as
well as its path, so a rebuilt-in-place file gets fresh peaks instead of
stale ones. generateWaveformCache — the proactive path that runs on upload —
still called buildWaveformCacheKey with the path alone, so it wrote to a
different key than the route reads from (making the pre-generated cache
never found) and kept the exact collision bug this fingerprint exists to fix
on its own path.

Review by Miga (PR #3211).

* style(docs): run oxfmt on the /hyperframes-audio skill docs

Table column widths had drifted out of alignment with oxfmt's own rules,
failing format:check and blocking the Preflight gate every downstream
branch inherits. Whitespace only, no content change.

* fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration

\b treats `_` as a word character, so \bbed\b never matched bed_01,
music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap —
an underscore-separated bed classified as "unknown" and could end up offered
as its own carve source. Replaced the short hints with a boundary that
actually excludes letters and digits on both sides.

clipsOverlap computed end = start + duration without guarding sign, so a
negative duration put end before start — an interval that does not describe
anything, and one specific case showed it silently dropping a real overlap
(a shorter, earlier broken end rejected a clip that genuinely contained the
point). Duration clamps to zero instead: a clip cannot un-play time, and a
zero-length clip at its start is the sane reading of "duration nobody wrote
down as positive."

Review by Miga (PR #3212).

* fix(studio): widen PropertyPanel's resetModules render timeout again

The 20s margin (already once widened for the same reason) is timing out in
CI's full-monorepo Test run — the resetModules()+fresh-import render this
test needs is uncached and competes with every other package's test suite
for the same worker pool, and the same test passes in well under 2s
standalone. Went to 45s rather than re-tuning to whatever number happens to
clear the current CI load, since that number moves every time CI gains a
package.

* fix(studio): stop the single-candidate auto-apply carve firing twice

Two auto-apply effects both fire when sourceOptions.length === 1: the
multi-candidate effect only guards length === 0, so a single candidate
passes it too, and the single-candidate effect passes its own guard right
after — both compute the same sources list and both call setCarve, so the
common case (one narrator, one bed) triggered two decodes, two FFT runs, and
two concurrent attribute writes for one decision.

The multi-candidate effect now defers to its sibling for exactly one
candidate, which already has its own detailed handling for that case.

Review by Miga (PR #3213).

* feat(core): carve against every voice over a bed, always (#3212)

* feat(core): carve against every voice over a bed, always dynamically

A bed usually runs under a whole sequence — a narrator, an interview answer, a
second presenter — and carving against one of them left the others fighting it.
`source` becomes `sources`, and `mixCarveSources` sums every voice onto the BED's
clock before anything is measured. That is what keeps one analysis sufficient: the
chain is fixed, so there is no per-voice filter to switch between, and bands drawn
from all the speech there is with envelopes that rise wherever any of it happens
answer the actual question — where and when is speech masking this bed.

Summed rather than averaged: two people talking at once mask more than either
alone. Audio before the bed starts is dropped rather than folded in at zero, since
it plays over nothing and shifting it would put a cut where there is no voice.

`dynamic` is gone. A fixed depth thins the bed through every pause, and once both
have been heard there is no reason to want it, so every carve follows the speech.

Two helpers the panel and the headless script now share instead of each carrying a
copy — two definitions of "what does this name suggest" drift, and then the two
disagree about which track is the voice:

- `classifyAudioName` reads a track's kind from its id and filename together.
  `unknown` is deliberately common: treating an unrecognised name as "not a voice"
  would hide the one track somebody needs to pick.
- `clipsOverlap` keeps out a voice that never plays while the bed does. An unwritten
  duration counts as unbounded, not zero — refusing a clip whose length the
  composition leaves to the media would drop the commonest case there is.

Files written before this still load: a single `source` reads as a one-voice list,
a stored `dynamic` is ignored, and an absent attribute means the defaults whole.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(core): stop \b from missing underscore-separated names, guard clipsOverlap's negative duration

\b treats `_` as a word character, so \bbed\b never matched bed_01,
music_bed_loop, or theme_song, and \bvo\b/\bvox\b/\btts\b had the same gap —
an underscore-separated bed classified as "unknown" and could end up offered
as its own carve source. Replaced the short hints with a boundary that
actually excludes letters and digits on both sides.

clipsOverlap computed end = start + duration without guarding sign, so a
negative duration put end before start — an interval that does not describe
anything, and one specific case showed it silently dropping a real overlap
(a shorter, earlier broken end rejected a clip that genuinely contained the
point). Duration clamps to zero instead: a clip cannot un-play time, and a
zero-length clip at its start is the sane reading of "duration nobody wrote
down as positive."

Review by Miga (PR #3212).

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(studio): port the carve UI off the removed source/dynamic fields

#3212 (accidentally squash-merged into this branch instead of main) changed
HfCarveSettings from a single `source` + `dynamic` toggle to a `sources`
list with dynamic mode removed outright — the multi-voice UI consumer that
goes with that shape lands in the very next PR, so this branch was left with
a type that no longer matched its own code.

Minimal port, not the multi-voice redesign that PR does properly: the
"Listen to" picker and analyse() treat sources[0] as the one voice this UI
still understands, and every dynamic-mode branch (the automated envelope
lanes, the toggle, the checkbox) is gone along with the field — a carve is
now always the static value the analysis computes, matching what the type
change made permanent. Test suite trimmed the same way: the automation-lane
and toggle tests covered behavior that no longer exists.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vance Ingalls
2026-08-13 08:52:57 -07:00
committed by GitHub
co-authored by Claude Opus 5
parent 2f97fc2b89
commit b839dbd2cc
15 changed files with 522 additions and 172 deletions
+107 -15
View File
@@ -25,13 +25,17 @@ class FakeNode {
Q = new FakeParam();
gain = new FakeParam();
delayTime = new FakeParam();
playbackRate = new FakeParam();
loop = false;
type = "";
curve: Float32Array | null = null;
oversample = "none";
buffer: unknown = null;
buffer: FakeBuffer | null = null;
normalize = true;
port = { postMessage: (m: unknown) => this.messages.push(m) };
messages: unknown[] = [];
/** `start(when, offset)` — the offset is the LFO's phase, so it is asserted. */
startArgs: (number | undefined)[] | null = null;
constructor(public kind: string) {}
connect(next: FakeNode): FakeNode {
this.connections.push(next);
@@ -40,10 +44,23 @@ class FakeNode {
disconnect(): void {
this.disconnected = true;
}
start(): void {}
start(...args: (number | undefined)[]): void {
this.startArgs = args;
}
stop(): void {}
}
/** One channel, kept across `getChannelData` calls so what is written can be read. */
class FakeBuffer {
private data: Float32Array;
constructor(public length: number) {
this.data = new Float32Array(length);
}
getChannelData(): Float32Array {
return this.data;
}
}
class FakeCtx {
sampleRate = 48000;
created: FakeNode[] = [];
@@ -67,6 +84,9 @@ class FakeCtx {
createOscillator() {
return this.make("osc");
}
createBufferSource() {
return this.make("bufferSource");
}
createWaveShaper() {
return this.make("waveshaper");
}
@@ -74,7 +94,7 @@ class FakeCtx {
return this.make("convolver");
}
createBuffer(_c: number, length: number) {
return { length, getChannelData: () => new Float32Array(length) };
return new FakeBuffer(length);
}
}
@@ -350,19 +370,91 @@ describe("levels and per-channel state", () => {
});
it("sets the phaser LFO waveform it declares", () => {
const ctx = new FakeCtx();
buildFxNode(ctx as unknown as BaseAudioContext, "phaser", {
...defaultAudioFxParams("phaser"),
type: "0",
// A quarter of the way through the cycle both waveforms peak at 1, so the
// eighth is where they part: a sine is at sin(π/4), a triangle halfway up.
const eighth = (c: FakeCtx): number => {
const buffer = c.created.find((n) => n.kind === "bufferSource")?.buffer;
if (!buffer) throw new Error("no LFO buffer");
return buffer.getChannelData()[Math.round(buffer.length / 8)] ?? 0;
};
const build = (type: string): FakeCtx => {
const c = new FakeCtx();
buildFxNode(c as unknown as BaseAudioContext, "phaser", {
...defaultAudioFxParams("phaser"),
type,
});
return c;
};
expect(eighth(build("0"))).toBeCloseTo(0.5, 3);
expect(eighth(build("1"))).toBeCloseTo(Math.SQRT1_2, 3);
});
/**
* The waveform is baked into a buffer at construction, so pushing a type change
* into the running graph would be a no-op — preview would keep sweeping on a
* triangle while the render used the sine the attribute now says.
*/
it("rebuilds a phaser when its LFO waveform changes", () => {
const phaser = (params: Record<string, number | string>): HfAudioFxChain => ({
version: 1,
nodes: [
{
type: "phaser",
enabled: true,
params: { ...defaultAudioFxParams("phaser"), type: "0", ...params },
},
],
});
const osc = ctx.created.find((n) => n.kind === "osc");
expect(osc?.type).toBe("triangle");
const ctx2 = new FakeCtx();
buildFxNode(ctx2 as unknown as BaseAudioContext, "phaser", {
...defaultAudioFxParams("phaser"),
type: "1",
});
expect(ctx2.created.find((n) => n.kind === "osc")?.type).toBe("sine");
const built = buildFxChain(asCtx(ctx()), phaser({}));
expect(built.update(phaser({ type: "1" }))).toBe(false);
// Everything else about a phaser still updates in place.
const other = buildFxChain(asCtx(ctx()), phaser({}));
expect(other.update(phaser({ speed: 2 }))).toBe(true);
});
/**
* An LFO's phase is the whole reason it is a looping buffer rather than an
* OscillatorNode, whose phase is zero at `start()` and cannot be set.
*
* Preview rebuilds the graph mid-play — a seek, a scrub, any structural edit —
* and an oscillator restarted there put the chorus at the top of its sweep
* wherever the playhead happened to be, so preview disagreed with the render
* and with itself across an edit.
*/
it("starts a modulated effect's LFO at the phase the clip has reached", () => {
// 3.5 s at 2 Hz is seven whole cycles: back at phase zero.
const whole = ctx();
buildFxNode(asCtx(whole), "chorus", { ...defaultAudioFxParams("chorus"), speed: 2 }, 3.5);
expect(whole.created.find((n) => n.kind === "bufferSource")?.startArgs?.[1]).toBeCloseTo(0, 6);
// 3.6 s at 2 Hz is seven cycles and a fifth.
const part = ctx();
buildFxNode(asCtx(part), "chorus", { ...defaultAudioFxParams("chorus"), speed: 2 }, 3.6);
const src = part.created.find((n) => n.kind === "bufferSource");
expect(src?.startArgs?.[1]).toBeCloseTo(0.2, 6);
expect(src?.loop).toBe(true);
// One second of waveform: the rate reads in Hz, so a speed lane needs no map.
expect(src?.playbackRate.value).toBeCloseTo(2, 6);
});
/**
* A source node is not retired by disconnecting what it feeds. The chorus and
* phaser stopped their LFO and left it out of the nodes they disconnect, so
* every rebuild that dropped one left a modulator still wired to the delay or
* the allpass bank it had been driving.
*/
it("unwires a modulated effect's LFO when the effect is disposed", () => {
for (const type of ["chorus", "phaser"]) {
const c = ctx();
buildFxNode(asCtx(c), type, defaultAudioFxParams(type)).dispose();
const lfo = c.created.find((node) => node.kind === "bufferSource");
expect(lfo?.disconnected, `${type} left its LFO connected`).toBe(true);
}
});
it("starts the LFO at zero for a render, which always begins at the clip's start", () => {
const c = ctx();
buildFxNode(asCtx(c), "phaser", defaultAudioFxParams("phaser"));
expect(c.created.find((n) => n.kind === "bufferSource")?.startArgs?.[1]).toBe(0);
});
it("rebuilds a one-pole filter when its cutoff moves", () => {
+108 -31
View File
@@ -83,13 +83,86 @@ export interface FxNodeHandle {
dispose(): void;
}
type Builder = (ctx: BaseAudioContext, p: HfAudioFxParamValues) => FxNodeHandle;
/**
* `elapsed` is the clip-relative time, in seconds, the graph is being built at.
*
* Zero for the render, which always starts a clip's audio from its first sample,
* and zero for a preview attached before playback. It is non-zero in the one case
* that used to be wrong: preview rebuilding the graph mid-play — a seek, a scrub,
* or any structural edit — where an LFO restarting from phase 0 made preview
* disagree with the render, and with itself across an edit.
*/
type Builder = (ctx: BaseAudioContext, p: HfAudioFxParamValues, elapsed: number) => FxNodeHandle;
const n = (v: number | string | undefined): number => (typeof v === "number" ? v : Number(v ?? 0));
/** Milliseconds on the knob, seconds on the AudioParam. */
const msToSec = (v: number): number => v / 1000;
/**
* An LFO with a settable phase.
*
* An OscillatorNode cannot have one: its phase is zero at `start()`, and
* `start(when)` clamps a past `when` to now. So the modulator is one cycle of the
* waveform in a looping buffer instead, where `start(when, offset)` *is* a phase
* control.
*
* The buffer holds exactly one second, so it plays at 1 Hz at the default rate
* and `playbackRate` reads directly in Hz — which is what the `speed` knob is in,
* and what an automation lane aimed at it writes, so neither needs a mapping.
*
* Phase is taken as `elapsed × speed`, which is exact for the constant speed this
* is built with. A lane that sweeps `speed` advances the real phase by its
* integral, so a graph rebuilt mid-sweep resumes fractionally off — smaller than
* the whole-cycle error this replaces, and not worth integrating a curve for.
*/
function lfoSource(
ctx: BaseAudioContext,
wave: "sine" | "triangle",
speed: number,
elapsed: number,
): AudioBufferSourceNode {
const length = Math.max(1, Math.round(ctx.sampleRate));
const buffer = ctx.createBuffer(1, length, ctx.sampleRate);
const cycle = buffer.getChannelData(0);
for (let i = 0; i < length; i++) {
const phase = i / length;
// Both start at zero and rise, the convention an OscillatorNode uses, so a
// render — which builds at elapsed 0 — is unmoved by this change.
cycle[i] =
wave === "sine"
? Math.sin(2 * Math.PI * phase)
: 4 * Math.abs(((phase + 0.75) % 1) - 0.5) - 1;
}
const src = ctx.createBufferSource();
src.buffer = buffer;
src.loop = true;
src.playbackRate.value = speed;
// A negative `offset` throws, and `elapsed` is only trusted to be a number.
const offset = ((((elapsed * speed) % 1) + 1) % 1) * (length / ctx.sampleRate);
src.start(typeof ctx.currentTime === "number" ? ctx.currentTime : 0, offset);
return src;
}
/**
* Retire an LFO: stopped *and* unwired.
*
* Both halves. The old oscillators were stopped and left in their builder's
* dispose list — so every chain rebuild that dropped a chorus or a phaser left a
* modulator still connected to the delay or the allpass bank it had been
* driving. Nothing audible came out of it, because the shell around it was
* disconnected, but the nodes stayed reachable and a session of edits to a
* modulated track accumulated them. Same shape as the worklet leak above.
*/
function retireLfo(src: AudioBufferSourceNode): void {
try {
src.stop();
} catch {
/* already stopped */
}
src.disconnect();
}
/** A wet/dry pair: the dry side is whatever the wet side is not. */
function mixTargets(wet: AudioParam, dry: AudioParam): FxParamTarget[] {
return [{ param: wet }, { param: dry, map: (v) => 1 - v }];
@@ -276,22 +349,21 @@ const delayFeedback: Builder = (ctx, p) => {
};
};
const chorusLfo: Builder = (ctx, p) => {
const chorusLfo: Builder = (ctx, p, elapsed) => {
const input = ctx.createGain();
const out = ctx.createGain();
const dl = ctx.createDelay(0.5);
const lfo = ctx.createOscillator();
const lfo = lfoSource(ctx, "sine", n(p.speed), elapsed);
const depth = ctx.createGain();
const wet = ctx.createGain();
const dry = ctx.createGain();
lfo.connect(depth).connect(dl.delayTime);
input.connect(dl).connect(wet).connect(out);
input.connect(dry).connect(out);
lfo.start();
const apply = (v: HfAudioFxParamValues): void => {
dl.delayTime.value = n(v.delay) / 1000;
depth.gain.value = n(v.depth) / 1000;
lfo.frequency.value = n(v.speed);
lfo.playbackRate.value = n(v.speed);
setWetDryMix(wet, dry, n(v.mix));
};
apply(p);
@@ -302,15 +374,12 @@ const chorusLfo: Builder = (ctx, p) => {
automation: {
delay: [{ param: dl.delayTime, map: msToSec }],
depth: [{ param: depth.gain, map: msToSec }],
speed: [{ param: lfo.frequency }],
// One second of waveform, so the rate is the frequency in Hz the knob names.
speed: [{ param: lfo.playbackRate }],
mix: mixTargets(wet.gain, dry.gain),
},
dispose: () => {
try {
lfo.stop();
} catch {
/* already stopped */
}
retireLfo(lfo);
[input, out, dl, depth, wet, dry].forEach((x) => x.disconnect());
},
};
@@ -318,7 +387,7 @@ const chorusLfo: Builder = (ctx, p) => {
const PHASER_STAGES = 6;
const allpassPhaser: Builder = (ctx, p) => {
const allpassPhaser: Builder = (ctx, p, elapsed) => {
const input = ctx.createGain();
const out = ctx.createGain();
// aphaser's in_gain/out_gain trim the signal entering and leaving the effect.
@@ -327,7 +396,12 @@ const allpassPhaser: Builder = (ctx, p) => {
// track level.
const inTrim = ctx.createGain();
const outTrim = ctx.createGain();
const lfo = ctx.createOscillator();
// aphaser's type 0 is triangular, 1 sinusoidal. The builder once left this
// unset, so the declared default ("Triangular") was silently a sine. The
// waveform is baked into the LFO's buffer, so switching it is a shape change
// that rebuilds the chain rather than a value pushed into the running graph —
// see `shapeOf`.
const lfo = lfoSource(ctx, String(p.type) === "1" ? "sine" : "triangle", n(p.speed), elapsed);
const depth = ctx.createGain();
const wet = ctx.createGain();
const dry = ctx.createGain();
@@ -344,11 +418,6 @@ const allpassPhaser: Builder = (ctx, p) => {
stages.push(ap);
}
lfo.connect(depth);
// aphaser's type 0 is triangular, 1 sinusoidal. The builder never set this, so
// the declared default ("Triangular") was silently a sine. An OscillatorNode
// has no triangle-with-the-same-phase primitive to switch to, so triangle is
// the node's own "triangle" type.
lfo.start();
node.connect(wet).connect(outTrim);
inTrim.connect(dry).connect(outTrim);
outTrim.connect(out);
@@ -358,8 +427,7 @@ const allpassPhaser: Builder = (ctx, p) => {
const centre = 1000 / Math.max(0.1, n(v.delay));
for (const ap of stages) ap.frequency.value = centre;
depth.gain.value = centre * n(v.decay);
lfo.frequency.value = n(v.speed);
lfo.type = String(v.type) === "1" ? "sine" : "triangle";
lfo.playbackRate.value = n(v.speed);
inTrim.gain.value = n(v.in_gain);
outTrim.gain.value = n(v.out_gain);
// Summed at unity: the sweep is the effect, not a blend control.
@@ -374,7 +442,7 @@ const allpassPhaser: Builder = (ctx, p) => {
// `delay` and `decay` set the sweep centre, which feeds every stage's
// frequency at once — not one knob, one param — so they stay unautomated.
automation: {
speed: [{ param: lfo.frequency }],
speed: [{ param: lfo.playbackRate }],
// The trims, not wet/dry. apply() drives inTrim/outTrim from these knobs
// and pins wet and dry to 1 — so a lane aimed at wet/dry modulated a
// constant and left the trim frozen, and the next values-only edit slammed
@@ -384,11 +452,7 @@ const allpassPhaser: Builder = (ctx, p) => {
out_gain: [{ param: outTrim.gain }],
},
dispose: () => {
try {
lfo.stop();
} catch {
/* already stopped */
}
retireLfo(lfo);
[input, out, inTrim, outTrim, depth, wet, dry, ...stages].forEach((x) => x.disconnect());
},
};
@@ -456,17 +520,18 @@ export function buildFxNode(
ctx: BaseAudioContext,
type: string,
params: HfAudioFxParamValues,
elapsed = 0,
): FxNodeHandle {
const def = getAudioFxDef(type);
if (!def) throw new Error(`Unknown effect type: ${type}`);
const resolved = normalizeAudioFxParams(type, params);
// One-pole is a different node type, not a different parameter value.
if ((type === "highpass" || type === "lowpass") && String(resolved.poles) === "1") {
return onePoleBuilder(type)(ctx, resolved);
return onePoleBuilder(type)(ctx, resolved, elapsed);
}
const builder = BUILDERS[def.web];
if (!builder) throw new Error(`No Web Audio builder for ${def.web}`);
return builder(ctx, resolved);
return builder(ctx, resolved, elapsed);
}
export interface FxChainHandle {
@@ -495,7 +560,11 @@ function shapeOf(chain: HfAudioFxChain): string {
// being pushed into a no-op updater — which is what let preview keep
// filtering at the old frequency while the render used the new one.
const fixedFreq = String(p.poles) === "1" ? `@${p.frequency}` : "";
return `${node.type}${poles}${fixedFreq}`;
// The phaser's LFO waveform is baked into a buffer at construction, for the
// same reason: pushed into the running graph it would be a no-op, and
// preview would keep sweeping on a triangle while the render used a sine.
const wave = node.type === "phaser" ? `~${p.type}` : "";
return `${node.type}${poles}${fixedFreq}${wave}`;
})
.join("|");
}
@@ -503,15 +572,23 @@ function shapeOf(chain: HfAudioFxChain): string {
/**
* Build the whole chain in series. Returns a handle whose `input`/`output` can
* be spliced into any graph; an empty chain yields a pass-through.
*
* `elapsed` is where in the clip this is being built — see `Builder`. It only
* reaches the modulated effects, and only matters when the graph is built after
* the audio has already started.
*/
export function buildFxChain(ctx: BaseAudioContext, chain: HfAudioFxChain): FxChainHandle {
export function buildFxChain(
ctx: BaseAudioContext,
chain: HfAudioFxChain,
elapsed = 0,
): FxChainHandle {
const input = ctx.createGain();
const output = ctx.createGain();
const handles: { id?: string; type: string; handle: FxNodeHandle }[] = [];
let tail: AudioNode = input;
for (const node of enabledAudioFxNodes(chain)) {
const handle = buildFxNode(ctx, node.type, node.params ?? {});
const handle = buildFxNode(ctx, node.type, node.params ?? {}, elapsed);
tail.connect(handle.input);
tail = handle.output;
handles.push({ ...(node.id ? { id: node.id } : {}), type: node.type, handle });