Skip to content

Write HTML. Render video. Built for agents.

feat(core): Web Audio graphs for the FX registry (#3020)

Vance Ingalls2350f9b69b10
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 0fcb2140f9..612b17cde1 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -146,6 +146,17 @@
"file": "packages/studio/src/utils/studioHelpers.ts",
"exports": ["resolveDroppedAssetDimensions"],
},
+ // Audio FX worklets sit near the bottom of the audio stack: the worklet
+ // source and its test reset are consumed by the runtime and engine PRs
+ // upstack, so a per-PR audit against the merge base sees them as unused.
+ {
+ "file": "packages/core/src/audio/audioFxWorklets.ts",
+ "exports": ["AUDIO_FX_WORKLET_SOURCE", "__resetAudioFxWorkletsForTests"],
+ },
+ {
+ "file": "packages/core/src/audio/audioFxGraph.ts",
+ "exports": ["ensureAudioFxWorklets"],
+ },
// drawElementService is the bottom of the fast-capture Graphite stack
// (#1917): its consumers (frameCapture in #1919) land two PRs upstack, so
// a per-PR audit diffing against the merge base sees these exports as
diff --git a/packages/core/src/audio/audioFxGraph.test.ts b/packages/core/src/audio/audioFxGraph.test.ts
new file mode 100644
index 0000000000..61cf137315
--- /dev/null
+++ b/packages/core/src/audio/audioFxGraph.test.ts
@@ -0,0 +1,343 @@
+// @vitest-environment happy-dom
+import { describe, expect, it } from "vitest";
+import { defaultAudioFxParams, HF_AUDIO_FX, type HfAudioFxChain } from "../audioFx.js";
+import {
+ buildFxChain,
+ buildFxNode,
+ chainNeedsWorklets,
+ synthesizeReverbImpulse,
+} from "./audioFxGraph.js";
+
+/**
+ * happy-dom has no Web Audio, and a real AudioContext needs a browser. These
+ * cover the graph wiring: which nodes get made, how they connect, and when an
+ * update can happen in place instead of forcing a rebuild. Whether each graph
+ * *sounds* like its FFmpeg counterpart is a separate measurement — that is the
+ * parity harness's job, and it runs in a real browser.
+ */
+class FakeParam {
+ constructor(public value = 0) {}
+}
+class FakeNode {
+ connections: FakeNode[] = [];
+ disconnected = false;
+ frequency = new FakeParam();
+ Q = new FakeParam();
+ gain = new FakeParam();
+ delayTime = new FakeParam();
+ type = "";
+ curve: Float32Array | null = null;
+ oversample = "none";
+ buffer: unknown = null;
+ normalize = true;
+ port = { postMessage: (m: unknown) => this.messages.push(m) };
+ messages: unknown[] = [];
+ constructor(public kind: string) {}
+ connect(next: FakeNode): FakeNode {
+ this.connections.push(next);
+ return next;
+ }
+ disconnect(): void {
+ this.disconnected = true;
+ }
+ start(): void {}
+ stop(): void {}
+}
+
+class FakeCtx {
+ sampleRate = 48000;
+ created: FakeNode[] = [];
+ private make(kind: string): FakeNode {
+ const node = new FakeNode(kind);
+ this.created.push(node);
+ return node;
+ }
+ createGain() {
+ return this.make("gain");
+ }
+ createBiquadFilter() {
+ return this.make("biquad");
+ }
+ createIIRFilter() {
+ return this.make("iir");
+ }
+ createDelay() {
+ return this.make("delay");
+ }
+ createOscillator() {
+ return this.make("osc");
+ }
+ createWaveShaper() {
+ return this.make("waveshaper");
+ }
+ createConvolver() {
+ return this.make("convolver");
+ }
+ createBuffer(_c: number, length: number) {
+ return { length, getChannelData: () => new Float32Array(length) };
+ }
+}
+
+// AudioWorkletNode is constructed directly, not via a context factory, so the
+// instances are recorded here rather than in FakeCtx.created.
+const workletNodes: FakeWorkletNode[] = [];
+class FakeWorkletNode extends FakeNode {
+ constructor(
+ _ctx: unknown,
+ public name: string,
+ public options: { processorOptions: unknown },
+ ) {
+ super("worklet");
+ workletNodes.push(this);
+ }
+}
+(globalThis as unknown as { AudioWorkletNode: unknown }).AudioWorkletNode = FakeWorkletNode;
+
+const ctx = (): FakeCtx => new FakeCtx();
+const asCtx = (c: FakeCtx) => c as unknown as BaseAudioContext;
+const chain = (...types: string[]): HfAudioFxChain => ({
+ version: 1,
+ nodes: types.map((t) => ({ type: t, enabled: true, params: defaultAudioFxParams(t) })),
+});
+
+describe("buildFxNode", () => {
+ it("builds a node for every effect in the registry", () => {
+ for (const def of HF_AUDIO_FX) {
+ const c = ctx();
+ expect(
+ () => buildFxNode(asCtx(c), def.id, defaultAudioFxParams(def.id)),
+ `${def.id} failed to build`,
+ ).not.toThrow();
+ }
+ });
+
+ it("rejects an unknown effect", () => {
+ expect(() => buildFxNode(asCtx(ctx()), "nope", {})).toThrow(/Unknown effect/);
+ });
+
+ it("uses a two-pole biquad by default and a one-pole IIR when asked", () => {
+ const two = ctx();
+ buildFxNode(asCtx(two), "highpass", { ...defaultAudioFxParams("highpass"), poles: "2" });
+ expect(two.created.some((n) => n.kind === "biquad")).toBe(true);
+ expect(two.created.some((n) => n.kind === "iir")).toBe(false);
+
+ const one = ctx();
+ buildFxNode(asCtx(one), "highpass", { ...defaultAudioFxParams("highpass"), poles: "1" });
+ expect(one.created.some((n) => n.kind === "iir")).toBe(true);
+ });
+
+ it("applies parameters to the biquad rather than leaving defaults", () => {
+ const c = ctx();
+ buildFxNode(asCtx(c), "peaking", { frequency: 750, gain: -9, q: 3 });
+ const bq = c.created.find((n) => n.kind === "biquad")!;
+ expect(bq.type).toBe("peaking");
+ expect(bq.frequency.value).toBe(750);
+ expect(bq.gain.value).toBe(-9);
+ expect(bq.Q.value).toBe(3);
+ });
+
+ it("clamps an out-of-range value on the way into the graph", () => {
+ const c = ctx();
+ buildFxNode(asCtx(c), "peaking", { frequency: 10_000_000, gain: 0, q: 1 });
+ expect(c.created.find((n) => n.kind === "biquad")!.frequency.value).toBe(20000);
+ });
+
+ it("sends worklet parameters through the port on update", () => {
+ workletNodes.length = 0;
+ const c = ctx();
+ const h = buildFxNode(asCtx(c), "compressor", defaultAudioFxParams("compressor"));
+ expect(workletNodes).toHaveLength(1);
+ expect(workletNodes[0]!.name).toBe("hf-compressor");
+ h.update({ ...defaultAudioFxParams("compressor"), threshold: -30 });
+ // Turning a dial re-parameterises the running processor instead of
+ // rebuilding it, which is what keeps the knob-to-ear loop immediate.
+ expect(workletNodes[0]!.messages).toHaveLength(1);
+ expect(workletNodes[0]!.messages[0]).toMatchObject({ threshold: -30 });
+ });
+
+ it("rebuilds the saturation curve for the selected shape", () => {
+ const c = ctx();
+ buildFxNode(asCtx(c), "saturate", { ...defaultAudioFxParams("saturate"), type: "hard" });
+ const ws = c.created.find((n) => n.kind === "waveshaper")!;
+ expect(ws.curve).toBeInstanceOf(Float32Array);
+ // A hard clip saturates to the threshold and stays flat at the extremes.
+ expect(ws.curve!.at(-1)).toBeCloseTo(ws.curve![ws.curve!.length - 2]!, 6);
+ });
+});
+
+describe("buildFxChain", () => {
+ it("passes audio straight through for an empty chain", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), { version: 1, nodes: [] });
+ expect(h.input.connect).toBeDefined();
+ expect((h.input as unknown as FakeNode).connections).toContain(h.output);
+ });
+
+ it("chains effects in order", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), chain("highpass", "peaking"));
+ // input -> highpass -> peaking -> output, so input reaches exactly one node.
+ expect((h.input as unknown as FakeNode).connections).toHaveLength(1);
+ expect(c.created.filter((n) => n.kind === "biquad")).toHaveLength(2);
+ });
+
+ it("skips bypassed nodes", () => {
+ const c = ctx();
+ buildFxChain(asCtx(c), {
+ version: 1,
+ nodes: [
+ { type: "peaking", enabled: false, params: defaultAudioFxParams("peaking") },
+ { type: "lowpass", enabled: true, params: defaultAudioFxParams("lowpass") },
+ ],
+ });
+ expect(c.created.filter((n) => n.kind === "biquad")).toHaveLength(1);
+ });
+
+ it("updates in place when only values changed", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), chain("peaking"));
+ const before = c.created.length;
+ const ok = h.update({
+ version: 1,
+ nodes: [{ type: "peaking", enabled: true, params: { frequency: 2000, gain: 5, q: 2 } }],
+ });
+ expect(ok).toBe(true);
+ expect(c.created.length).toBe(before); // nothing rebuilt
+ expect(c.created.find((x) => x.kind === "biquad")!.frequency.value).toBe(2000);
+ });
+
+ it("reports that a rebuild is needed when the chain shape changes", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), chain("peaking"));
+ expect(h.update(chain("peaking", "lowpass"))).toBe(false);
+ expect(h.update(chain("lowpass"))).toBe(false);
+ });
+
+ it("treats a pole-count change as a rebuild, since it changes the node type", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), chain("highpass"));
+ expect(
+ h.update({
+ version: 1,
+ nodes: [
+ {
+ type: "highpass",
+ enabled: true,
+ params: { ...defaultAudioFxParams("highpass"), poles: "1" },
+ },
+ ],
+ }),
+ ).toBe(false);
+ });
+
+ it("treats bypassing a node as a shape change", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), chain("peaking", "lowpass"));
+ expect(
+ h.update({
+ version: 1,
+ nodes: [
+ { type: "peaking", enabled: true, params: defaultAudioFxParams("peaking") },
+ { type: "lowpass", enabled: false, params: defaultAudioFxParams("lowpass") },
+ ],
+ }),
+ ).toBe(false);
+ });
+
+ it("disconnects everything it made on dispose", () => {
+ const c = ctx();
+ const h = buildFxChain(asCtx(c), chain("delay"));
+ h.dispose();
+ expect(c.created.every((n) => n.disconnected)).toBe(true);
+ });
+});
+
+describe("chainNeedsWorklets", () => {
+ it("is true only when the chain contains a worklet-backed effect", () => {
+ expect(chainNeedsWorklets(chain("peaking", "delay"))).toBe(false);
+ expect(chainNeedsWorklets(chain("peaking", "compressor"))).toBe(true);
+ });
+});
+
+describe("synthesizeReverbImpulse", () => {
+ it("is deterministic for the same room, so preview and render convolve the same tail", () => {
+ const a = synthesizeReverbImpulse(48000, 0.7, 0.5);
+ const b = synthesizeReverbImpulse(48000, 0.7, 0.5);
+ expect(Array.from(a.slice(0, 64))).toEqual(Array.from(b.slice(0, 64)));
+ });
+
+ it("varies with the room and decays to near-silence", () => {
+ const small = synthesizeReverbImpulse(48000, 0.1, 0.5);
+ const large = synthesizeReverbImpulse(48000, 1.0, 0.5);
+ expect(large.length).toBeGreaterThan(small.length);
+ const tail = large.subarray(large.length - 128);
+ expect(Math.max(...Array.from(tail, Math.abs))).toBeLessThan(0.01);
+ });
+});
+
+describe("levels and per-channel state", () => {
+ const energy = (ir: Float32Array): number => {
+ let e = 0;
+ for (const v of ir) e += v * v;
+ return Math.sqrt(e);
+ };
+
+ it("normalises the reverb impulse, so adding one does not clip the mix", () => {
+ // A ConvolverNode applies the impulse's gain whole (normalize is off so the
+ // room is deterministic). Raw decaying noise ran to +33 dB at the registry
+ // default, which put the wet path ~24 dB over dry at wet: 0.35.
+ for (const [size, damping] of [
+ [0.7, 0.5],
+ [1, 0],
+ [0, 1],
+ [0.5, 0.5],
+ ]) {
+ expect(energy(synthesizeReverbImpulse(48000, size, damping))).toBeCloseTo(1, 5);
+ }
+ });
+
+ it("keeps a phaser at unity, rather than summing its two gains above it", () => {
+ // in_gain/out_gain trim what enters and leaves the effect; wired as a wet/dry
+ // pair their defaults summed to 1.14, so inserting a phaser raised the level.
+ const ctx = new FakeCtx();
+ buildFxNode(ctx as unknown as BaseAudioContext, "phaser", defaultAudioFxParams("phaser"));
+ const gains = ctx.created.filter((n) => n.kind === "gain").map((n) => n.gain.value);
+ // The wet and dry legs are summed at unity; the trims carry the knob values.
+ expect(gains.filter((g) => g === 1).length).toBeGreaterThanOrEqual(2);
+ });
+
+ it("sets the phaser LFO waveform it declares", () => {
+ const ctx = new FakeCtx();
+ buildFxNode(ctx as unknown as BaseAudioContext, "phaser", {
+ ...defaultAudioFxParams("phaser"),
+ type: "0",
+ });
+ 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");
+ });
+
+ it("rebuilds a one-pole filter when its cutoff moves", () => {
+ // Its coefficients are fixed at construction, so a cutoff change cannot be
+ // pushed into the running graph — preview kept filtering at the old
+ // frequency while the render used the new one.
+ const ctx = new FakeCtx() as unknown as BaseAudioContext;
+ const chain = (frequency: number): HfAudioFxChain => ({
+ version: 1,
+ nodes: [{ type: "highpass", enabled: true, params: { frequency, q: 0.707, poles: "1" } }],
+ });
+ const built = buildFxChain(ctx, chain(300));
+ expect(built.update(chain(2000))).toBe(false);
+ // A two-pole filter is a BiquadFilterNode and still updates in place.
+ const twoPole = (frequency: number): HfAudioFxChain => ({
+ version: 1,
+ nodes: [{ type: "highpass", enabled: true, params: { frequency, q: 0.707, poles: "2" } }],
+ });
+ expect(buildFxChain(ctx, twoPole(300)).update(twoPole(2000))).toBe(true);
+ });
+});
diff --git a/packages/core/src/audio/audioFxGraph.ts b/packages/core/src/audio/audioFxGraph.ts
new file mode 100644
index 0000000000..ab8dc34101
--- /dev/null
+++ b/packages/core/src/audio/audioFxGraph.ts
@@ -0,0 +1,435 @@
+/**
+ * Builds the Web Audio graph for an FX chain, one builder per `web` id in the
+ * core registry.
+ *
+ * Every node exposes `update`, so turning a dial re-parameterises the running
+ * graph instead of rebuilding it. That is the whole point of previewing in the
+ * browser: an AudioParam change lands on the next 128-sample render quantum,
+ * about 2.7 ms at 48 kHz, so the knob-to-ear loop is immediate.
+ */
+
+import {
+ getAudioFxDef,
+ normalizeAudioFxParams,
+ type HfAudioFxChain,
+ type HfAudioFxParamValues,
+} from "../audioFx.js";
+import { ensureAudioFxWorklets } from "./audioFxWorklets.js";
+
+/**
+ * Deterministic reverb impulse, shared by both engines so the browser and the
+ * render convolve the identical response. Exponentially-decaying noise with a
+ * one-pole lowpass standing in for air absorption; the PRNG is seeded from the
+ * parameters so the same room always produces the same tail.
+ */
+export function synthesizeReverbImpulse(
+ sampleRate: number,
+ size: number,
+ damping: number,
+): Float32Array {
+ const seconds = 0.6 + Math.max(0, Math.min(1, size)) * 2.6;
+ const length = Math.max(1, Math.floor(sampleRate * seconds));
+ const out = new Float32Array(length);
+ // Seed from the parameters: same room, same tail, on every machine.
+ let seed = (Math.round(size * 1000) * 2654435761 + Math.round(damping * 1000) * 40503) >>> 0;
+ const rand = (): number => {
+ seed = (seed * 1664525 + 1013904223) >>> 0;
+ return (seed / 0xffffffff) * 2 - 1;
+ };
+ const cutoff = Math.max(0.001, 1 - Math.max(0, Math.min(1, damping)));
+ let lp = 0;
+ let energy = 0;
+ for (let i = 0; i < length; i++) {
+ lp += cutoff * (rand() - lp);
+ const sample = lp * Math.pow(1 - i / length, 2.5);
+ out[i] = sample;
+ energy += sample * sample;
+ }
+ // Scale to unit energy. A ConvolverNode applies the impulse's gain whole (the
+ // graph sets `normalize = false` so the room is deterministic rather than
+ // browser-defined), and this impulse is decaying noise whose raw energy runs
+ // to +33 dB at the default size — loud enough that simply adding a Reverb
+ // clipped the mix. Normalising here keeps the wet knob meaning what it says
+ // and keeps preview and render identical, since both convolve this buffer.
+ const norm = Math.sqrt(energy);
+ if (norm > 0) {
+ for (let i = 0; i < length; i++) out[i] = (out[i] ?? 0) / norm;
+ }
+ return out;
+}
+
+export interface FxNodeHandle {
+ input: AudioNode;
+ output: AudioNode;
+ update(params: HfAudioFxParamValues): void;
+ dispose(): void;
+}
+
+type Builder = (ctx: BaseAudioContext, p: HfAudioFxParamValues) => FxNodeHandle;
+
+const n = (v: number | string | undefined): number => (typeof v === "number" ? v : Number(v ?? 0));
+
+/** A node that is its own input and output and has nothing to tear down. */
+function simple(node: AudioNode, update: (p: HfAudioFxParamValues) => void): FxNodeHandle {
+ return { input: node, output: node, update, dispose: () => node.disconnect() };
+}
+
+function biquad(type: BiquadFilterType, useGain: boolean): Builder {
+ return (ctx, p) => {
+ const f = ctx.createBiquadFilter();
+ f.type = type;
+ const apply = (v: HfAudioFxParamValues): void => {
+ f.frequency.value = n(v.frequency);
+ if (v.q !== undefined) f.Q.value = n(v.q);
+ if (useGain) f.gain.value = n(v.gain);
+ };
+ apply(p);
+ return simple(f, apply);
+ };
+}
+
+/**
+ * FFmpeg's highpass/lowpass take a pole count; Web Audio's biquad is always
+ * two-pole, so one-pole is built from raw coefficients via IIRFilterNode.
+ * Changing the pole count changes the node type, so the chain rebuilds rather
+ * than updates — handled by the caller comparing structural signatures.
+ */
+function onePoleBuilder(kind: "highpass" | "lowpass"): Builder {
+ return (ctx, p) => {
+ const k = Math.tan((Math.PI * n(p.frequency)) / ctx.sampleRate);
+ const node =
+ kind === "highpass"
+ ? ctx.createIIRFilter([1 / (1 + k), -1 / (1 + k)], [1, (k - 1) / (k + 1)])
+ : ctx.createIIRFilter([k / (1 + k), k / (1 + k)], [1, (k - 1) / (k + 1)]);
+ // IIRFilterNode coefficients are immutable; the caller rebuilds on change.
+ return simple(node, () => {});
+ };
+}
+
+function workletBuilder(processor: string): Builder {
+ return (ctx, p) => {
+ const node = new AudioWorkletNode(ctx, processor, { processorOptions: { ...p } });
+ return {
+ input: node,
+ output: node,
+ update: (v) => node.port.postMessage({ ...v }),
+ dispose: () => node.disconnect(),
+ };
+ };
+}
+
+/** Curves matching asoftclip's shapes, sampled once per parameter change. */
+const CURVES: Record<string, (x: number) => number> = {
+ tanh: Math.tanh,
+ atan: (x) => (2 / Math.PI) * Math.atan((Math.PI / 2) * x),
+ cubic: (x) => (Math.abs(x) >= 1 ? Math.sign(x) : x - x ** 3 / 3),
+ exp: (x) => Math.sign(x) * (1 - Math.exp(-Math.abs(x))),
+ alg: (x) => x / Math.sqrt(1 + x * x),
+ quintic: (x) => (Math.abs(x) >= 1 ? Math.sign(x) : x - x ** 5 / 5),
+ sin: (x) => (Math.abs(x) >= 1 ? Math.sign(x) : Math.sin((Math.PI / 2) * x)),
+ erf: (x) => Math.tanh(1.20211 * x),
+ hard: (x) => Math.max(-1, Math.min(1, x)),
+};
+
+const waveshaper: Builder = (ctx, p) => {
+ const ws = ctx.createWaveShaper();
+ const preGain = ctx.createGain();
+ const postGain = ctx.createGain();
+ preGain.connect(ws).connect(postGain);
+ const apply = (v: HfAudioFxParamValues): void => {
+ const shape = CURVES[String(v.type)] ?? Math.tanh;
+ const threshold = Math.pow(10, n(v.threshold) / 20);
+ const SIZE = 8192;
+ const curve = new Float32Array(SIZE);
+ for (let i = 0; i < SIZE; i++) {
+ const x = (i / (SIZE - 1)) * 2 - 1;
+ curve[i] = shape(x / Math.max(1e-6, threshold)) * threshold;
+ }
+ ws.curve = curve;
+ ws.oversample = n(v.oversample) >= 4 ? "4x" : n(v.oversample) >= 2 ? "2x" : "none";
+ postGain.gain.value = Math.pow(10, n(v.output) / 20);
+ };
+ apply(p);
+ return {
+ input: preGain,
+ output: postGain,
+ update: apply,
+ dispose: () => {
+ preGain.disconnect();
+ ws.disconnect();
+ postGain.disconnect();
+ },
+ };
+};
+
+const delayFeedback: Builder = (ctx, p) => {
+ const input = ctx.createGain();
+ const out = ctx.createGain();
+ const dl = ctx.createDelay(5);
+ const fb = ctx.createGain();
+ const wet = ctx.createGain();
+ const dry = ctx.createGain();
+ input.connect(dl);
+ dl.connect(fb);
+ fb.connect(dl);
+ dl.connect(wet).connect(out);
+ input.connect(dry).connect(out);
+ const apply = (v: HfAudioFxParamValues): void => {
+ dl.delayTime.value = Math.min(5, n(v.time) / 1000);
+ fb.gain.value = n(v.feedback);
+ wet.gain.value = n(v.mix);
+ dry.gain.value = 1 - n(v.mix);
+ };
+ apply(p);
+ return {
+ input,
+ output: out,
+ update: apply,
+ dispose: () => [input, out, dl, fb, wet, dry].forEach((x) => x.disconnect()),
+ };
+};
+
+const chorusLfo: Builder = (ctx, p) => {
+ const input = ctx.createGain();
+ const out = ctx.createGain();
+ const dl = ctx.createDelay(0.5);
+ const lfo = ctx.createOscillator();
+ 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);
+ wet.gain.value = n(v.mix);
+ dry.gain.value = 1 - n(v.mix);
+ };
+ apply(p);
+ return {
+ input,
+ output: out,
+ update: apply,
+ dispose: () => {
+ try {
+ lfo.stop();
+ } catch {
+ /* already stopped */
+ }
+ [input, out, dl, depth, wet, dry].forEach((x) => x.disconnect());
+ },
+ };
+};
+
+const PHASER_STAGES = 6;
+
+const allpassPhaser: Builder = (ctx, p) => {
+ const input = ctx.createGain();
+ const out = ctx.createGain();
+ // aphaser's in_gain/out_gain trim the signal entering and leaving the effect.
+ // Wiring them to the wet and dry legs instead made "Input" mute the dry path
+ // and let the two defaults sum above unity, so inserting a phaser raised the
+ // track level.
+ const inTrim = ctx.createGain();
+ const outTrim = ctx.createGain();
+ const lfo = ctx.createOscillator();
+ const depth = ctx.createGain();
+ const wet = ctx.createGain();
+ const dry = ctx.createGain();
+ const stages: BiquadFilterNode[] = [];
+ input.connect(inTrim);
+ let node: AudioNode = inTrim;
+ for (let i = 0; i < PHASER_STAGES; i++) {
+ const ap = ctx.createBiquadFilter();
+ ap.type = "allpass";
+ ap.Q.value = 0.7071;
+ depth.connect(ap.frequency);
+ node.connect(ap);
+ node = ap;
+ 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);
+ const apply = (v: HfAudioFxParamValues): void => {
+ // aphaser sweeps around a centre derived from its delay; mirror the range
+ // rather than the exact curve, and let the parity harness score it.
+ 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";
+ 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.
+ wet.gain.value = 1;
+ dry.gain.value = 1;
+ };
+ apply(p);
+ return {
+ input,
+ output: out,
+ update: apply,
+ dispose: () => {
+ try {
+ lfo.stop();
+ } catch {
+ /* already stopped */
+ }
+ [input, out, inTrim, outTrim, depth, wet, dry, ...stages].forEach((x) => x.disconnect());
+ },
+ };
+};
+
+const convolver: Builder = (ctx, p) => {
+ const input = ctx.createGain();
+ const out = ctx.createGain();
+ const conv = ctx.createConvolver();
+ const wet = ctx.createGain();
+ const dry = ctx.createGain();
+ conv.normalize = false;
+ input.connect(conv).connect(wet).connect(out);
+ input.connect(dry).connect(out);
+ let lastKey = "";
+ const apply = (v: HfAudioFxParamValues): void => {
+ const key = `${n(v.size)}:${n(v.damping)}`;
+ if (key !== lastKey) {
+ // Same generator the render uses, so both convolve the identical tail.
+ const ir = synthesizeReverbImpulse(ctx.sampleRate, n(v.size), n(v.damping));
+ const buf = ctx.createBuffer(1, ir.length, ctx.sampleRate);
+ buf.getChannelData(0).set(ir);
+ conv.buffer = buf;
+ lastKey = key;
+ }
+ wet.gain.value = n(v.wet);
+ dry.gain.value = n(v.dry);
+ };
+ apply(p);
+ return {
+ input,
+ output: out,
+ update: apply,
+ dispose: () => [input, out, conv, wet, dry].forEach((x) => x.disconnect()),
+ };
+};
+
+const BUILDERS: Record<string, Builder> = {
+ "biquad-peaking": biquad("peaking", true),
+ "biquad-lowshelf": biquad("lowshelf", true),
+ "biquad-highshelf": biquad("highshelf", true),
+ "biquad-highpass": biquad("highpass", false),
+ "biquad-lowpass": biquad("lowpass", false),
+ "worklet-compressor": workletBuilder("hf-compressor"),
+ "worklet-limiter": workletBuilder("hf-limiter"),
+ "worklet-gate": workletBuilder("hf-gate"),
+ "worklet-bitcrush": workletBuilder("hf-bitcrush"),
+ waveshaper,
+ "delay-feedback": delayFeedback,
+ "chorus-lfo": chorusLfo,
+ "allpass-phaser": allpassPhaser,
+ convolver,
+};
+
+/** Effect ids whose Web Audio node needs a worklet module registered first. */
+export function chainNeedsWorklets(chain: HfAudioFxChain): boolean {
+ return chain.nodes.some((node) => getAudioFxDef(node.type)?.web.startsWith("worklet-") ?? false);
+}
+
+export function buildFxNode(
+ ctx: BaseAudioContext,
+ type: string,
+ params: HfAudioFxParamValues,
+): 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);
+ }
+ const builder = BUILDERS[def.web];
+ if (!builder) throw new Error(`No Web Audio builder for ${def.web}`);
+ return builder(ctx, resolved);
+}
+
+export interface FxChainHandle {
+ input: AudioNode;
+ output: AudioNode;
+ /** Re-parameterise in place when the shape is unchanged; false if a rebuild is needed. */
+ update(chain: HfAudioFxChain): boolean;
+ dispose(): void;
+}
+
+/**
+ * A signature of everything that changes the graph's *shape* rather than its
+ * parameter values. When this is unchanged an update can just push new values
+ * into the running nodes; when it changes, the caller rebuilds.
+ */
+function shapeOf(chain: HfAudioFxChain): string {
+ return chain.nodes
+ .filter((node) => node.enabled !== false)
+ .map((node) => {
+ const p = normalizeAudioFxParams(node.type, node.params);
+ const poles = p.poles !== undefined ? `:${p.poles}` : "";
+ // A one-pole filter is an IIRFilterNode whose coefficients are fixed at
+ // construction, so its cutoff cannot be pushed into the running graph.
+ // Carrying the frequency here makes a cutoff change rebuild instead of
+ // 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}`;
+ })
+ .join("|");
+}
+
+/**
+ * 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.
+ */
+export function buildFxChain(ctx: BaseAudioContext, chain: HfAudioFxChain): FxChainHandle {
+ const input = ctx.createGain();
+ const output = ctx.createGain();
+ const handles: { type: string; handle: FxNodeHandle }[] = [];
+
+ let tail: AudioNode = input;
+ for (const node of chain.nodes) {
+ if (node.enabled === false) continue;
+ const handle = buildFxNode(ctx, node.type, node.params ?? {});
+ tail.connect(handle.input);
+ tail = handle.output;
+ handles.push({ type: node.type, handle });
+ }
+ tail.connect(output);
+
+ let shape = shapeOf(chain);
+
+ return {
+ input,
+ output,
+ update(next) {
+ if (shapeOf(next) !== shape) return false;
+ const active = next.nodes.filter((node) => node.enabled !== false);
+ active.forEach((node, i) => {
+ handles[i]?.handle.update(normalizeAudioFxParams(node.type, node.params));
+ });
+ shape = shapeOf(next);
+ return true;
+ },
+ dispose() {
+ for (const { handle } of handles) handle.dispose();
+ input.disconnect();
+ output.disconnect();
+ },
+ };
+}
+
+export { ensureAudioFxWorklets };
diff --git a/packages/core/src/audio/audioFxWorklets.ts b/packages/core/src/audio/audioFxWorklets.ts
new file mode 100644
index 0000000000..4a36a938ba
--- /dev/null
+++ b/packages/core/src/audio/audioFxWorklets.ts
@@ -0,0 +1,221 @@
+/**
+ * AudioWorklet processors for the effects Web Audio has no native node for.
+ *
+ * Each one targets the behaviour of its FFmpeg counterpart rather than of any
+ * particular plugin, because the render is FFmpeg and preview only earns its
+ * keep by predicting the render. How closely each lands is measured, not
+ * assumed — see the preview/render parity harness.
+ *
+ * Kept as a source string so it can be registered from a Blob URL without a
+ * separate bundled asset, which keeps the studio's build unchanged.
+ */
+export const AUDIO_FX_WORKLET_SOURCE = `
+const dbToLin = (db) => Math.pow(10, db / 20);
+
+/**
+ * One-pole envelope followers, one per channel.
+ *
+ * Per channel matters: the followers advance once per sample, so a single shared
+ * follower stepped once per channel per sample. On stereo that ran a 20 ms attack
+ * as 10 ms, and gave the right channel a gain computed from an envelope that had
+ * already traversed the left — so the two channels ducked by different amounts
+ * from the same input and the image pumped.
+ */
+class EnvBank {
+ constructor(attackMs, releaseMs) { this.set(attackMs, releaseMs); this.values = []; }
+ set(attackMs, releaseMs) {
+ this.a = Math.exp(-1 / (sampleRate * Math.max(1e-5, attackMs / 1000)));
+ this.r = Math.exp(-1 / (sampleRate * Math.max(1e-5, releaseMs / 1000)));
+ }
+ push(ch, x) {
+ const prev = this.values[ch] ?? 0;
+ const m = Math.abs(x);
+ const c = m > prev ? this.a : this.r;
+ const next = m + c * (prev - m);
+ this.values[ch] = next;
+ return next;
+ }
+}
+
+/** Soft-knee gain computer in dB, matching acompressor's shape. */
+function kneeGain(envDb, thresholdDb, ratio, kneeDb) {
+ const over = envDb - thresholdDb;
+ if (kneeDb > 0 && over > -kneeDb && over < kneeDb) {
+ const t = (over + kneeDb) / (2 * kneeDb);
+ return -((1 - 1 / ratio) * kneeDb * t * t);
+ }
+ return over > 0 ? -(over * (1 - 1 / ratio)) : 0;
+}
+
+class HfCompressor extends AudioWorkletProcessor {
+ constructor(o) {
+ super();
+ this.p = o.processorOptions || {};
+ this.env = new EnvBank(this.p.attack ?? 20, this.p.release ?? 250);
+ this.port.onmessage = (e) => {
+ this.p = { ...this.p, ...e.data };
+ this.env.set(this.p.attack ?? 20, this.p.release ?? 250);
+ };
+ }
+ process(inputs, outputs) {
+ const i = inputs[0], o = outputs[0];
+ if (!i || !i.length) return true;
+ const p = this.p;
+ const makeup = dbToLin(p.makeup ?? 0);
+ const mix = p.mix ?? 1;
+ // Knee is expressed as a ratio in FFmpeg; convert to dB width.
+ const kneeDb = 20 * Math.log10(Math.max(1.0001, p.knee ?? 2.83));
+ for (let ch = 0; ch < i.length; ch++) {
+ const inp = i[ch], out = o[ch];
+ for (let n = 0; n < inp.length; n++) {
+ const x = inp[n];
+ const env = this.env.push(ch, x);
+ const envDb = env > 1e-9 ? 20 * Math.log10(env) : -200;
+ const g = dbToLin(kneeGain(envDb, p.threshold ?? -24, p.ratio ?? 4, kneeDb));
+ out[n] = x * g * makeup * mix + x * (1 - mix);
+ }
+ }
+ return true;
+ }
+}
+registerProcessor("hf-compressor", HfCompressor);
+
+class HfLimiter extends AudioWorkletProcessor {
+ constructor(o) {
+ super();
+ this.p = o.processorOptions || {};
+ this.env = new EnvBank(this.p.attack ?? 5, this.p.release ?? 50);
+ this.port.onmessage = (e) => {
+ this.p = { ...this.p, ...e.data };
+ this.env.set(this.p.attack ?? 5, this.p.release ?? 50);
+ };
+ }
+ process(inputs, outputs) {
+ const i = inputs[0], o = outputs[0];
+ if (!i || !i.length) return true;
+ const ceiling = dbToLin(this.p.limit ?? -1);
+ const outGain = dbToLin(this.p.level_out ?? 0);
+ for (let ch = 0; ch < i.length; ch++) {
+ const inp = i[ch], out = o[ch];
+ for (let n = 0; n < inp.length; n++) {
+ const x = inp[n];
+ const env = this.env.push(ch, x);
+ // Only ever attenuate: a limiter that can raise level is a compressor.
+ const g = env > ceiling ? ceiling / env : 1;
+ out[n] = x * g * outGain;
+ }
+ }
+ return true;
+ }
+}
+registerProcessor("hf-limiter", HfLimiter);
+
+class HfGate extends AudioWorkletProcessor {
+ constructor(o) {
+ super();
+ this.p = o.processorOptions || {};
+ this.env = new EnvBank(this.p.attack ?? 1, this.p.release ?? 100);
+ this.gains = [];
+ this.port.onmessage = (e) => {
+ this.p = { ...this.p, ...e.data };
+ this.env.set(this.p.attack ?? 1, this.p.release ?? 100);
+ };
+ }
+ process(inputs, outputs) {
+ const i = inputs[0], o = outputs[0];
+ if (!i || !i.length) return true;
+ const p = this.p;
+ const threshold = dbToLin(p.threshold ?? -35);
+ const floor = dbToLin(p.range ?? -24);
+ const ratio = p.ratio ?? 10;
+ // Knee is declared in the registry as a ratio, like the compressor's; a
+ // hard threshold ignored it and chattered on material sitting right at the
+ // gate point.
+ const kneeDb = 20 * Math.log10(Math.max(1.0001, p.knee ?? 2.83));
+ const kneeLin = dbToLin((p.threshold ?? -35) + kneeDb);
+ for (let ch = 0; ch < i.length; ch++) {
+ const inp = i[ch], out = o[ch];
+ for (let n = 0; n < inp.length; n++) {
+ const x = inp[n];
+ const env = this.env.push(ch, x);
+ let target = 1;
+ if (env < threshold) {
+ const under = env > 1e-9 ? threshold / env : 1e9;
+ target = Math.max(floor, 1 / Math.pow(under, ratio - 1));
+ if (!isFinite(target)) target = floor;
+ }
+ // Smooth toward the target so the gate does not click on every sample.
+ const held = this.gains[ch] ?? 1;
+ const c = target < held ? this.env.r : this.env.a;
+ const smoothed = target + c * (held - target);
+ this.gains[ch] = smoothed;
+ out[n] = x * smoothed;
+ }
+ }
+ return true;
+ }
+}
+registerProcessor("hf-gate", HfGate);
+
+class HfBitcrush extends AudioWorkletProcessor {
+ constructor(o) {
+ super();
+ this.p = o.processorOptions || {};
+ this.holds = [];
+ this.held = [];
+ this.port.onmessage = (e) => { this.p = { ...this.p, ...e.data }; };
+ }
+ process(inputs, outputs) {
+ const i = inputs[0], o = outputs[0];
+ if (!i || !i.length) return true;
+ const p = this.p;
+ const levels = Math.pow(2, (p.bits ?? 8) - 1);
+ const step = Math.max(1, Math.round(p.samples ?? 1));
+ const mix = p.mix ?? 1;
+ for (let ch = 0; ch < i.length; ch++) {
+ const inp = i[ch], out = o[ch];
+ if (this.held[ch] === undefined) this.held[ch] = 0;
+ if (this.holds[ch] === undefined) this.holds[ch] = 0;
+ for (let n = 0; n < inp.length; n++) {
+ // Per channel: advancing one shared counter only on the last channel
+ // left every earlier channel either unheld or frozen for a whole
+ // 128-sample quantum, clicking once a block.
+ if (this.holds[ch] === 0) this.held[ch] = Math.round(inp[n] * levels) / levels;
+ out[n] = this.held[ch] * mix + inp[n] * (1 - mix);
+ this.holds[ch] = (this.holds[ch] + 1) % step;
+ }
+ }
+ return true;
+ }
+}
+registerProcessor("hf-bitcrush", HfBitcrush);
+`;
+
+let modulePromise: Promise<void> | undefined;
+
+/**
+ * Register the processors on a context. Idempotent per module instance, since
+ * addModule throws if the same processor name is registered twice.
+ */
+export function ensureAudioFxWorklets(ctx: BaseAudioContext): Promise<void> {
+ modulePromise ??= (async () => {
+ if (!ctx.audioWorklet) {
+ throw new Error(
+ "AudioWorklet is unavailable — the page needs a secure context (https, localhost or file://)",
+ );
+ }
+ // A data: URL rather than a blob:, because a blob inherits the page origin
+ // and is treated as opaque on a file:// page, where the module then fails
+ // to load with an unhelpful AbortError.
+ const url = `data:text/javascript;base64,${btoa(
+ String.fromCharCode(...new TextEncoder().encode(AUDIO_FX_WORKLET_SOURCE)),
+ )}`;
+ await ctx.audioWorklet.addModule(url);
+ })();
+ return modulePromise;
+}
+
+/** Test seam: forget the cached registration so a fresh context can register. */
+export function __resetAudioFxWorkletsForTests(): void {
+ modulePromise = undefined;
+}