Skip to content

Write HTML. Render video. Built for agents.

feat(engine): render the FX chain offline, and the carve analysis behind it (#3021)

Vance Ingallscc40e35aa099
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 612b17cde1..bb892426a1 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -26,6 +26,9 @@
// Bundled as a standalone IIFE by the position-edits render artifact
// generator; referenced by file path rather than imported by TypeScript.
"packages/core/stubs/position-edits-render-entry.ts",
+ // Same arrangement for the audio FX graph builders, bundled by
+ // build-audio-fx-runtime.ts for the offline render page.
+ "packages/core/stubs/audio-fx-runtime-entry.ts",
// In-page audit scripts read as raw strings and injected via
// page.addScriptTag (see layout.ts / validate.ts) — referenced by file
// path, never imported, so they have no import-graph referrer.
diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json
index c7b9e3a597..b8905eb8e2 100644
--- a/packages/core/package-subpaths.json
+++ b/packages/core/package-subpaths.json
@@ -98,6 +98,18 @@
"types": "./dist/audioFx.d.ts",
"environments": ["browser", "bun", "node"]
},
+ "./audio-fx-runtime": {
+ "source": "./src/generated/audio-fx-runtime-inline.ts",
+ "runtime": "./dist/generated/audio-fx-runtime-inline.js",
+ "types": "./dist/generated/audio-fx-runtime-inline.d.ts",
+ "environments": ["bun", "node"]
+ },
+ "./audio-carve": {
+ "source": "./src/audioCarve.ts",
+ "runtime": "./dist/audioCarve.js",
+ "types": "./dist/audioCarve.d.ts",
+ "environments": ["browser", "bun", "node"]
+ },
"./color-grading": {
"source": "./src/colorGrading.ts",
"runtime": "./dist/colorGrading.js",
diff --git a/packages/core/package.json b/packages/core/package.json
index 1e9d9fa748..cd9d6aed06 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -112,6 +112,18 @@
"import": "./src/audioFx.ts",
"types": "./src/audioFx.ts"
},
+ "./audio-fx-runtime": {
+ "bun": "./src/generated/audio-fx-runtime-inline.ts",
+ "node": "./dist/generated/audio-fx-runtime-inline.js",
+ "import": "./src/generated/audio-fx-runtime-inline.ts",
+ "types": "./src/generated/audio-fx-runtime-inline.ts"
+ },
+ "./audio-carve": {
+ "bun": "./src/audioCarve.ts",
+ "node": "./dist/audioCarve.js",
+ "import": "./src/audioCarve.ts",
+ "types": "./src/audioCarve.ts"
+ },
"./color-grading": {
"bun": "./src/colorGrading.ts",
"node": "./dist/colorGrading.js",
@@ -378,6 +390,14 @@
"import": "./dist/audioFx.js",
"types": "./dist/audioFx.d.ts"
},
+ "./audio-fx-runtime": {
+ "import": "./dist/generated/audio-fx-runtime-inline.js",
+ "types": "./dist/generated/audio-fx-runtime-inline.d.ts"
+ },
+ "./audio-carve": {
+ "import": "./dist/audioCarve.js",
+ "types": "./dist/audioCarve.d.ts"
+ },
"./color-grading": {
"import": "./dist/colorGrading.js",
"types": "./dist/colorGrading.d.ts"
@@ -518,7 +538,7 @@
"types": "./dist/index.d.ts"
},
"scripts": {
- "build": "bun run build:hyperframes-runtime && bun run build:position-edits-render && tsc && tsx scripts/rewrite-esm-extensions.ts",
+ "build": "bun run build:hyperframes-runtime && bun run build:position-edits-render && bun run build:audio-fx-runtime && tsc && tsx scripts/rewrite-esm-extensions.ts",
"test": "bun run check:position-edits-render && vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
@@ -526,6 +546,7 @@
"typecheck": "tsc --noEmit && bun run typecheck:runtime",
"typecheck:runtime": "tsc --noEmit -p tsconfig.runtime.json",
"lint:runtime-preview-guards": "bun scripts/lint-runtime-preview-guards.ts",
+ "build:audio-fx-runtime": "tsx scripts/build-audio-fx-runtime.ts",
"build:hyperframes-runtime": "tsx scripts/build-hyperframes-runtime-artifact.ts",
"build:position-edits-render": "tsx scripts/build-position-edits-render.ts",
"check:position-edits-render": "bun run build:position-edits-render && git diff --exit-code -- src/generated/position-edits-render-inline.ts",
diff --git a/packages/core/scripts/build-audio-fx-runtime.ts b/packages/core/scripts/build-audio-fx-runtime.ts
new file mode 100644
index 0000000000..eb6c841a51
--- /dev/null
+++ b/packages/core/scripts/build-audio-fx-runtime.ts
@@ -0,0 +1,50 @@
+/** Build the injectable audio-FX runtime artifact from the canonical runtime. */
+
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { buildSync } from "esbuild";
+import { execFileSync } from "node:child_process";
+
+const thisDir = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(thisDir, "..");
+const entry = resolve(repoRoot, "stubs/audio-fx-runtime-entry.ts");
+const generatedDir = resolve(repoRoot, "src/generated");
+const outPath = resolve(generatedDir, "audio-fx-runtime-inline.ts");
+
+const result = buildSync({
+ entryPoints: [entry],
+ bundle: true,
+ write: false,
+ platform: "browser",
+ format: "iife",
+ target: ["es2020"],
+ minify: true,
+ legalComments: "none",
+});
+const iife = result.outputFiles[0]?.text ?? "";
+if (!iife) throw new Error("esbuild produced no output for audio-fx-runtime-entry.ts");
+
+mkdirSync(generatedDir, { recursive: true });
+writeFileSync(
+ outPath,
+ [
+ "// AUTO-GENERATED by scripts/build-audio-fx-runtime.ts - do not edit",
+ `const AUDIO_FX_RUNTIME_IIFE: string = ${JSON.stringify(iife)};`,
+ "",
+ "/** Returns the pre-built audio-FX runtime IIFE as a string constant. */",
+ "export function getAudioFxRuntimeScript(): string {",
+ " return AUDIO_FX_RUNTIME_IIFE;",
+ "}",
+ "",
+ ].join("\n"),
+ "utf8",
+);
+
+try {
+ execFileSync("bun", ["x", "oxfmt", outPath], { stdio: "ignore" });
+} catch {
+ // Formatting is best effort when the generator runs in a minimal environment.
+}
+
+console.log(JSON.stringify({ event: "audio_fx_runtime_generated", outPath, bytes: iife.length }));
diff --git a/packages/core/src/audioCarve.test.ts b/packages/core/src/audioCarve.test.ts
new file mode 100644
index 0000000000..5778a1731d
--- /dev/null
+++ b/packages/core/src/audioCarve.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it } from "vitest";
+import {
+ analyseCarveBands,
+ carveBandsToChain,
+ DEFAULT_CARVE,
+ normalizeCarveSettings,
+} from "./audioCarve.js";
+
+const SR = 48000;
+
+/** A tone-plus-harmonics stand-in for a voice, centred on `f0`. */
+function voiceLike(f0: number, seconds = 0.5): Float32Array {
+ const n = Math.floor(SR * seconds);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ const t = i / SR;
+ out[i] =
+ 0.6 * Math.sin(2 * Math.PI * f0 * t) +
+ 0.3 * Math.sin(2 * Math.PI * f0 * 2 * t) +
+ 0.1 * Math.sin(2 * Math.PI * f0 * 3 * t);
+ }
+ return out;
+}
+
+describe("normalizeCarveSettings", () => {
+ it("fills defaults and clamps nonsense", () => {
+ expect(normalizeCarveSettings(undefined)).toEqual(DEFAULT_CARVE);
+ const v = normalizeCarveSettings({ maxCutDb: 500, bands: 99, q: 0, intelligibilityBias: -3 });
+ expect(v.maxCutDb).toBe(24);
+ expect(v.bands).toBe(6);
+ expect(v.q).toBe(0.3);
+ expect(v.intelligibilityBias).toBe(0);
+ });
+});
+
+describe("analyseCarveBands", () => {
+ it("returns nothing for silence-length input", () => {
+ expect(analyseCarveBands(new Float32Array(0), SR, DEFAULT_CARVE)).toEqual([]);
+ });
+
+ it("returns the requested number of bands, ascending, all cuts", () => {
+ const bands = analyseCarveBands(voiceLike(250), SR, { ...DEFAULT_CARVE, bands: 3 });
+ expect(bands).toHaveLength(3);
+ expect(bands.map((b) => b.freq)).toEqual([...bands.map((b) => b.freq)].sort((a, b) => a - b));
+ for (const b of bands) expect(b.gainDb).toBeLessThan(0);
+ });
+
+ it("never cuts deeper than the configured maximum", () => {
+ const bands = analyseCarveBands(voiceLike(400), SR, { ...DEFAULT_CARVE, maxCutDb: 5 });
+ for (const b of bands) expect(Math.abs(b.gainDb)).toBeLessThanOrEqual(5);
+ });
+
+ it("follows raw voice power when the bias is off", () => {
+ // With no bias, a low-pitched voice should select its own fundamental
+ // region — this is the behaviour that makes an unbiased carve thin the bed
+ // rather than unmask the voice.
+ const bands = analyseCarveBands(voiceLike(160), SR, {
+ ...DEFAULT_CARVE,
+ bands: 1,
+ intelligibilityBias: 0,
+ });
+ expect(bands[0]!.freq).toBeLessThanOrEqual(400);
+ });
+
+ it("moves selection upward when the bias is on", () => {
+ // The bias reweights ranking, it does not override the spectrum: a band the
+ // voice has no energy in is not worth carving. So the guarantee is that
+ // biasing never selects *lower* than the unbiased ranking, and lifts it
+ // whenever there is competing energy up top to select.
+ const broadband = (() => {
+ const n = Math.floor(SR * 0.5);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ const t = i / SR;
+ out[i] =
+ 0.5 * Math.sin(2 * Math.PI * 160 * t) +
+ 0.45 * Math.sin(2 * Math.PI * 1000 * t) +
+ 0.4 * Math.sin(2 * Math.PI * 2500 * t);
+ }
+ return out;
+ })();
+ const flat = analyseCarveBands(broadband, SR, {
+ ...DEFAULT_CARVE,
+ bands: 1,
+ intelligibilityBias: 0,
+ });
+ const biased = analyseCarveBands(broadband, SR, {
+ ...DEFAULT_CARVE,
+ bands: 1,
+ intelligibilityBias: 1,
+ });
+ expect(biased[0]!.freq).toBeGreaterThanOrEqual(flat[0]!.freq);
+ expect(biased[0]!.freq).toBeGreaterThanOrEqual(1000);
+ });
+
+ /**
+ * A voice with the spectral tilt real speech has: energy falls off about 6 dB
+ * per octave above the fundamental, so the low bands carry 20-30 dB more power
+ * than the presence region. `broadband` above spreads its three tones over
+ * roughly 2 dB, which is why it cannot tell a working bias from an inert one.
+ */
+ function tiltedVoice(f0 = 120, seconds = 0.5): Float32Array {
+ const n = Math.floor(SR * seconds);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ const t = i / SR;
+ let v = 0;
+ // Harmonics out past 6 kHz, each 6 dB/octave down, so every candidate band
+ // has real energy to rank and the ranking is decided by the weighting
+ // rather than by which band happens to be the only one occupied.
+ for (let h = 1; h * f0 < SR / 2 && h <= 64; h++) {
+ v += (1 / h) * Math.sin(2 * Math.PI * f0 * h * t);
+ }
+ out[i] = 0.5 * v;
+ }
+ return out;
+ }
+
+ it("reaches the presence region at the default bias, not just at bias 1", () => {
+ // The point of the feature: dip the bed where the voice is MASKED, 1-3 kHz,
+ // not where the voice is loudest. DEFAULT_CARVE is what a user gets from
+ // clicking "Analyse and apply", so the default has to do this — a knob that
+ // only works at its extreme does not work.
+ const bands = analyseCarveBands(tiltedVoice(), SR, { ...DEFAULT_CARVE, bands: 3 });
+ expect(bands.map((b) => b.freq).some((f) => f >= 1000)).toBe(true);
+ });
+
+ it("gives the bias enough authority to cross a speech-sized tilt", () => {
+ // The authority, stated in the unit that decides it: a multiplicative weight
+ // bounded below by (1 - bias) can move a ranking by at most
+ // 10*log10(1/(1 - bias)) — 5.2 dB at the 0.7 default. Speech tilts 20-30 dB.
+ //
+ // Two tones, the low one 9 dB louder, both on candidate centres (the bands
+ // are a third of an octave wide but their centres step about two thirds
+ // apart, so a tone between two of them — 2 kHz, say — falls in a gap and is
+ // invisible to the analysis). Raw power says 250 Hz; the default bias has to
+ // be able to say 1.6 kHz anyway.
+ //
+ // 9 dB rather than the 21 dB the bias nominally carries at 0.7: a lone tone
+ // is diluted by `bandPower` averaging across the band's bins, and the 1.6 kHz
+ // band spans about six times as many bins as the 250 Hz one, which costs
+ // roughly 8 dB. Broadband content — a real voice — fills both and keeps it.
+ const twoTone = (() => {
+ const n = Math.floor(SR * 0.5);
+ const out = new Float32Array(n);
+ const quiet = Math.pow(10, -9 / 20);
+ for (let i = 0; i < n; i++) {
+ const t = i / SR;
+ out[i] =
+ 0.5 * Math.sin(2 * Math.PI * 250 * t) + 0.5 * quiet * Math.sin(2 * Math.PI * 1600 * t);
+ }
+ return out;
+ })();
+ const one = { ...DEFAULT_CARVE, bands: 1 };
+ expect(analyseCarveBands(twoTone, SR, { ...one, intelligibilityBias: 0 })[0]!.freq).toBe(250);
+ expect(analyseCarveBands(twoTone, SR, one)[0]!.freq).toBe(1600);
+ });
+
+ it("still follows raw power exactly when the bias is off", () => {
+ // The escape hatch keeps working: at bias 0 selection is the voice's own
+ // loudest band, whatever the weighting curve would have preferred.
+ const bands = analyseCarveBands(tiltedVoice(), SR, {
+ ...DEFAULT_CARVE,
+ bands: 1,
+ intelligibilityBias: 0,
+ });
+ expect(bands[0]!.freq).toBeLessThanOrEqual(400);
+ });
+});
+
+describe("carveBandsToChain", () => {
+ it("turns bands into peaking nodes carrying the analysed values", () => {
+ const chain = carveBandsToChain([{ freq: 1000, gainDb: -6, q: 1.4 }]);
+ expect(chain.nodes).toHaveLength(1);
+ expect(chain.nodes[0]!.type).toBe("peaking");
+ expect(chain.nodes[0]!.params).toMatchObject({ frequency: 1000, gain: -6, q: 1.4 });
+ });
+
+ it("produces an empty chain for no bands", () => {
+ expect(carveBandsToChain([]).nodes).toEqual([]);
+ });
+});
diff --git a/packages/core/src/audioCarve.ts b/packages/core/src/audioCarve.ts
new file mode 100644
index 0000000000..386aadf64b
--- /dev/null
+++ b/packages/core/src/audioCarve.ts
@@ -0,0 +1,261 @@
+/**
+ * Voiceover carve: find the bands a voice occupies and dip a music bed there,
+ * so the voice sits in front without ducking the whole track.
+ *
+ * This is a relationship between two tracks, not an effect on one. The controls
+ * live on the bed being processed and name the voice to listen to, the same way
+ * a sidechain compressor works: you select the track that gets quieter and pick
+ * what makes it quieter.
+ *
+ * The output is an ordinary FX chain of peaking filters, so a carve is just a
+ * chain the studio generated rather than a separate rendering path.
+ */
+
+import {
+ defaultAudioFxParams,
+ HF_AUDIO_FX_CHAIN_VERSION,
+ type HfAudioFxChain,
+ type HfAudioFxNode,
+} from "./audioFx.js";
+
+export const HF_AUDIO_CARVE_ATTR = "data-fx-carve";
+
+/** Third-octave centres spanning the range speech actually occupies. */
+const CANDIDATE_CENTERS_HZ = [160, 250, 400, 630, 1000, 1600, 2500, 4000, 6000] as const;
+
+const FRAME = 4096;
+const HOP = 2048;
+
+export interface HfCarveBand {
+ freq: number;
+ gainDb: number;
+ q: number;
+}
+
+export interface HfCarveSettings {
+ /** Element id of the voice track to analyse. */
+ source: string;
+ /** Deepest cut applied to the strongest band. */
+ maxCutDb: number;
+ /** How many bands to dip. */
+ bands: number;
+ q: number;
+ /**
+ * Weight selection toward intelligibility rather than raw voice energy.
+ *
+ * Ranking purely by voice power lands on the fundamental almost every time,
+ * because that is where a voice is loudest — but masking that actually hurts
+ * a voiceover happens higher up, and dipping 160 Hz mostly just thins the
+ * bed. Weighting pushes selection toward 1-3 kHz where intelligibility lives.
+ */
+ intelligibilityBias: number;
+}
+
+export const DEFAULT_CARVE: HfCarveSettings = {
+ source: "",
+ maxCutDb: 6,
+ bands: 3,
+ q: 1.4,
+ intelligibilityBias: 0.7,
+};
+
+export function normalizeCarveSettings(raw: Partial<HfCarveSettings> | undefined): HfCarveSettings {
+ const clamp = (v: unknown, lo: number, hi: number, dflt: number): number => {
+ const n = typeof v === "number" ? v : Number(v);
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt;
+ };
+ return {
+ source: typeof raw?.source === "string" ? raw.source : "",
+ maxCutDb: clamp(raw?.maxCutDb, 0, 24, DEFAULT_CARVE.maxCutDb),
+ bands: Math.round(clamp(raw?.bands, 1, 6, DEFAULT_CARVE.bands)),
+ q: clamp(raw?.q, 0.3, 8, DEFAULT_CARVE.q),
+ intelligibilityBias: clamp(raw?.intelligibilityBias, 0, 1, DEFAULT_CARVE.intelligibilityBias),
+ };
+}
+
+/** Averaged power spectrum, Welch-style. */
+function powerSpectrum(
+ mono: Float32Array,
+ sampleRate: number,
+): { freqs: number[]; power: number[] } {
+ const n = Math.max(mono.length, FRAME);
+ const padded =
+ mono.length >= FRAME
+ ? mono
+ : (() => {
+ const p = new Float32Array(FRAME);
+ p.set(mono);
+ return p;
+ })();
+
+ const window = new Float32Array(FRAME);
+ for (let i = 0; i < FRAME; i++) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1));
+
+ const bins = FRAME / 2 + 1;
+ const acc = new Float64Array(bins);
+ let frames = 0;
+ for (let start = 0; start + FRAME <= n; start += HOP) {
+ // Goertzel-free naive DFT would be O(n^2); use a real FFT via recursion on
+ // a copied frame. FRAME is a power of two so the radix-2 split is exact.
+ const re = new Float64Array(FRAME);
+ const im = new Float64Array(FRAME);
+ for (let i = 0; i < FRAME; i++) re[i] = (padded[start + i] ?? 0) * window[i]!;
+ fft(re, im);
+ for (let k = 0; k < bins; k++) acc[k]! += re[k]! * re[k]! + im[k]! * im[k]!;
+ frames++;
+ }
+ if (frames === 0) frames = 1;
+
+ const freqs: number[] = [];
+ const power: number[] = [];
+ for (let k = 0; k < bins; k++) {
+ freqs.push((k * sampleRate) / FRAME);
+ power.push(acc[k]! / frames);
+ }
+ return { freqs, power };
+}
+
+/** In-place iterative radix-2 FFT. */
+function fft(re: Float64Array, im: Float64Array): void {
+ const n = re.length;
+ for (let i = 1, j = 0; i < n; i++) {
+ let bit = n >> 1;
+ for (; j & bit; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) {
+ [re[i], re[j]] = [re[j]!, re[i]!];
+ [im[i], im[j]] = [im[j]!, im[i]!];
+ }
+ }
+ for (let len = 2; len <= n; len <<= 1) {
+ const ang = (-2 * Math.PI) / len;
+ const wr = Math.cos(ang);
+ const wi = Math.sin(ang);
+ for (let i = 0; i < n; i += len) {
+ let cr = 1;
+ let ci = 0;
+ for (let k = 0; k < len / 2; k++) {
+ const ur = re[i + k]!;
+ const ui = im[i + k]!;
+ const vr = re[i + k + len / 2]! * cr - im[i + k + len / 2]! * ci;
+ const vi = re[i + k + len / 2]! * ci + im[i + k + len / 2]! * cr;
+ re[i + k] = ur + vr;
+ im[i + k] = ui + vi;
+ re[i + k + len / 2] = ur - vr;
+ im[i + k + len / 2] = ui - vi;
+ const ncr = cr * wr - ci * wi;
+ ci = cr * wi + ci * wr;
+ cr = ncr;
+ }
+ }
+ }
+}
+
+function bandPower(freqs: number[], power: number[], center: number): number {
+ const lo = center / Math.pow(2, 1 / 6);
+ const hi = center * Math.pow(2, 1 / 6);
+ let sum = 0;
+ let count = 0;
+ for (let i = 0; i < freqs.length; i++) {
+ if (freqs[i]! >= lo && freqs[i]! < hi) {
+ sum += power[i]!;
+ count++;
+ }
+ }
+ return count > 0 ? sum / count : 0;
+}
+
+/**
+ * How far the bias may move a band in the ranking, in dB, at full strength.
+ *
+ * This has to be on the scale of the thing it competes with. Speech spreads
+ * 20-30 dB across these candidate bands — it falls off roughly 6 dB per octave
+ * above the fundamental — so a bias that can only shift the ranking by a few dB
+ * cannot shift it at all. 30 dB gives the 0.7 default about 21 dB of authority
+ * over the low bands, enough to cross a normal voice's tilt, while still leaving
+ * a band the voice genuinely dominates able to win: the bias reweights the
+ * ranking, it does not override the spectrum.
+ */
+const BIAS_AUTHORITY_DB = 30;
+
+/**
+ * Ranking penalty for a candidate band, in dB. Zero at 2 kHz, where speech
+ * intelligibility lives and where a bed most often masks a voice, rising as a
+ * band sits further away in either direction.
+ *
+ * Applied in dB, and that is the point. As a multiplicative weight of
+ * `1 - bias + bias * shaped` it is bounded below by `1 - bias`, so the most it
+ * could ever move a ranking is `10*log10(1/(1 - bias))`: 5.2 dB at the 0.7
+ * default, 3 dB at 0.5. Against speech's own 20-30 dB tilt that is no influence,
+ * and every bias below ~0.95 ranks exactly like bias 0 — selecting the
+ * fundamental every time, the precise outcome the bias exists to prevent. A
+ * fixture whose bands sit 2 dB apart cannot tell the two apart.
+ */
+function intelligibilityPenaltyDb(center: number, bias: number): number {
+ const octavesFrom2k = Math.log2(center / 2000);
+ const shaped = Math.exp(-(octavesFrom2k * octavesFrom2k) / 2);
+ return bias * BIAS_AUTHORITY_DB * (1 - shaped);
+}
+
+/**
+ * Analyse a voice and return the bands to dip in the bed. Bands come back in
+ * ascending frequency; the deepest cut lands on the strongest band and the
+ * others scale with their relative weight, floored at half depth so a selected
+ * band still does something audible.
+ */
+export function analyseCarveBands(
+ voice: Float32Array,
+ sampleRate: number,
+ settings: HfCarveSettings,
+): HfCarveBand[] {
+ if (voice.length === 0) return [];
+ const { freqs, power } = powerSpectrum(voice, sampleRate);
+
+ const scored = CANDIDATE_CENTERS_HZ.map((center) => {
+ const bandPowerAt = bandPower(freqs, power, center);
+ return {
+ center,
+ hasEnergy: bandPowerAt > 0,
+ // A band with no energy scores -Infinity rather than a large negative
+ // number, so it can never outrank a real band however favourably the bias
+ // views its frequency.
+ scoreDb:
+ bandPowerAt > 0
+ ? 10 * Math.log10(bandPowerAt) -
+ intelligibilityPenaltyDb(center, settings.intelligibilityBias)
+ : Number.NEGATIVE_INFINITY,
+ };
+ }).sort((a, b) => b.scoreDb - a.scoreDb);
+
+ const selected = scored.slice(0, Math.max(1, settings.bands)).filter((b) => b.hasEnergy);
+ if (selected.length === 0) return [];
+
+ const topDb = selected[0]!.scoreDb;
+ return selected
+ .map(({ center, scoreDb }) => {
+ // Same relative depth as a ratio of linear scores would give — a band 3 dB
+ // under the strongest gets half its cut — read off the dB difference.
+ const relative = Math.pow(10, (scoreDb - topDb) / 10);
+ const depth = Math.min(
+ settings.maxCutDb,
+ Math.max(settings.maxCutDb / 2, settings.maxCutDb * relative),
+ );
+ return { freq: center, gainDb: -Number(depth.toFixed(2)), q: settings.q };
+ })
+ .sort((a, b) => a.freq - b.freq);
+}
+
+/** Carve bands as an ordinary FX chain of peaking filters. */
+export function carveBandsToChain(bands: HfCarveBand[]): HfAudioFxChain {
+ const nodes: HfAudioFxNode[] = bands.map((b) => ({
+ type: "peaking",
+ enabled: true,
+ params: {
+ ...defaultAudioFxParams("peaking"),
+ frequency: b.freq,
+ gain: b.gainDb,
+ q: b.q,
+ },
+ }));
+ return { version: HF_AUDIO_FX_CHAIN_VERSION, nodes };
+}
diff --git a/packages/core/stubs/audio-fx-runtime-entry.ts b/packages/core/stubs/audio-fx-runtime-entry.ts
new file mode 100644
index 0000000000..4bf75d16a1
--- /dev/null
+++ b/packages/core/stubs/audio-fx-runtime-entry.ts
@@ -0,0 +1,93 @@
+/**
+ * Entry point for the injectable audio-FX runtime.
+ *
+ * The engine renders audio by running the *same* Web Audio graph the studio
+ * previews with, inside an OfflineAudioContext in the headless browser it
+ * already drives. Bundling the graph builders into one IIFE is what lets both
+ * ends share a single implementation rather than two that have to be kept in
+ * agreement.
+ *
+ * Exposes `window.__HF_AUDIO_FX.render(pcm, sampleRate, chain)`, which returns
+ * the processed samples.
+ */
+
+import {
+ buildFxChain,
+ chainNeedsWorklets,
+ ensureAudioFxWorklets,
+} from "../src/audio/audioFxGraph.js";
+import { parseAudioFxChain, type HfAudioFxChain } from "../src/audioFx.js";
+
+declare global {
+ interface Window {
+ __HF_AUDIO_FX?: {
+ render(
+ planes: Float32Array[],
+ sampleRate: number,
+ chainJson: string,
+ ): Promise<Float32Array[]>;
+ };
+ }
+}
+
+/**
+ * Run the chain over one clip's audio, a plane per channel.
+ *
+ * Channel count is preserved: folding to mono here collapsed a stereo bed's
+ * width for the render only, while preview kept it stereo.
+ *
+ * The context is exactly as long as the input. An effect with a tail — reverb,
+ * delay — is still ringing at that point and is cut there, which is the one place
+ * the render does not match preview. Extending it would lengthen the clip in the
+ * mix, so how far a tail may run past a clip's end is a product decision rather
+ * than something to pick here.
+ */
+/** The clip's audio as an AudioBuffer, a plane per channel. */
+function toBuffer(
+ ctx: OfflineAudioContext,
+ planes: readonly Float32Array[],
+ channels: number,
+ frames: number,
+ sampleRate: number,
+): AudioBuffer {
+ const buffer = ctx.createBuffer(channels, frames, sampleRate);
+ for (let c = 0; c < channels; c++) {
+ const plane = planes[c];
+ if (plane) buffer.getChannelData(c).set(plane);
+ }
+ return buffer;
+}
+
+/** Every rendered channel, copied out of the result buffer. */
+function toPlanes(rendered: AudioBuffer): Float32Array[] {
+ const out: Float32Array[] = [];
+ for (let c = 0; c < rendered.numberOfChannels; c++) {
+ out.push(new Float32Array(rendered.getChannelData(c)));
+ }
+ return out;
+}
+
+async function render(
+ planes: Float32Array[],
+ sampleRate: number,
+ chainJson: string,
+): Promise<Float32Array[]> {
+ const chain: HfAudioFxChain = parseAudioFxChain(chainJson);
+ const channels = Math.max(1, planes.length);
+ const frames = planes[0]?.length ?? 0;
+ const ctx = new OfflineAudioContext(channels, frames, sampleRate);
+
+ if (chainNeedsWorklets(chain)) await ensureAudioFxWorklets(ctx);
+
+ const source = ctx.createBufferSource();
+ source.buffer = toBuffer(ctx, planes, channels, frames, sampleRate);
+
+ const fx = buildFxChain(ctx, chain);
+ source.connect(fx.input);
+ fx.output.connect(ctx.destination);
+ source.start();
+
+ return toPlanes(await ctx.startRendering());
+}
+
+window.__HF_AUDIO_FX = { render };
diff --git a/packages/engine/src/services/audioFxRender.test.ts b/packages/engine/src/services/audioFxRender.test.ts
new file mode 100644
index 0000000000..872b18e92e
--- /dev/null
+++ b/packages/engine/src/services/audioFxRender.test.ts
@@ -0,0 +1,247 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { applyVolumeEnvelopeToWav } from "./audioVolumeEnvelope.js";
+import { defaultAudioFxParams, type HfAudioFxChain } from "@hyperframes/core/audio-fx";
+import { applyAudioFxChain, AudioFxRenderError, readWav, writeWav } from "./audioFxRender.js";
+import { resolveHeadlessShellPath } from "./browserManager.js";
+import { getFfmpegBinary } from "../utils/ffmpegBinaries.js";
+
+/** Same probe the ffmpeg-dependent suites use: ask the binary, don't assume it. */
+const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"], { encoding: "utf-8" }).status === 0;
+
+/**
+ * Whether a Chrome is actually on this machine, asked the same way the render
+ * asks — `resolveHeadlessShellPath` is what `acquireBrowser` resolves through,
+ * so this cannot drift from the thing it is guarding the way a hard-coded cache
+ * path would.
+ *
+ * The repo's `Test` job installs ffmpeg and no browser, on purpose. Without
+ * this guard the four browser cases below fail there with a spawn error that
+ * says nothing about the code under test, and the same pattern already covers
+ * the ffmpeg-dependent suites (`describe.skipIf(!HAS_FFMPEG)`).
+ *
+ * They still run wherever a browser exists — every developer machine, and any
+ * job that has run `hyperframes browser ensure`.
+ */
+const HAS_BROWSER = ((): boolean => {
+ try {
+ const path = resolveHeadlessShellPath();
+ if (!path) return false;
+ // ASK the binary rather than trusting that the file is there. CI carries a
+ // chrome-headless-shell in its cache that resolves and then fails to spawn
+ // — a partial download is indistinguishable from a working one by
+ // existsSync, and the first version of this guard was fooled by exactly
+ // that. Same probe the ffmpeg suites use.
+ return spawnSync(path, ["--version"], { encoding: "utf-8" }).status === 0;
+ } catch {
+ // An explicitly-configured path that does not exist throws. That is a
+ // broken environment rather than an absent browser, but either way these
+ // cases cannot run.
+ return false;
+ }
+})();
+
+const SR = 48000;
+
+const chainOf = (...types: string[]): HfAudioFxChain => ({
+ version: 1,
+ nodes: types.map((t) => ({ type: t, enabled: true, params: defaultAudioFxParams(t) })),
+});
+
+let dir: string;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "hf-audiofx-"));
+});
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+/** A 440 Hz tone written as float WAV, the shape the mixer hands us. */
+function tone(path: string, seconds = 0.3, freq = 440): void {
+ const n = Math.floor(SR * seconds);
+ const s = new Float32Array(n);
+ for (let i = 0; i < n; i++) s[i] = 0.5 * Math.sin((2 * Math.PI * freq * i) / SR);
+ writeWav(path, s, SR);
+}
+
+const rms = (s: Float32Array): number =>
+ Math.sqrt(s.reduce((a, x) => a + x * x, 0) / Math.max(1, s.length));
+const db = (x: number): number => 20 * Math.log10(x + 1e-30);
+
+describe("readWav / writeWav", () => {
+ it("round-trips samples as 16-bit PCM, the format the volume bake requires", () => {
+ const p = join(dir, "rt.wav");
+ const src = new Float32Array([0, 0.5, -0.5, 0.25]);
+ writeWav(p, src, SR);
+ const back = readWav(p);
+ expect(back.sampleRate).toBe(SR);
+ expect(back.channels).toBe(1);
+ // Quantised, not bit-exact: one 16-bit step is the tolerance.
+ for (let i = 0; i < src.length; i++) {
+ expect(back.samples[i]).toBeCloseTo(src[i] as number, 4);
+ }
+ });
+
+ it("preserves the channel count, interleaved", () => {
+ // Folding to mono collapsed a stereo bed's width for the render only.
+ const p = join(dir, "stereo.wav");
+ writeWav(p, new Float32Array([0.5, -0.5, 0.25, -0.25]), SR, 2);
+ const back = readWav(p);
+ expect(back.channels).toBe(2);
+ expect(back.samples.length).toBe(4);
+ expect(back.samples[0]).toBeCloseTo(0.5, 4);
+ expect(back.samples[1]).toBeCloseTo(-0.5, 4);
+ });
+
+ it("writes a file the volume envelope baker will accept", () => {
+ // This is why the writer emits 16-bit: the mixer bakes the envelope into the
+ // samples immediately after, and that baker refuses anything else — so float
+ // output silently downgraded a track to the 32-segment ffmpeg path.
+ const p = join(dir, "bakeable.wav");
+ writeWav(p, new Float32Array(4800).fill(0.5), SR);
+ const baked = applyVolumeEnvelopeToWav(
+ p,
+ [
+ { time: 0, volume: 1 },
+ { time: 0.1, volume: 0 },
+ ],
+ 0,
+ 1,
+ );
+ expect(baked).toBe(true);
+ const after = readWav(p);
+ // Faded within the clip: the tail is quieter than the head.
+ expect(Math.abs(after.samples[4700] as number)).toBeLessThan(
+ Math.abs(after.samples[10] as number),
+ );
+ });
+
+ it("clamps past full scale rather than wrapping it into a click", () => {
+ const p = join(dir, "hot.wav");
+ writeWav(p, new Float32Array([1.8, -1.8]), SR);
+ const back = readWav(p);
+ expect(back.samples[0]).toBeCloseTo(1, 3);
+ expect(back.samples[1]).toBeCloseTo(-1, 3);
+ });
+
+ // Needs a real ffmpeg to author the 16-bit fixture. The Test job installs one,
+ // but a bare "ffmpeg" is not on PATH there — hence getFfmpegBinary above — and
+ // a contributor without it should skip rather than fail.
+ it.skipIf(!HAS_FFMPEG)("reads 16-bit PCM, which the trim step can emit", () => {
+ const p = join(dir, "pcm16.wav");
+ execFileSync(getFfmpegBinary(), [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ `sine=frequency=440:duration=0.1:sample_rate=${SR}`,
+ "-c:a",
+ "pcm_s16le",
+ "-ac",
+ "1",
+ p,
+ "-y",
+ ]);
+ const back = readWav(p);
+ expect(back.sampleRate).toBe(SR);
+ expect(back.samples.length).toBeGreaterThan(0);
+ // 16-bit values must be scaled into the float range, not left as integers.
+ expect(Math.max(...Array.from(back.samples, Math.abs))).toBeLessThanOrEqual(1);
+ });
+
+ it("refuses a file it cannot read rather than returning noise", () => {
+ const p = join(dir, "junk.wav");
+ writeFileSync(p, Buffer.from("not a wav at all"));
+ expect(() => readWav(p)).toThrow(AudioFxRenderError);
+ });
+});
+
+describe("applyAudioFxChain", () => {
+ it("returns the input untouched when nothing is enabled", async () => {
+ const input = join(dir, "in.wav");
+ tone(input);
+ const out = await applyAudioFxChain(
+ input,
+ { version: 1, nodes: [{ type: "peaking", enabled: false }] },
+ join(dir, "out.wav"),
+ { trackId: "t" },
+ );
+ expect(out).toBe(input);
+ expect(existsSync(join(dir, "out.wav"))).toBe(false);
+ });
+
+ it("throws when there is work to do but the input is missing", async () => {
+ await expect(
+ applyAudioFxChain(join(dir, "nope.wav"), chainOf("peaking"), join(dir, "out.wav"), {
+ trackId: "t",
+ }),
+ ).rejects.toThrow(/input is missing/);
+ });
+});
+
+/**
+ * These drive a real headless browser, which is the point: the render path is
+ * an OfflineAudioContext running the same graph the studio previews with. They
+ * are the only place that proves the injected runtime loads and processes
+ * audio, so they are worth the seconds they cost.
+ */
+describe.skipIf(!HAS_BROWSER)("browser render", () => {
+ it("notches out the tone it is tuned to", async () => {
+ const input = join(dir, "in.wav");
+ tone(input);
+ const outPath = join(dir, "out.wav");
+ const result = await applyAudioFxChain(
+ input,
+ {
+ version: 1,
+ nodes: [{ type: "peaking", enabled: true, params: { frequency: 440, gain: -30, q: 1 } }],
+ },
+ outPath,
+ { trackId: "t" },
+ );
+ expect(result).toBe(outPath);
+ const before = readWav(input).samples;
+ const after = readWav(outPath).samples;
+ expect(after.length).toBe(before.length);
+ expect(db(rms(after))).toBeLessThan(db(rms(before)) - 15);
+ }, 180_000);
+
+ it("runs a worklet-backed effect, not just the native nodes", async () => {
+ // The dynamics processors are AudioWorklets; if the module fails to load in
+ // the render context, this is where it surfaces.
+ const input = join(dir, "in.wav");
+ tone(input, 0.3, 200);
+ const outPath = join(dir, "out.wav");
+ await applyAudioFxChain(
+ input,
+ {
+ version: 1,
+ nodes: [
+ {
+ type: "compressor",
+ enabled: true,
+ params: { ...defaultAudioFxParams("compressor"), threshold: -40, ratio: 20 },
+ },
+ ],
+ },
+ outPath,
+ { trackId: "t" },
+ );
+ expect(db(rms(readWav(outPath).samples))).toBeLessThan(db(rms(readWav(input).samples)) - 3);
+ }, 180_000);
+
+ it("renders a multi-effect chain including reverb", async () => {
+ const input = join(dir, "in.wav");
+ tone(input);
+ const outPath = join(dir, "out.wav");
+ await applyAudioFxChain(input, chainOf("highpass", "reverb", "delay"), outPath, {
+ trackId: "t",
+ });
+ expect(readWav(outPath).samples.length).toBeGreaterThan(0);
+ }, 180_000);
+});
diff --git a/packages/engine/src/services/audioFxRender.ts b/packages/engine/src/services/audioFxRender.ts
new file mode 100644
index 0000000000..6376f6ae01
--- /dev/null
+++ b/packages/engine/src/services/audioFxRender.ts
@@ -0,0 +1,292 @@
+/**
+ * Applies an audio FX chain to a WAV at render time.
+ *
+ * The processing runs in an OfflineAudioContext inside the headless browser the
+ * engine already drives, using the same graph builders the studio previews
+ * with. There is one implementation of each effect, so the render matching the
+ * preview is a property of the architecture rather than a tolerance to police.
+ *
+ * The alternative — reimplementing every effect as an FFmpeg filter — means two
+ * implementations that have to be kept in agreement, and four of them (the
+ * dynamics processors and the modulated delays) have no filter that behaves the
+ * same way, so preview would quietly stop predicting the render.
+ */
+
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { getAudioFxRuntimeScript } from "@hyperframes/core/audio-fx-runtime";
+import { enabledAudioFxNodes, type HfAudioFxChain } from "@hyperframes/core/audio-fx";
+import { acquireBrowser } from "./browserManager.js";
+
+export class AudioFxRenderError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "AudioFxRenderError";
+ }
+}
+
+interface WavData {
+ samples: Float32Array;
+ sampleRate: number;
+ channels: number;
+}
+
+/**
+ * Minimal reader for the WAVs the mixer produces upstream. Handles 16-bit PCM
+ * and 32-bit float, the two formats the trim/extract steps emit; anything else
+ * is refused rather than silently misread as noise.
+ */
+/** Walk the chunks for the format and the payload, in whatever order they sit. */
+function readWavChunks(buf: Buffer): {
+ format: number;
+ channels: number;
+ sampleRate: number;
+ bits: number;
+ data?: Buffer;
+} {
+ let offset = 12;
+ const head = { format: 1, channels: 1, sampleRate: 48000, bits: 16 };
+ let data: Buffer | undefined;
+ while (offset + 8 <= buf.length) {
+ const id = buf.toString("ascii", offset, offset + 4);
+ const size = buf.readUInt32LE(offset + 4);
+ if (id === "fmt ") {
+ head.format = buf.readUInt16LE(offset + 8);
+ head.channels = buf.readUInt16LE(offset + 10);
+ head.sampleRate = buf.readUInt32LE(offset + 12);
+ head.bits = buf.readUInt16LE(offset + 22);
+ } else if (id === "data") {
+ data = buf.subarray(offset + 8, Math.min(buf.length, offset + 8 + size));
+ break;
+ }
+ offset += 8 + size + (size % 2);
+ }
+ return { ...head, data };
+}
+
+export function readWav(path: string): WavData {
+ const buf = readFileSync(path);
+ if (buf.length < 44 || buf.toString("ascii", 0, 4) !== "RIFF") {
+ throw new AudioFxRenderError(`Not a WAV file: ${path}`);
+ }
+ const { format, channels, sampleRate, bits, data } = readWavChunks(buf);
+ if (!data) throw new AudioFxRenderError(`WAV has no data chunk: ${path}`);
+ return { samples: decodeSamples(data, format, bits, path), sampleRate, channels };
+}
+
+/** Interleaved samples as floats, for the two formats the mixer emits upstream. */
+function decodeSamples(data: Buffer, format: number, bits: number, path: string): Float32Array {
+ if (format === 3 && bits === 32) {
+ const n = Math.floor(data.length / 4);
+ // A Float32Array view demands a 4-aligned offset, and chunk layouts that put
+ // `data` on an odd boundary (an 18-byte fmt plus a fact chunk, which
+ // ffmpeg's pcm_f32le writes) would otherwise throw RangeError. Copy then.
+ if (data.byteOffset % 4 === 0) return new Float32Array(data.buffer, data.byteOffset, n);
+ const copied = new Float32Array(n);
+ for (let i = 0; i < n; i++) copied[i] = data.readFloatLE(i * 4);
+ return copied;
+ }
+ if (format === 1 && bits === 16) {
+ const n = Math.floor(data.length / 2);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i++) out[i] = data.readInt16LE(i * 2) / 32768;
+ return out;
+ }
+ throw new AudioFxRenderError(`Unsupported WAV format ${format}/${bits}-bit: ${path}`);
+}
+
+/**
+ * Write 16-bit PCM, interleaved, preserving the channel count.
+ *
+ * 16-bit rather than the float32 this used to emit: the very next step in the
+ * mixer bakes the volume envelope into the samples, and that baker accepts only
+ * 16-bit PCM. Emitting float meant enabling any effect silently downgraded a
+ * track's volume automation to the ffmpeg expression path, which is capped at 32
+ * straight segments — so a curved envelope was quantised and a dense one could
+ * fall back to rendering at base volume.
+ */
+export function writeWav(
+ path: string,
+ samples: Float32Array,
+ sampleRate: number,
+ channels = 1,
+): void {
+ const n = samples.length;
+ const bytes = n * 2;
+ const buf = Buffer.alloc(44 + bytes);
+ buf.write("RIFF", 0, "ascii");
+ buf.writeUInt32LE(36 + bytes, 4);
+ buf.write("WAVE", 8, "ascii");
+ buf.write("fmt ", 12, "ascii");
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20); // WAVE_FORMAT_PCM
+ buf.writeUInt16LE(channels, 22);
+ buf.writeUInt32LE(sampleRate, 24);
+ buf.writeUInt32LE(sampleRate * channels * 2, 28);
+ buf.writeUInt16LE(channels * 2, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36, "ascii");
+ buf.writeUInt32LE(bytes, 40);
+ for (let i = 0; i < n; i++) {
+ // Clamp before scaling: a limiter set to 0 dB or a resonant filter can push
+ // past full scale, and wrapping would turn that into a click.
+ const v = Math.max(-1, Math.min(1, samples[i] ?? 0));
+ buf.writeInt16LE(Math.round(v * 32767), 44 + i * 2);
+ }
+ // lgtm[js/insecure-temporary-file] — `path` is always inside a directory the
+ // caller made with `mkdtempSync`, never a name assembled directly under
+ // `tmpdir()`. Both routes here are covered: the browser host page writes into
+ // `mkdtempSync(join(tmpdir(), "hf-fx-host-"))` below, and the render output
+ // goes to the producer's work dir, itself created as
+ // `mkdtempSync(join(tempRoot, "producer-project-"))`. mkdtemp picks the random
+ // suffix and creates the directory 0700 in one syscall, so the predictable
+ // FILENAME inside it (`<elementId>-fx.wav`) cannot be pre-created or
+ // symlinked by another user — which is the attack this rule is about. CodeQL
+ // flags it because the dataflow reaches `tmpdir()` without seeing the mkdtemp
+ // in between.
+ writeFileSync(path, buf);
+}
+
+/**
+ * Split an interleaved buffer into one array per channel.
+ *
+ * The graph used to fold everything to mono, which collapsed a stereo bed's
+ * width for the render only — and cost ~3 dB through the very mono-to-stereo
+ * rematrix that `prepareAudioTrack`'s pan filter exists to avoid. Preview kept
+ * the track stereo, so the two diverged the moment any effect was enabled.
+ */
+function deinterleave(samples: Float32Array, channels: number): Float32Array[] {
+ if (channels <= 1) return [samples];
+ const frames = Math.floor(samples.length / channels);
+ const out = Array.from({ length: channels }, () => new Float32Array(frames));
+ for (let i = 0; i < frames; i++) {
+ for (let c = 0; c < channels; c++) {
+ (out[c] as Float32Array)[i] = samples[i * channels + c] ?? 0;
+ }
+ }
+ return out;
+}
+
+/** Re-interleave per-channel arrays for the WAV writer. */
+function interleave(planes: readonly Float32Array[]): Float32Array {
+ if (planes.length === 1) return planes[0] as Float32Array;
+ const frames = planes[0]?.length ?? 0;
+ const out = new Float32Array(frames * planes.length);
+ for (let i = 0; i < frames; i++) {
+ for (let c = 0; c < planes.length; c++) {
+ out[i * planes.length + c] = (planes[c] as Float32Array)[i] ?? 0;
+ }
+ }
+ return out;
+}
+
+/**
+ * Run a chain over `inputWav`, writing `outputWav`. Resolves to the path to use
+ * downstream: `outputWav` when the chain did something, `inputWav` untouched
+ * when the chain was empty.
+ *
+ * Failure is fatal to the caller rather than a soft per-track warning: quietly
+ * rendering the dry signal ships a mix that sounds plausible and is not what
+ * the author set up.
+ */
+export async function applyAudioFxChain(
+ inputWav: string,
+ chain: HfAudioFxChain,
+ outputWav: string,
+ options: { trackId: string; signal?: AbortSignal },
+): Promise<string> {
+ if (enabledAudioFxNodes(chain).length === 0) return inputWav;
+ if (!existsSync(inputWav)) {
+ throw new AudioFxRenderError(`Audio FX input is missing: ${inputWav}`);
+ }
+
+ const { samples, sampleRate, channels } = readWav(inputWav);
+ const planes = deinterleave(samples, channels);
+
+ // Audio processing needs no GPU or special capture mode; a plain sandboxed
+ // browser is enough, and the lease pool reuses one across tracks.
+ const lease = await acquireBrowser([
+ "--no-sandbox",
+ "--autoplay-policy=no-user-gesture-required",
+ ]);
+ const hostDir = mkdtempSync(join(tmpdir(), "hf-fx-host-"));
+ try {
+ if (options.signal?.aborted) {
+ throw new AudioFxRenderError(`Audio FX cancelled for track ${options.trackId}`);
+ }
+ const page = await lease.browser.newPage();
+ try {
+ // AudioWorklet is only exposed in a secure context, and about:blank is
+ // not one — the module would fail with an opaque error. A file:// page
+ // qualifies and needs no listening socket.
+ const hostPage = join(hostDir, "audio-fx.html");
+ writeFileSync(hostPage, "<!doctype html><meta charset=utf-8><title>audio fx</title>");
+ await page.goto(pathToFileURL(hostPage).href, { waitUntil: "domcontentloaded" });
+ await page.addScriptTag({ content: getAudioFxRuntimeScript() });
+
+ const rendered = (await page.evaluate(
+ async ([channelB64, rate, chainJson]: [string[], number, string]) => {
+ const decode = (b64: string): Float32Array => {
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ return new Float32Array(bytes.buffer);
+ };
+ const api = (
+ window as unknown as {
+ __HF_AUDIO_FX?: {
+ render(p: Float32Array[], r: number, c: string): Promise<Float32Array[]>;
+ };
+ }
+ ).__HF_AUDIO_FX;
+ if (!api) throw new Error("audio FX runtime failed to load");
+ const out = await api.render(channelB64.map(decode), rate, chainJson);
+ const encode = (plane: Float32Array): string => {
+ const u8 = new Uint8Array(plane.buffer, plane.byteOffset, plane.length * 4);
+ let s = "";
+ const CHUNK = 0x8000;
+ for (let i = 0; i < u8.length; i += CHUNK) {
+ s += String.fromCharCode.apply(null, Array.from(u8.subarray(i, i + CHUNK)));
+ }
+ return btoa(s);
+ };
+ return out.map(encode);
+ },
+ [
+ planes.map((plane) =>
+ Buffer.from(plane.buffer, plane.byteOffset, plane.length * 4).toString("base64"),
+ ),
+ sampleRate,
+ JSON.stringify(chain),
+ ] as [string[], number, string],
+ )) as string[];
+
+ // byteOffset and byteLength matter: Node pools small allocations, so a
+ // short payload decodes into an 8 KiB pool and a view over the whole
+ // ArrayBuffer would read kilobytes of unrelated memory at the wrong length.
+ const outPlanes = rendered.map((b64) => {
+ const buf = Buffer.from(b64, "base64");
+ return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
+ });
+ if (outPlanes.length === 0 || (outPlanes[0]?.length ?? 0) === 0) {
+ throw new AudioFxRenderError(`Audio FX produced no samples for track ${options.trackId}`);
+ }
+ writeWav(outputWav, interleave(outPlanes), sampleRate, outPlanes.length);
+ return outputWav;
+ } finally {
+ await page.close().catch(() => undefined);
+ }
+ } catch (err) {
+ if (err instanceof AudioFxRenderError) throw err;
+ throw new AudioFxRenderError(
+ `Audio FX failed for track ${options.trackId}: ${(err as Error).message}`,
+ );
+ } finally {
+ rmSync(hostDir, { recursive: true, force: true });
+ await lease.release().catch(() => undefined);
+ }
+}
+
+export type { HfAudioFxChain };
diff --git a/packages/engine/src/services/audioMixer.test.ts b/packages/engine/src/services/audioMixer.test.ts
index 74fd07a9c5..d0b1aa1db2 100644
--- a/packages/engine/src/services/audioMixer.test.ts
+++ b/packages/engine/src/services/audioMixer.test.ts
@@ -957,3 +957,18 @@ describe("parseAudioElements — hidden tracks", () => {
]);
});
});
+
+describe("parseAudioElements data-fx-chain", () => {
+ it("captures the serialised chain when present", () => {
+ const chain = `{"version":1,"nodes":[{"type":"peaking"}]}`;
+ const html = `<audio id="music" src="bgm.mp3" data-start="0" data-end="10" data-fx-chain='${chain}'></audio>`;
+ const [el] = parseAudioElements(html);
+ expect(el!.fxChain).toBe(chain);
+ });
+
+ it("leaves fxChain undefined when the attribute is absent", () => {
+ const html = `<audio id="music" src="bgm.mp3" data-start="0" data-end="10"></audio>`;
+ const [el] = parseAudioElements(html);
+ expect(el!.fxChain).toBeUndefined();
+ });
+});
diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts
index cb0da8f854..c08d092445 100644
--- a/packages/engine/src/services/audioMixer.ts
+++ b/packages/engine/src/services/audioMixer.ts
@@ -29,6 +29,8 @@ import type {
MixResult,
} from "./audioMixer.types.js";
import { applyVolumeEnvelopeToWav } from "./audioVolumeEnvelope.js";
+import { HF_AUDIO_FX_ATTR, parseAudioFxChain } from "@hyperframes/core/audio-fx";
+import { applyAudioFxChain, AudioFxRenderError } from "./audioFxRender.js";
export type { AudioElement, MixResult } from "./audioMixer.types.js";
@@ -366,6 +368,7 @@ export function parseAudioElements(html: string): AudioElement[] {
const mediaStartAttr = el.getAttribute("data-media-start");
const layerAttr = el.getAttribute("data-layer");
const volumeAttr = el.getAttribute("data-volume");
+ const fxChain = el.getAttribute(HF_AUDIO_FX_ATTR);
return {
id,
src: el.getAttribute("src") as string,
@@ -374,6 +377,7 @@ export function parseAudioElements(html: string): AudioElement[] {
mediaStart: mediaStartAttr ? parseFloat(mediaStartAttr) : 0,
layer: layerAttr ? parseInt(layerAttr) : 0,
volume: volumeAttr ? parseFloat(volumeAttr) : 1.0,
+ ...(fxChain ? { fxChain } : {}),
type,
};
};
@@ -717,9 +721,21 @@ export async function processCompositionAudio(
if (!existsSync(workDir)) mkdirSync(workDir, { recursive: true });
+ // Every element's work races under Promise.all, which rejects on the first
+ // failure without waiting for its siblings. A fatal FX error therefore has to
+ // be able to abort the in-flight ffmpeg runs before the finally-block removes
+ // workDir out from under them. Chained off the caller's signal so external
+ // cancellation still behaves as before.
+ const internalController = new AbortController();
+ const effectiveSignal = internalController.signal;
+ if (signal) {
+ if (signal.aborted) internalController.abort();
+ else signal.addEventListener("abort", () => internalController.abort(), { once: true });
+ }
+
await Promise.all(
elements.map(async (element) => {
- if (signal?.aborted) {
+ if (effectiveSignal.aborted) {
failures.push({
stage: "cancelled",
reason: "cancelled",
@@ -854,6 +870,24 @@ export async function processCompositionAudio(
audioSrcPath = trimmedPath;
}
+ // Apply the track's FX chain to the dry, trimmed audio, before volume
+ // automation is baked in: effects should see the raw signal, and the
+ // envelope belongs on their output. A missing or broken chain is fatal
+ // for the whole mix rather than a per-track warning — quietly rendering
+ // the dry signal ships a mix that sounds plausible and is wrong.
+ if (element.fxChain) {
+ // The chain is serialised into the attribute, the same way colour
+ // grading carries its config, so there is no side-car file to find,
+ // resolve or lose.
+ const chain = parseAudioFxChain(element.fxChain);
+ audioSrcPath = await applyAudioFxChain(
+ audioSrcPath,
+ chain,
+ join(workDir, `${element.id}-fx.wav`),
+ { trackId: element.id, signal: effectiveSignal },
+ );
+ }
+
// Primary volume-automation path: bake the envelope into the PCM samples
// (sample-accurate, no keyframe ceiling). If the WAV isn't the expected
// 16-bit PCM, fall back to the ffmpeg expression path by leaving the
@@ -879,6 +913,11 @@ export async function processCompositionAudio(
volumeKeyframes: bakedEnvelope ? undefined : element.volumeKeyframes,
});
} catch (err: unknown) {
+ // An FX failure is fatal for the whole mix. Every other failure mode
+ // degrades gracefully — the track drops and siblings continue — but
+ // substituting the dry signal for a processed one ships a render that
+ // sounds plausible and is not what was authored.
+ if (err instanceof AudioFxRenderError) throw err;
failures.push({
stage: "internal",
reason: "internal",
@@ -893,7 +932,17 @@ export async function processCompositionAudio(
});
}
}),
- );
+ ).catch((err: unknown) => {
+ // Promise.all rejected on the first fatal failure without waiting for its
+ // siblings; abort them so their ffmpeg stops before workDir disappears.
+ internalController.abort();
+ try {
+ rmSync(workDir, { recursive: true, force: true });
+ } catch {
+ /* ignore */
+ }
+ throw err;
+ });
// Never turn a per-track preparation failure into a successful partial mix.
// The producer only surfaces audio failures when `success` is false; mixing
diff --git a/packages/engine/src/services/audioMixer.types.ts b/packages/engine/src/services/audioMixer.types.ts
index a599e1d675..0316d01e7d 100644
--- a/packages/engine/src/services/audioMixer.types.ts
+++ b/packages/engine/src/services/audioMixer.types.ts
@@ -12,6 +12,8 @@ export interface AudioElement {
layer: number;
volume?: number;
volumeKeyframes?: AudioVolumeKeyframe[];
+ /** Serialised FX chain JSON from `data-fx-chain`, when set. */
+ fxChain?: string;
type: "audio" | "video";
}
diff --git a/packages/producer/src/services/render/stages/audioStage.test.ts b/packages/producer/src/services/render/stages/audioStage.test.ts
index c64dde37c3..7be552b084 100644
--- a/packages/producer/src/services/render/stages/audioStage.test.ts
+++ b/packages/producer/src/services/render/stages/audioStage.test.ts
@@ -110,4 +110,32 @@ describe("runAudioStage", () => {
expect(result.audioError).toBeUndefined();
expect(result.audioFailures).toBeUndefined();
});
+
+ it("reports a rejection as audioError instead of letting it escape the stage", async () => {
+ // An FX failure the mixer cannot degrade past rejects rather than returning a
+ // result. Escaping here would reach the orchestrator as an unclassified
+ // pipeline exception, losing the stage/owner/retryable classification — and
+ // skipping the abort check this stage runs.
+ processCompositionAudioMock.mockRejectedValue(
+ new Error("Audio FX failed for track bgm: browser launch failed"),
+ );
+ const result = await runAudioStage(makeInput());
+ expect(result.hasAudio).toBe(false);
+ expect(result.audioError).toMatch(/Audio FX failed for track bgm/);
+ expect(result.audioFailures).toBeUndefined();
+ });
+
+ it("lets an abort keep its own shape rather than becoming an audio error", async () => {
+ processCompositionAudioMock.mockRejectedValue(new Error("boom"));
+ const aborted = new Error("render aborted");
+ await expect(
+ runAudioStage(
+ makeInput({
+ assertNotAborted: () => {
+ throw aborted;
+ },
+ }),
+ ),
+ ).rejects.toBe(aborted);
+ });
});
diff --git a/packages/producer/src/services/render/stages/audioStage.ts b/packages/producer/src/services/render/stages/audioStage.ts
index ddcbdaa28f..89739aede6 100644
--- a/packages/producer/src/services/render/stages/audioStage.ts
+++ b/packages/producer/src/services/render/stages/audioStage.ts
@@ -66,16 +66,35 @@ export async function runAudioStage(input: AudioStageInput): Promise<AudioStageR
let audioFailures: AudioProcessingFailure[] | undefined;
if (audios.length > 0) {
- const audioResult = await processCompositionAudio(
- audios,
- projectDir,
- join(workDir, "audio-work"),
- audioOutputPath,
- duration,
- abortSignal,
- undefined,
- compiledDir,
- );
+ // processCompositionAudio reports per-track failures in its result, but an FX
+ // failure it cannot degrade past — a browser that will not launch, a chain
+ // that will not build — rejects instead. Caught here so it lands in
+ // `audioError` with the rest, rather than escaping as an unclassified
+ // pipeline exception and losing the stage/owner/retryable classification
+ // this stage exists to attach.
+ let audioResult: Awaited<ReturnType<typeof processCompositionAudio>>;
+ try {
+ audioResult = await processCompositionAudio(
+ audios,
+ projectDir,
+ join(workDir, "audio-work"),
+ audioOutputPath,
+ duration,
+ abortSignal,
+ undefined,
+ compiledDir,
+ );
+ } catch (err) {
+ // An abort is the caller's own signal and must keep its own shape.
+ assertNotAborted();
+ return {
+ audioOutputPath,
+ hasAudio: false,
+ audioProcessMs: Date.now() - stage3Start,
+ audioError: err instanceof Error ? err.message : String(err),
+ audioFailures: undefined,
+ };
+ }
assertNotAborted();
hasAudio = audioResult.success;