Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(engine): harden grouped audio rendering (#3446)
Vance Ingalls1aec3b4a09ea
diff --git a/packages/engine/src/services/audioFxRender.ts b/packages/engine/src/services/audioFxRender.tsindex fb5af4f44f..8c977d4fb6 100644--- a/packages/engine/src/services/audioFxRender.ts+++ b/packages/engine/src/services/audioFxRender.ts@@ -35,6 +35,9 @@ interface WavData {samples: Float32Array;sampleRate: number;channels: number;+ /** True when the source was 32-bit float rather than 16-bit PCM. Carried so+ * the output can be written back in the same format — see `writeWav`. */+ float: boolean;}/**@@ -77,7 +80,12 @@ export function readWav(path: string): WavData {}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 };+ return {+ samples: decodeSamples(data, format, bits, path),+ sampleRate,+ channels,+ float: format === 3 && bits === 32,+ };}/** Interleaved samples as floats, for the two formats the mixer emits upstream. */@@ -102,38 +110,51 @@ function decodeSamples(data: Buffer, format: number, bits: number, path: string)}/**- * Write 16-bit PCM, interleaved, preserving the channel count.+ * Write interleaved samples, preserving the channel count.+ *+ * 16-bit by default 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+ * accepted 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.*- * 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.+ * `float` opts back out, for the ONE input that needs it: a group sub-mix. Its+ * members sum at unity, so the sum can legitimately exceed full scale, and the+ * group's fader is applied downstream — clamping here handed that headroom back+ * one step before the thing that was going to reduce it, which is the same bug+ * the float intermediate exists to avoid. Safe now only because the envelope+ * baker reads float too; before that it was not.*/export function writeWav(path: string,samples: Float32Array,sampleRate: number,channels = 1,+ float = false,): void {const n = samples.length;- const bytes = n * 2;+ const bytesPerSample = float ? 4 : 2;+ const bytes = n * bytesPerSample;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(float ? 3 : 1, 20); // IEEE_FLOAT / PCMbuf.writeUInt16LE(channels, 22);buf.writeUInt32LE(sampleRate, 24);- buf.writeUInt32LE(sampleRate * channels * 2, 28);- buf.writeUInt16LE(channels * 2, 32);- buf.writeUInt16LE(16, 34);+ buf.writeUInt32LE(sampleRate * channels * bytesPerSample, 28);+ buf.writeUInt16LE(channels * bytesPerSample, 32);+ buf.writeUInt16LE(float ? 32 : 16, 34);buf.write("data", 36, "ascii");buf.writeUInt32LE(bytes, 40);for (let i = 0; i < n; i++) {+ if (float) {+ buf.writeFloatLE(samples[i] ?? 0, 44 + i * 4);+ continue;+ }// 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));@@ -267,7 +288,7 @@ export async function applyAudioFxChain(throw new AudioFxRenderError(`Audio FX input is missing: ${inputWav}`);}- const { samples, sampleRate, channels } = readWav(inputWav);+ const { samples, sampleRate, channels, float } = readWav(inputWav);const planes = deinterleave(samples, channels);// An empty track has nothing to process — and an OfflineAudioContext of zero// length throws, which is fatal for the WHOLE render rather than this track:@@ -303,118 +324,26 @@ export async function applyAudioFxChain(await page.goto(pathToFileURL(hostPage).href, { waitUntil: "domcontentloaded" });await page.addScriptTag({ content: getAudioFxRuntimeScript() });- // Hand the input over a chunk at a time. The chunks stay separate byte- // arrays page-side rather than being concatenated into one string, so- // neither the frame cap nor V8's string limit sees the whole track.- await page.evaluate((count: number) => {- (window as unknown as AudioFxWindow).__HF_FX_IO = {- in: Array.from({ length: count }, (): Uint8Array[] => []),- out: [],- };- }, planes.length);+ await sendPlanesToPage(page, planes);- for (let p = 0; p < planes.length; p += 1) {- const plane = planes[p];- if (!plane) continue;- const bytes = Buffer.from(plane.buffer, plane.byteOffset, plane.length * 4);- for (let at = 0; at < bytes.length; at += TRANSFER_BYTES) {- await page.evaluate(- ([index, b64]: [number, string]) => {- const bin = atob(b64);- const chunk = new Uint8Array(bin.length);- for (let i = 0; i < bin.length; i++) chunk[i] = bin.charCodeAt(i);- (window as unknown as AudioFxWindow).__HF_FX_IO?.in[index]?.push(chunk);- },- [p, bytes.subarray(at, at + TRANSFER_BYTES).toString("base64")] as [number, string],- );- }- }-- const outLengths = (await page.evaluate(- async ([rate, chainJson, automationJson]: [number, string, string]) => {- const w = window as unknown as AudioFxWindow;- const io = w.__HF_FX_IO;- if (!w.__HF_AUDIO_FX || !io) throw new Error("audio FX runtime failed to load");- const inPlanes = io.in.map((chunks) => {- const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));- let at = 0;- for (const chunk of chunks) {- bytes.set(chunk, at);- at += chunk.length;- }- return new Float32Array(bytes.buffer);- });- // Dropped before the render allocates its own buffers, so the page- // does not hold two copies of the track at once.- io.in = [];- io.out = await w.__HF_AUDIO_FX.render(- inPlanes,- rate,- chainJson,- automationJson || undefined,- );- return io.out.map((plane) => plane.length);- },- [- sampleRate,- JSON.stringify(chain),- options.automation ? serializeAutomation(options.automation) : "",- ] as [number, string, string],- )) as number[];-- const outPlanes: Float32Array[] = [];- for (let p = 0; p < outLengths.length; p += 1) {- const byteLength = (outLengths[p] ?? 0) * 4;- const parts: Buffer[] = [];- for (let at = 0; at < byteLength; at += TRANSFER_BYTES) {- const b64 = (await page.evaluate(- ([index, offset, limit]: [number, number, number]) => {- const plane = (window as unknown as AudioFxWindow).__HF_FX_IO?.out[index];- if (!plane) return "";- const u8 = new Uint8Array(- plane.buffer,- plane.byteOffset + offset,- Math.min(limit, plane.length * 4 - offset),- );- let s = "";- const CHUNK = 0x8000;- for (let i = 0; i < u8.length; i += CHUNK) {- // `apply` takes array-likes, so the subarray goes in as it is;- // Array.from boxed every byte of a 32 KiB window for nothing.- s += String.fromCharCode.apply(- null,- u8.subarray(i, i + CHUNK) as unknown as number[],- );- }- return btoa(s);- },- [p, at, TRANSFER_BYTES] as [number, number, number],- )) as string;- parts.push(Buffer.from(b64, "base64"));- }- // 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 buf = Buffer.concat(parts);- outPlanes.push(- new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)),- );- }+ const outLengths = await renderPlanesInPage(+ page,+ sampleRate,+ chain,+ options.automation ? serializeAutomation(options.automation) : "",+ );+ const outPlanes = await readPlanesFromPage(page, outLengths);if (outPlanes.length === 0 || (outPlanes[0]?.length ?? 0) === 0) {throw new AudioFxRenderError(`Audio FX produced no samples for track ${options.trackId}`);}// Null when the keyframes normalise away to nothing — then the mixer's// own paths still own this track's gain, so say so rather than claiming// a bake that never happened.- const gainAt = options.envelope- ? createEnvelopeWalker(- options.envelope.keyframes,- options.envelope.trackStart,- options.envelope.baseVolume,- )- : null;+ const gainAt = envelopeWalkerFor(options.envelope);if (gainAt) applyEnvelopeToPlanes(outPlanes, sampleRate, gainAt);- writeWav(outputWav, interleave(outPlanes), sampleRate, outPlanes.length);+ // Same format in as out: a float input is a group sub-mix whose headroom+ // must survive to its fader (see writeWav).+ writeWav(outputWav, interleave(outPlanes), sampleRate, outPlanes.length, float);return { path: outputWav, envelopeBaked: gainAt !== null };} finally {await page.close().catch(() => undefined);@@ -430,4 +359,127 @@ export async function applyAudioFxChain(}}+/** The page handle `acquireBrowser().browser.newPage()` returns. */+type FxPage = Awaited<ReturnType<Awaited<ReturnType<typeof acquireBrowser>>["browser"]["newPage"]>>;++/**+ * Hand the input planes to the page a chunk at a time.+ *+ * The chunks stay separate byte arrays page-side rather than being concatenated+ * into one string, so neither the CDP frame cap nor V8's string limit ever sees+ * the whole track.+ */+async function sendPlanesToPage(page: FxPage, planes: readonly Float32Array[]): Promise<void> {+ await page.evaluate((count: number) => {+ (window as unknown as AudioFxWindow).__HF_FX_IO = {+ in: Array.from({ length: count }, (): Uint8Array[] => []),+ out: [],+ };+ }, planes.length);++ for (let p = 0; p < planes.length; p += 1) {+ const plane = planes[p];+ if (!plane) continue;+ const bytes = Buffer.from(plane.buffer, plane.byteOffset, plane.length * 4);+ for (let at = 0; at < bytes.length; at += TRANSFER_BYTES) {+ await page.evaluate(+ ([index, b64]: [number, string]) => {+ const bin = atob(b64);+ const chunk = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) chunk[i] = bin.charCodeAt(i);+ (window as unknown as AudioFxWindow).__HF_FX_IO?.in[index]?.push(chunk);+ },+ [p, bytes.subarray(at, at + TRANSFER_BYTES).toString("base64")] as [number, string],+ );+ }+ }+}++/** Run the chain in the page and return each output plane's sample count. The+ * samples themselves stay page-side until `readPlanesFromPage` pulls them. */+async function renderPlanesInPage(+ page: FxPage,+ sampleRate: number,+ chain: HfAudioFxChain,+ automationJson: string,+): Promise<number[]> {+ return (await page.evaluate(+ async ([rate, chainJson, automation]: [number, string, string]) => {+ const w = window as unknown as AudioFxWindow;+ const io = w.__HF_FX_IO;+ if (!w.__HF_AUDIO_FX || !io) throw new Error("audio FX runtime failed to load");+ const inPlanes = io.in.map((chunks) => {+ const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));+ let at = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, at);+ at += chunk.length;+ }+ return new Float32Array(bytes.buffer);+ });+ // Dropped before the render allocates its own buffers, so the page does+ // not hold two copies of the track at once.+ io.in = [];+ io.out = await w.__HF_AUDIO_FX.render(inPlanes, rate, chainJson, automation || undefined);+ return io.out.map((plane) => plane.length);+ },+ [sampleRate, JSON.stringify(chain), automationJson] as [number, string, string],+ )) as number[];+}++/** Pull one output plane back over CDP, `TRANSFER_BYTES` at a time. */+async function readPlaneFromPage(+ page: FxPage,+ index: number,+ byteLength: number,+): Promise<Float32Array> {+ const parts: Buffer[] = [];+ for (let at = 0; at < byteLength; at += TRANSFER_BYTES) {+ const b64 = (await page.evaluate(+ ([plane_index, offset, limit]: [number, number, number]) => {+ const plane = (window as unknown as AudioFxWindow).__HF_FX_IO?.out[plane_index];+ if (!plane) return "";+ const u8 = new Uint8Array(+ plane.buffer,+ plane.byteOffset + offset,+ Math.min(limit, plane.length * 4 - offset),+ );+ let s = "";+ const CHUNK = 0x8000;+ for (let i = 0; i < u8.length; i += CHUNK) {+ // `apply` takes array-likes, so the subarray goes in as it is;+ // Array.from boxed every byte of a 32 KiB window for nothing.+ s += String.fromCharCode.apply(null, u8.subarray(i, i + CHUNK) as unknown as number[]);+ }+ return btoa(s);+ },+ [index, at, TRANSFER_BYTES] as [number, number, number],+ )) as string;+ parts.push(Buffer.from(b64, "base64"));+ }+ // 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 buf = Buffer.concat(parts);+ return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));+}++async function readPlanesFromPage(page: FxPage, outLengths: number[]): Promise<Float32Array[]> {+ const outPlanes: Float32Array[] = [];+ for (let p = 0; p < outLengths.length; p += 1) {+ outPlanes.push(await readPlaneFromPage(page, p, (outLengths[p] ?? 0) * 4));+ }+ return outPlanes;+}++/** The envelope walker for a track that has keyframes, or null when it has none. */+function envelopeWalkerFor(+ envelope:+ | { keyframes: AudioVolumeKeyframe[]; trackStart: number; baseVolume: number }+ | undefined,+): ReturnType<typeof createEnvelopeWalker> | null {+ if (!envelope) return null;+ return createEnvelopeWalker(envelope.keyframes, envelope.trackStart, envelope.baseVolume);+}+export type { HfAudioFxChain, HfAutomation };diff --git a/packages/engine/src/services/audioMixer.grouping.test.ts b/packages/engine/src/services/audioMixer.grouping.test.tsindex bdd23e1ec1..a3f0ab87fc 100644--- a/packages/engine/src/services/audioMixer.grouping.test.ts+++ b/packages/engine/src/services/audioMixer.grouping.test.ts@@ -1,10 +1,10 @@import { spawnSync } from "node:child_process";-import { mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { getFfmpegBinary } from "../utils/ffmpegBinaries.js";-import { MIXED_AUDIO_FILENAME, processCompositionAudio } from "./audioMixer.js";+import { MIXED_AUDIO_FILENAME, parseAudioElements, processCompositionAudio } from "./audioMixer.js";/*** Level arithmetic across the mix graph.@@ -21,45 +21,6 @@ import { MIXED_AUDIO_FILENAME, processCompositionAudio } from "./audioMixer.js";* loud. These tests are the instrument that catches that class.*/-/**- * The production ffmpeg process timeout is 5 minutes — far above any test- * budget — so a stalled mix could only ever surface here as a bare- * "Test timed out in 30000ms": no stderr, no clue which stage hung. That is- * what made the Windows CI failure from this file undiagnosable. Capping it- * well under the per-test timeout turns a stall into a fast, reported failure,- * while leaving a merely slow runner room to finish.- */-const TEST_FFMPEG_TIMEOUT_MS = 20_000;--/**- * `processCompositionAudio` with the short process timeout, throwing the- * recorded failures rather than returning `success: false`. Every call here- * asserts success immediately afterwards, so a bare `expected false to be true`- * was all a broken mix ever reported — the reason was sitting unread in- * `failures`.- */-async function mixAudio(- elements: Parameters<typeof processCompositionAudio>[0],- baseDir: string,- workDir: string,- outputPath: string,- totalDuration: number,-): ReturnType<typeof processCompositionAudio> {- const result = await processCompositionAudio(- elements,- baseDir,- workDir,- outputPath,- totalDuration,- undefined,- { ffmpegProcessTimeout: TEST_FFMPEG_TIMEOUT_MS },- );- if (!result.success) {- throw new Error(`mix failed: ${JSON.stringify(result.failures ?? result, null, 2)}`);- }- return result;-}-const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"], { encoding: "utf-8" }).status === 0;const tempDirs: string[] = [];@@ -102,6 +63,35 @@ function writeTone(path: string, freq: number, seconds: number, gain: number): vif (result.status !== 0) throw new Error(`Could not write tone: ${result.stderr}`);}+/**+ * A sine of an EXACT peak amplitude.+ *+ * `writeTone` builds on ffmpeg's `sine` source, whose output is ~0.125 full+ * scale, so its `gain` argument is a relative knob rather than a level: a tone+ * asked for at 0.7 lands at about -21 dBFS. Fine for the relative comparisons+ * above, useless for anything about headroom — `aevalsrc` states the amplitude+ * outright.+ */+function writePeakTone(path: string, freq: number, seconds: number, peak: number): void {+ const result = spawnSync(+ getFfmpegBinary(),+ [+ "-nostdin",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ `aevalsrc=${peak}*sin(2*PI*${freq}*t):d=${seconds}:s=48000`,+ "-c:a",+ "pcm_s16le",+ path,+ ],+ { encoding: "utf-8" },+ );+ if (result.status !== 0) throw new Error(`Could not write tone: ${result.stderr}`);+}+const track = (id: string, end: number, volume = 1) => ({id,src: `${id}.wav`,@@ -113,180 +103,444 @@ const track = (id: string, end: number, volume = 1) => ({type: "audio" as const,});-describe.skipIf(!HAS_FFMPEG)("mix level arithmetic", () => {- afterEach(() => {- for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });- });+// Every case here mixes with REAL ffmpeg, and vitest's default 5s per test is not+// enough for that on a Windows runner — two cases timed out there while passing+// everywhere else (PR #3363). The suite-level timeout covers all of them at once.+describe.skipIf(!HAS_FFMPEG)(+ "mix level arithmetic",+ () => {+ afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+ });- it("keeps every track at its authored level regardless of how many there are", async () => {- // The property the compensation exists to hold: adding tracks must not- // duck the ones already there. Mixing the SAME tone twice is the cleanest- // probe — two coherent copies sum to exactly +6.02 dB, so any residual- // normalisation shows up as a plain arithmetic miss rather than something- // that has to be teased out of unrelated material.- const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-count-"));- const workDir = mkdtempSync(join(tmpdir(), "hf-grp-count-work-"));- tempDirs.push(projectDir, workDir);+ it("keeps every track at its authored level regardless of how many there are", async () => {+ // The property the compensation exists to hold: adding tracks must not+ // duck the ones already there. Mixing the SAME tone twice is the cleanest+ // probe — two coherent copies sum to exactly +6.02 dB, so any residual+ // normalisation shows up as a plain arithmetic miss rather than something+ // that has to be teased out of unrelated material.+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-count-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-count-work-"));+ tempDirs.push(projectDir, workDir);- writeTone(join(projectDir, "a.wav"), 440, 2, 0.4);- writeTone(join(projectDir, "b.wav"), 440, 2, 0.4);- const oneUp = join(projectDir, `one-${MIXED_AUDIO_FILENAME}`);- const twoUp = join(projectDir, `two-${MIXED_AUDIO_FILENAME}`);-- const one = await mixAudio([track("a", 2)], projectDir, workDir, oneUp, 2);- const two = await mixAudio([track("a", 2), track("b", 2)], projectDir, workDir, twoUp, 2);- expect(one.success).toBe(true);- expect(two.success).toBe(true);-- // Two coherent copies of one tone = +6.02 dB. If amix's 1/N ever survives- // the correction, this lands at 0 dB instead.- expect(meanVolumeDb(twoUp) - meanVolumeDb(oneUp)).toBeCloseTo(6.02, 0);- }, 60_000);-- it("does not lift the survivors when a shorter track ends", async () => {- // amix with normalize=true rescales by the number of CURRENTLY ACTIVE- // inputs, so a track ending mid-composition would hand the remaining ones- // a level jump. `apad` to the full duration is what holds every input- // active for the whole graph and neutralises that — an invariant the- // filter string relies on without saying so.- //- // Measured without apad (spike, 2026-08-14): the tail runs +1.94 dB hot.- // Any group work that builds its own amix has to keep the padding, or- // inherit that bug one level down.- const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-drop-"));- const workDir = mkdtempSync(join(tmpdir(), "hf-grp-drop-work-"));- tempDirs.push(projectDir, workDir);+ writeTone(join(projectDir, "a.wav"), 440, 2, 0.4);+ writeTone(join(projectDir, "b.wav"), 440, 2, 0.4);+ const oneUp = join(projectDir, `one-${MIXED_AUDIO_FILENAME}`);+ const twoUp = join(projectDir, `two-${MIXED_AUDIO_FILENAME}`);- writeTone(join(projectDir, "short.wav"), 440, 1, 0.5);- writeTone(join(projectDir, "long.wav"), 880, 3, 0.5);- const together = join(projectDir, `both-${MIXED_AUDIO_FILENAME}`);- const alone = join(projectDir, `alone-${MIXED_AUDIO_FILENAME}`);+ const one = await processCompositionAudio([track("a", 2)], projectDir, workDir, oneUp, 2);+ const two = await processCompositionAudio(+ [track("a", 2), track("b", 2)],+ projectDir,+ workDir,+ twoUp,+ 2,+ );+ expect(one.success).toBe(true);+ expect(two.success).toBe(true);- const both = await mixAudio(- [track("short", 1), track("long", 3)],- projectDir,- workDir,- together,- 3,- );- const solo = await mixAudio([track("long", 3)], projectDir, workDir, alone, 3);- expect(both.success).toBe(true);- expect(solo.success).toBe(true);+ // Two coherent copies of one tone = +6.02 dB. If amix's 1/N ever survives+ // the correction, this lands at 0 dB instead.+ expect(meanVolumeDb(twoUp) - meanVolumeDb(oneUp)).toBeCloseTo(6.02, 0);+ });- // After 1.5 s only `long` is sounding. It must read the same whether or not- // a second track happened to end earlier.- const tailTogether = meanVolumeDb(together, 1.5, 3);- const tailAlone = meanVolumeDb(alone, 1.5, 3);- expect(Math.abs(tailTogether - tailAlone)).toBeLessThan(0.5);- }, 60_000);+ it("does not lift the survivors when a shorter track ends", async () => {+ // amix with normalize=true rescales by the number of CURRENTLY ACTIVE+ // inputs, so a track ending mid-composition would hand the remaining ones+ // a level jump. `apad` to the full duration is what holds every input+ // active for the whole graph and neutralises that — an invariant the+ // filter string relies on without saying so.+ //+ // Measured without apad (spike, 2026-08-14): the tail runs +1.94 dB hot.+ // Any group work that builds its own amix has to keep the padding, or+ // inherit that bug one level down.+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-drop-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-drop-work-"));+ tempDirs.push(projectDir, workDir);- /**- * The gate for group buses (plans/audio-mixer-groups.md §1).- *- * Grouping is routing, not processing: a group whose FX chain is empty must- * be a no-op on the mix. Enable this the moment `data-audio-group` routes- * through a nested amix — it is the definition of done for §1.3, and the- * only thing standing between a wrong gain correction and a silently loud- * export.- *- * Proven reachable in the spike: nesting with each amix compensated by ITS- * OWN input count nulls against the flat mix to -inf (sample-identical), as- * does `amix=normalize=0` with no correction at all.- */- it("mixes a grouped composition at the same level as the ungrouped one", async () => {- const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-level-"));- const workDir = mkdtempSync(join(tmpdir(), "hf-grp-level-work-"));- tempDirs.push(projectDir, workDir);+ writeTone(join(projectDir, "short.wav"), 440, 1, 0.5);+ writeTone(join(projectDir, "long.wav"), 880, 3, 0.5);+ const together = join(projectDir, `both-${MIXED_AUDIO_FILENAME}`);+ const alone = join(projectDir, `alone-${MIXED_AUDIO_FILENAME}`);- writeTone(join(projectDir, "a.wav"), 440, 2, 0.4);- writeTone(join(projectDir, "b.wav"), 660, 2, 0.4);- const flatOut = join(projectDir, `flat-${MIXED_AUDIO_FILENAME}`);- const groupedOut = join(projectDir, `grouped-${MIXED_AUDIO_FILENAME}`);+ const both = await processCompositionAudio(+ [track("short", 1), track("long", 3)],+ projectDir,+ workDir,+ together,+ 3,+ );+ const solo = await processCompositionAudio([track("long", 3)], projectDir, workDir, alone, 3);+ expect(both.success).toBe(true);+ expect(solo.success).toBe(true);++ // After 1.5 s only `long` is sounding. It must read the same whether or not+ // a second track happened to end earlier.+ const tailTogether = meanVolumeDb(together, 1.5, 3);+ const tailAlone = meanVolumeDb(alone, 1.5, 3);+ expect(Math.abs(tailTogether - tailAlone)).toBeLessThan(0.5);+ });++ /**+ * The gate for group buses (plans/audio-mixer-groups.md §1).+ *+ * Grouping is routing, not processing: a group whose FX chain is empty must+ * be a no-op on the mix. Enable this the moment `data-audio-group` routes+ * through a nested amix — it is the definition of done for §1.3, and the+ * only thing standing between a wrong gain correction and a silently loud+ * export.+ *+ * Proven reachable in the spike: nesting with each amix compensated by ITS+ * OWN input count nulls against the flat mix to -inf (sample-identical), as+ * does `amix=normalize=0` with no correction at all.+ */+ it("mixes a grouped composition at the same level as the ungrouped one", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-level-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-level-work-"));+ tempDirs.push(projectDir, workDir);++ writeTone(join(projectDir, "a.wav"), 440, 2, 0.4);+ writeTone(join(projectDir, "b.wav"), 660, 2, 0.4);+ const flatOut = join(projectDir, `flat-${MIXED_AUDIO_FILENAME}`);+ const groupedOut = join(projectDir, `grouped-${MIXED_AUDIO_FILENAME}`);++ const flat = await processCompositionAudio(+ [track("a", 2), track("b", 2)],+ projectDir,+ workDir,+ flatOut,+ 2,+ );+ const grouped = await processCompositionAudio(+ [+ { ...track("a", 2), groupId: "voiceover" },+ { ...track("b", 2), groupId: "voiceover" },+ ],+ projectDir,+ workDir,+ groupedOut,+ 2,+ );+ expect(flat.success).toBe(true);+ expect(grouped.success).toBe(true);++ // An empty group chain is pure routing — the export must read the same+ // whether or not the two tones happened to share a group.+ expect(Math.abs(meanVolumeDb(groupedOut) - meanVolumeDb(flatOut))).toBeLessThan(0.3);+ });++ it("a group FX chain fully cutting its members leaves an ungrouped track untouched (routing isolation)", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-fx-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-fx-work-"));+ tempDirs.push(projectDir, workDir);++ writeTone(join(projectDir, "voice.wav"), 440, 2, 0.4);+ writeTone(join(projectDir, "sfx.wav"), 880, 2, 0.4);+ const mixedOut = join(projectDir, `mixed-${MIXED_AUDIO_FILENAME}`);+ const sfxAloneOut = join(projectDir, `sfx-alone-${MIXED_AUDIO_FILENAME}`);++ const groupChain = JSON.stringify({+ version: 1,+ nodes: [{ type: "gain", id: "g", params: { gain: -60 } }],+ });++ const mixed = await processCompositionAudio(+ [{ ...track("voice", 2), groupId: "vo", groupFxChain: groupChain }, track("sfx", 2)],+ projectDir,+ workDir,+ mixedOut,+ 2,+ );+ const sfxAlone = await processCompositionAudio(+ [track("sfx", 2)],+ projectDir,+ workDir,+ sfxAloneOut,+ 2,+ );+ expect(mixed.success).toBe(true);+ expect(sfxAlone.success).toBe(true);- const flat = await mixAudio([track("a", 2), track("b", 2)], projectDir, workDir, flatOut, 2);- const grouped = await mixAudio(+ // The voice group is cut ~60 dB — the mix should read close to sfx alone,+ // and the ungrouped sfx track's own processing is unaffected by the+ // group existing at all.+ expect(Math.abs(meanVolumeDb(mixedOut) - meanVolumeDb(sfxAloneOut))).toBeLessThan(0.5);+ });++ it("a member's own volume envelope still applies inside a group", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-env-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-env-work-"));+ tempDirs.push(projectDir, workDir);++ writeTone(join(projectDir, "a.wav"), 440, 4, 0.5);+ const groupedOut = join(projectDir, `grouped-${MIXED_AUDIO_FILENAME}`);+ const flatOut = join(projectDir, `flat-${MIXED_AUDIO_FILENAME}`);++ const withEnvelope = {+ ...track("a", 4),+ volumeKeyframes: [+ { time: 0, volume: 1 },+ { time: 4, volume: 0 },+ ],+ };++ const grouped = await processCompositionAudio(+ [{ ...withEnvelope, groupId: "vo" }],+ projectDir,+ workDir,+ groupedOut,+ 4,+ );+ const flat = await processCompositionAudio([withEnvelope], projectDir, workDir, flatOut, 4);+ expect(grouped.success).toBe(true);+ expect(flat.success).toBe(true);++ // The envelope fades to silent — the tail should read the same whether+ // the track is grouped or not, proving member-level processing survives+ // the group path unchanged.+ const groupedTail = meanVolumeDb(groupedOut, 3, 4);+ const flatTail = meanVolumeDb(flatOut, 3, 4);+ expect(Math.abs(groupedTail - flatTail)).toBeLessThan(0.5);+ });++ // Members sum at unity (normalize=0), so an over-unity sum used to hard-clip+ // at ±1 in the 16-bit intermediate BEFORE the group's fader and FX chain ran+ // — pulling the group down then operated on distortion. Every existing probe+ // here sums to ≤ 0.8, which is exactly why nothing caught it; preview cannot+ // reproduce it either, because its bus is float.+ it("does not clip an over-unity member sum before the group fader", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-clip-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-clip-work-"));+ tempDirs.push(projectDir, workDir);++ // Two coherent copies of the same tone: 0.7 + 0.7 = 1.4, comfortably over.+ // `writePeakTone`, not `writeTone` — ffmpeg's `sine` source is nowhere near+ // full scale (its output peaks at ~0.125), so every tone in this file sits+ // around -21 dBFS and NOTHING here can reach a clip no matter what gain is+ // asked for. That is a large part of why this class of bug survived.+ writePeakTone(join(projectDir, "a.wav"), 440, 2, 0.7);+ writePeakTone(join(projectDir, "b.wav"), 440, 2, 0.7);+ // The reference: the level that sum SHOULD reach once the group's 0.5+ // fader has been applied — 1.4 × 0.5 = 0.7, one tone's worth.+ writePeakTone(join(projectDir, "ref.wav"), 440, 2, 0.7);++ const groupedOut = join(projectDir, `clip-grouped-${MIXED_AUDIO_FILENAME}`);+ const refOut = join(projectDir, `clip-ref-${MIXED_AUDIO_FILENAME}`);++ const grouped = await processCompositionAudio(+ [+ { ...track("a", 2), groupId: "vo", groupVolume: 0.5 },+ { ...track("b", 2), groupId: "vo", groupVolume: 0.5 },+ ],+ projectDir,+ workDir,+ groupedOut,+ 2,+ );+ const reference = await processCompositionAudio(+ [track("ref", 2)],+ projectDir,+ workDir,+ refOut,+ 2,+ );+ expect(grouped.success).toBe(true);+ expect(reference.success).toBe(true);++ // Both are ONE track into the outer mix, so the outer graph is identical+ // and the levels are directly comparable. Clipped, the flat-topped sum+ // reads well over a dB hot even after the fader halves it.+ expect(Math.abs(meanVolumeDb(groupedOut) - meanVolumeDb(refOut))).toBeLessThan(0.5);+ });++ // The same property, for a group that carries an FX CHAIN. That path runs the+ // sum through applyAudioFxChain, whose writeWav clamps to ±1 and emits 16-bit+ // — so the headroom the float sub-mix preserved was handed back before the+ // fader, one step later than the original bug but with the same result.+ // A transparent chain isolates the clamp from anything the effects do.+ it("does not clip an over-unity sum before the fader when the group has FX", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-clipfx-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-clipfx-work-"));+ tempDirs.push(projectDir, workDir);++ writePeakTone(join(projectDir, "a.wav"), 440, 2, 0.7);+ writePeakTone(join(projectDir, "b.wav"), 440, 2, 0.7);+ writePeakTone(join(projectDir, "ref.wav"), 440, 2, 0.7);++ // 0 dB gain: in the chain, doing nothing to the level.+ const transparentChain = JSON.stringify({+ version: 1,+ nodes: [{ type: "gain", id: "g", params: { gain: 0 } }],+ });++ const groupedOut = join(projectDir, `clipfx-grouped-${MIXED_AUDIO_FILENAME}`);+ const refOut = join(projectDir, `clipfx-ref-${MIXED_AUDIO_FILENAME}`);++ const grouped = await processCompositionAudio(+ [+ { ...track("a", 2), groupId: "vo", groupVolume: 0.5, groupFxChain: transparentChain },+ { ...track("b", 2), groupId: "vo", groupVolume: 0.5, groupFxChain: transparentChain },+ ],+ projectDir,+ workDir,+ groupedOut,+ 2,+ );+ const reference = await processCompositionAudio(+ [track("ref", 2)],+ projectDir,+ workDir,+ refOut,+ 2,+ );+ expect(grouped.success).toBe(true);+ expect(reference.success).toBe(true);++ expect(Math.abs(meanVolumeDb(groupedOut) - meanVolumeDb(refOut))).toBeLessThan(0.5);+ });+ },+ 60_000,+);++describe.skipIf(!HAS_FFMPEG)("group sub-mix failure contract", () => {+ afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+ });++ // A malformed chain on a BUS threw straight out of processCompositionAudio,+ // bypassing the MixResult/failures[] shape the caller handles and skipping+ // bail()'s workDir cleanup. The per-element loop has always wrapped the+ // identical calls.+ it("reports an unparseable group fx-chain as a failure instead of throwing", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-bad-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-bad-work-"));+ tempDirs.push(projectDir, workDir);+ writeTone(join(projectDir, "a.wav"), 440, 1, 0.4);++ const result = await processCompositionAudio([- { ...track("a", 2), groupId: "voiceover" },- { ...track("b", 2), groupId: "voiceover" },+ {+ ...track("a", 1),+ groupId: "vo",+ groupFxChain: '{"version":1,"nodes":[{"type":"tapestop"}]}',+ },],projectDir,workDir,- groupedOut,- 2,+ join(projectDir, `bad-${MIXED_AUDIO_FILENAME}`),+ 1,);- expect(flat.success).toBe(true);- expect(grouped.success).toBe(true);-- // An empty group chain is pure routing — the export must read the same- // whether or not the two tones happened to share a group.- expect(Math.abs(meanVolumeDb(groupedOut) - meanVolumeDb(flatOut))).toBeLessThan(0.3);- }, 60_000);-- it("a group FX chain fully cutting its members leaves an ungrouped track untouched (routing isolation)", async () => {- const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-fx-"));- const workDir = mkdtempSync(join(tmpdir(), "hf-grp-fx-work-"));- tempDirs.push(projectDir, workDir);- writeTone(join(projectDir, "voice.wav"), 440, 2, 0.4);- writeTone(join(projectDir, "sfx.wav"), 880, 2, 0.4);- const mixedOut = join(projectDir, `mixed-${MIXED_AUDIO_FILENAME}`);- const sfxAloneOut = join(projectDir, `sfx-alone-${MIXED_AUDIO_FILENAME}`);+ expect(result.success).toBe(false);+ const failure = result.failures?.find((f) => f.elementId === "vo");+ expect(failure?.stage).toBe("mix");+ expect(failure?.detail).toContain("tapestop");+ });- const groupChain = JSON.stringify({- version: 1,- nodes: [{ type: "gain", id: "g", params: { gain: -60 } }],- });+ // `data-audio-group` arrives unvalidated from the document. `group-${id}.wav`+ // defuses a bare `../` (the segment is `group-..`, not `..`), but an id+ // holding a slash BEFORE the dots does escape: `a/../../x` normalizes to+ // `<workDir>/../x.wav`, outside the tree `bail()`'s rmSync can reach.+ it("keeps a traversal-shaped group id inside the work directory", async () => {+ const parent = mkdtempSync(join(tmpdir(), "hf-grp-parent-"));+ tempDirs.push(parent);+ const projectDir = join(parent, "project");+ const workDir = join(parent, "work");+ mkdirSync(projectDir);+ mkdirSync(workDir);+ writeTone(join(projectDir, "a.wav"), 440, 1, 0.4);- const mixed = await mixAudio(- [{ ...track("voice", 2), groupId: "vo", groupFxChain: groupChain }, track("sfx", 2)],+ const result = await processCompositionAudio(+ [{ ...track("a", 1), groupId: "a/../../escaped" }],projectDir,workDir,- mixedOut,- 2,+ join(projectDir, `esc-${MIXED_AUDIO_FILENAME}`),+ 1,);- const sfxAlone = await mixAudio([track("sfx", 2)], projectDir, workDir, sfxAloneOut, 2);- expect(mixed.success).toBe(true);- expect(sfxAlone.success).toBe(true);-- // The voice group is cut ~60 dB — the mix should read close to sfx alone,- // and the ungrouped sfx track's own processing is unaffected by the- // group existing at all.- expect(Math.abs(meanVolumeDb(mixedOut) - meanVolumeDb(sfxAloneOut))).toBeLessThan(0.5);- }, 60_000);-- it("a member's own volume envelope still applies inside a group", async () => {- const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-env-"));- const workDir = mkdtempSync(join(tmpdir(), "hf-grp-env-work-"));++ expect(result.success).toBe(true);+ // workDir is cleaned up on success, so what matters is what is left BESIDE+ // it: an escaped would survive there. Only the project remains.+ expect(readdirSync(parent).sort()).toEqual(["project"]);+ });++ it("keeps distinct groups isolated when their sanitized ids collide", async () => {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-grp-collision-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-grp-collision-work-"));tempDirs.push(projectDir, workDir);+ writeTone(join(projectDir, "a.wav"), 440, 2, 0.4);+ writeTone(join(projectDir, "b.wav"), 880, 2, 0.4);- writeTone(join(projectDir, "a.wav"), 440, 4, 0.5);const groupedOut = join(projectDir, `grouped-${MIXED_AUDIO_FILENAME}`);const flatOut = join(projectDir, `flat-${MIXED_AUDIO_FILENAME}`);-- const withEnvelope = {- ...track("a", 4),- volumeKeyframes: [- { time: 0, volume: 1 },- { time: 4, volume: 0 },+ const grouped = await processCompositionAudio(+ [+ { ...track("a", 2), groupId: "bed/a" },+ { ...track("b", 2), groupId: "bed?a" },],- };-- const grouped = await mixAudio(- [{ ...withEnvelope, groupId: "vo" }],projectDir,workDir,groupedOut,- 4,+ 2,);- const flat = await mixAudio([withEnvelope], projectDir, workDir, flatOut, 4);+ const flat = await processCompositionAudio(+ [track("a", 2), track("b", 2)],+ projectDir,+ workDir,+ flatOut,+ 2,+ );+expect(grouped.success).toBe(true);expect(flat.success).toBe(true);+ // If both ids map to `group-bed_a.wav`, the second submix overwrites the+ // first and the outer mix reads the 880 Hz group twice, roughly 3 dB hot.+ expect(Math.abs(meanVolumeDb(groupedOut) - meanVolumeDb(flatOut))).toBeLessThan(0.5);+ }, 30_000);+});- // The envelope fades to silent — the tail should read the same whether- // the track is grouped or not, proving member-level processing survives- // the group path unchanged.- const groupedTail = meanVolumeDb(groupedOut, 3, 4);- const flatTail = meanVolumeDb(flatOut, 3, 4);- expect(Math.abs(groupedTail - flatTail)).toBeLessThan(0.5);- }, 60_000);+describe("duplicate bus instances", () => {+ /**+ * The reviewer's own repro. Two inlined instances of one sub-composition, each+ * with its own bus and member, only the SECOND muted. Keyed by author id the+ * two collapsed into one bus (last wins), so instance B's `data-hidden` took+ * instance A's audio out of the export with it.+ */+ it("drops only the muted instance's member", () => {+ const html = `<div id="root" data-composition-id="main" data-start="0" data-duration="4">+ <div data-composition-id="bedcomp">+ <hf-audio-group id="bed" data-hf-render-id="bed" data-volume="0.5"></hf-audio-group>+ <audio id="m1" src="a.wav" data-start="0" data-duration="2"+ data-audio-group="bed" data-hf-group-render-id="bed"></audio>+ </div>+ <div data-composition-id="bedcomp">+ <hf-audio-group id="bed" data-hf-render-id="bed__hf2" data-volume="0.5" data-hidden></hf-audio-group>+ <audio id="m1" src="a.wav" data-start="2" data-duration="2"+ data-audio-group="bed" data-hf-group-render-id="bed__hf2"></audio>+ </div>+ </div>`;++ const tracks = parseAudioElements(html);+ expect(tracks.map((t) => t.groupId)).toEqual(["bed"]);+ expect(tracks).toHaveLength(1);+ });++ it("keeps two instances as two separate buses when neither is muted", () => {+ const html = `<div id="root" data-composition-id="main" data-start="0" data-duration="4">+ <hf-audio-group id="bed" data-hf-render-id="bed" data-volume="0.25"></hf-audio-group>+ <audio id="m1" src="a.wav" data-start="0" data-duration="2"+ data-audio-group="bed" data-hf-group-render-id="bed"></audio>+ <hf-audio-group id="bed" data-hf-render-id="bed__hf2" data-volume="0.75"></hf-audio-group>+ <audio id="m2" src="b.wav" data-start="2" data-duration="2"+ data-audio-group="bed" data-hf-group-render-id="bed__hf2"></audio>+ </div>`;++ const tracks = parseAudioElements(html);+ // Each member keeps its OWN instance's fader — the collapse used to apply+ // whichever bus came last to both.+ expect(tracks.map((t) => [t.groupId, t.groupVolume])).toEqual([+ ["bed", 0.25],+ ["bed__hf2", 0.75],+ ]);+ });});diff --git a/packages/engine/src/services/audioMixer.level.test.ts b/packages/engine/src/services/audioMixer.level.test.tsindex 145485537d..3a5b02257b 100644--- a/packages/engine/src/services/audioMixer.level.test.ts+++ b/packages/engine/src/services/audioMixer.level.test.ts@@ -55,28 +55,9 @@ function firstAudibleSeconds(path: string): number {throw new Error(`No audible sample found in ${path}`);}-/**- * These two tests drive real ffmpeg, and the file ran on vitest's 5s default:- * `places a delayed track on its authored start` takes ~137ms locally and still- * hit that cap on the windows runner, failing an unrelated PR. 60s is what the- * rest of the ffmpeg-driven engine tests use. Applied to the suite rather than- * each test so the budget has one home.- *- * Headroom alone would only delay an undiagnosable failure, so the ffmpeg- * process timeout is capped well under it too. Its production default is 5- * minutes — far above any test budget — so a stalled mix could only ever- * surface as a bare "Test timed out", with no stderr and no failing stage.- */-const FFMPEG_TEST_TIMEOUT_MS = 60_000;-const TEST_FFMPEG_TIMEOUT_MS = 20_000;--/** Assert the mix succeeded, reporting `failures` rather than a bare `false`. */-function expectMixed(result: { success: boolean; failures?: unknown }): void {- if (!result.success) {- throw new Error(`mix failed: ${JSON.stringify(result.failures ?? result, null, 2)}`);- }-}-+// Same real-ffmpeg exposure as audioMixer.grouping.test.ts, which timed out on a+// Windows runner at vitest's default 5s. This one has not failed yet; it is one+// spawn slower away from it.describe.skipIf(!HAS_FFMPEG)("processCompositionAudio levels",() => {@@ -127,11 +108,9 @@ describe.skipIf(!HAS_FFMPEG)(workDir,outputPath,1,- undefined,- { ffmpegProcessTimeout: TEST_FFMPEG_TIMEOUT_MS },);- expectMixed(result);+ expect(result.success).toBe(true);expect(meanVolumeDb(outputPath) - meanVolumeDb(sourcePath)).toBeGreaterThan(-0.3);});@@ -182,13 +161,11 @@ describe.skipIf(!HAS_FFMPEG)(workDir,outputPath,4,- undefined,- { ffmpegProcessTimeout: TEST_FFMPEG_TIMEOUT_MS },);- expectMixed(result);+ expect(result.success).toBe(true);expect(firstAudibleSeconds(outputPath)).toBeCloseTo(2, 2);});},- FFMPEG_TEST_TIMEOUT_MS,+ 60_000,);diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.tsindex 0fa593deb0..c3ec1c34f4 100644--- a/packages/engine/src/services/audioMixer.ts+++ b/packages/engine/src/services/audioMixer.ts@@ -48,6 +48,7 @@ import {readMediaStart,} from "@hyperframes/core";import { HF_AUDIO_GROUP_ATTR, resolveAudioGroups } from "@hyperframes/core/audio-groups";+import { AUDIO_GROUP_RENDER_ID_ATTR } from "@hyperframes/core";import { applyAudioFxChain, AudioFxRenderError } from "./audioFxRender.js";import type { AudioVolumeKeyframe } from "./audioMixer.types.js";@@ -68,10 +69,45 @@ export type { AudioElement, MixResult } from "./audioMixer.types.js";*/export const MIXED_AUDIO_FILENAME = "audio.m4a";+/**+ * The bus key a member belongs to, as `resolveAudioGroups` keys them.+ *+ * The compiler's `data-hf-group-render-id` names one INSTANCE of a bus; the+ * author's `data-audio-group` names it only within its own composition file. A+ * sub-composition declaring a bus and its members, used twice, therefore had+ * both instances' members under one key: one sub-mix for two independent buses,+ * one instance's fader and chain over the other's audio, and — with only the+ * second muted — BOTH instances dropped from the export. Uncompiled documents+ * (the live preview) carry no stamp and read exactly as before.+ */+function memberGroupKey(el: RefResolverEl): string | null {+ return el.getAttribute(AUDIO_GROUP_RENDER_ID_ATTR) ?? el.getAttribute(HF_AUDIO_GROUP_ATTR);+}+function clampVolume(volume: number): number {return clampAudioGain(volume);}+/**+ * An author-controlled id, made safe to put in a filename.+ *+ * `data-audio-group` reaches this file straight from the document — the+ * studio's `GROUP_ID_PATTERN` guards only ids the studio itself mints, and a+ * hand-authored or agent-written one is unvalidated. Interpolated raw it could+ * carry `/` or `..`, and `mkdirSync(recursive)` inside ffmpeg's own path+ * handling would then write outside `workDir`, where `bail()`'s `rmSync` never+ * cleans it up. Everything outside [A-Za-z0-9_-] collapses to `_`, and every+ * result gets a stable positional suffix so distinct ids that sanitize alike+ * cannot share one intermediate file.+ */+function safePathSegment(id: string, fallbackIndex: number): string {+ const cleaned = id.replace(/[^A-Za-z0-9_-]/g, "_");+ // Sanitisation is many-to-one (`bed/a` and `bed?a` both become `bed_a`).+ // The stable position keeps every authored group on a distinct temp path+ // even when their readable portions collide.+ return `${cleaned || "group"}-${fallbackIndex}`;+}+function formatFilterNumber(value: number): string {return Number(value.toFixed(6)).toString();}@@ -469,7 +505,7 @@ export function parseAudioElements(html: string): AudioElement[] {resolveAudioGroups(document).map((group) => [group.id, group] as const),);const memberGroupHidden = (el: AudioMediaElement): boolean => {- const groupId = el.getAttribute(HF_AUDIO_GROUP_ATTR);+ const groupId = memberGroupKey(el);return groupId ? (groupsById.get(groupId)?.hidden ?? false) : false;};@@ -484,7 +520,7 @@ export function parseAudioElements(html: string): AudioElement[] {const automation = el.getAttribute(HF_AUDIO_AUTOMATION_ATTR);// Audio only in v1 (matches resolveAudioGroups, which only scans// `audio[data-audio-group]`) — a stray attribute on a <video> is inert.- const groupId = type === "audio" ? el.getAttribute(HF_AUDIO_GROUP_ATTR) : null;+ const groupId = type === "audio" ? memberGroupKey(el) : null;const group = groupId ? groupsById.get(groupId) : undefined;return {id,@@ -519,6 +555,8 @@ export function parseAudioElements(html: string): AudioElement[] {for (const el of document.querySelectorAll("audio[id][src]")) {const id = trackId(el);+ // `memberGroupHidden` is the group's own mute: a hidden BUS drops every+ // member from the mix, the same way `isHidden` drops one track.if (!id || !el.getAttribute("src") || isHidden(el) || memberGroupHidden(el)) continue;if (isKnownInactiveTimelineWindow(el, resolveStart(el))) continue;elements.push(build(el, id, "audio"));@@ -865,6 +903,14 @@ async function mixAudioTracks(};}+/**+ * Verified against the real binary, because the wording is the whole contract:+ * ffmpeg 8.1.1 emits `Error applying option 'X' to filter 'amix': Option not+ * found`, which "option not found" matches. Only pre-4.4 libavfilter's+ * `Option 'normalize' not found` phrasing sits outside the first test — and+ * that build predates `normalize` existing at all, so it would fail for the+ * right reason anyway. A review pass read this as dead and it is not.+ */function groupNormalizeOptionUnsupported(stderr: string): boolean {return (/normalize/i.test(stderr) &&@@ -894,24 +940,36 @@ async function mixGroupMembers(totalDuration: number,signal?: AbortSignal,config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,-): Promise<{ success: boolean; error?: string }> {+): Promise<{ success: boolean; error?: string; degradedAutomation?: boolean }> {const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;const outputDir = dirname(outputPath);if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });- const inputFilters = memberTracks.map((track, i) => {- const delayMs = Math.round(track.start * 1000);- const trimDuration = track.end - track.start + (track.tailSeconds ?? 0);- const volumeFilter = buildVolumeExpression(track);- return `[${i}:a]atrim=0:${formatFilterNumber(trimDuration)},${volumeFilter},adelay=${delayMs}|${delayMs},apad,atrim=0:${formatFilterNumber(totalDuration)}[a${i}]`;- });+ const buildInputFilters = (ignoreKeyframes: boolean) =>+ memberTracks.map((track, i) => {+ const delayMs = Math.round(track.start * 1000);+ const trimDuration = track.end - track.start + (track.tailSeconds ?? 0);+ const volumeFilter = buildVolumeExpression(track, ignoreKeyframes);+ // Same `asetpts=N/SR/TB` as the master mix above, for the same reason and+ // on the same builds: these are delayed branches padded to length and then+ // amix'd, so without the renumbering a delayed member lands at t=0 and a+ // group of four or more loses its last one.+ return `[${i}:a]atrim=0:${formatFilterNumber(trimDuration)},${volumeFilter},adelay=${delayMs}|${delayMs},apad,asetpts=N/SR/TB,atrim=0:${formatFilterNumber(totalDuration)}[a${i}]`;+ });const mixInputs = memberTracks.map((_, i) => `[a${i}]`).join("");- const runOnce = async (useNormalize: boolean): Promise<RunFfmpegResult> => {+ const runOnce = async (+ useNormalize: boolean,+ ignoreKeyframes = false,+ ): Promise<RunFfmpegResult> => {+ const inputFilters = buildInputFilters(ignoreKeyframes);const mixFilter = useNormalize? `${mixInputs}amix=inputs=${memberTracks.length}:duration=longest:dropout_transition=0:normalize=0[out]`- : // amix's default normalize divides by input count; compensate by THIS- // group's own member count — never the render's global track count.+ : // Every member is padded and trimmed to totalDuration above, and+ // dropout_transition=0 keeps all N inputs active for that whole span.+ // amix's default normalize therefore divides by exactly N throughout;+ // compensate by THIS group's own member count — never the render's+ // global track count.`${mixInputs}amix=inputs=${memberTracks.length}:duration=longest:dropout_transition=0[mixed];[mixed]volume=${formatFilterNumber(memberTracks.length)}[out]`;const filterComplex = [...inputFilters, mixFilter].join(";");const scriptDir = mkdtempSync(join(outputDir, ".group-filter-complex-"));@@ -931,8 +989,15 @@ async function mixGroupMembers(scriptPath,"-map","[out]",+ // Float, not pcm_s16le: `normalize=0` sums the members at unity, so any+ // over-unity sum hard-clipped at ±1 in the intermediate — BEFORE the+ // group's FX chain and its fader ran. Pulling the group down, or the+ // Giant preset's compressor, then operated on distortion. Preview+ // cannot reproduce it (its bus is float), and it only shows up in the+ // export. Both readers downstream take float: `readWav` (format 3) and+ // `applyVolumeEnvelopeToWav`."-acodec",- "pcm_s16le",+ "pcm_f32le","-ar","48000","-t",@@ -952,14 +1017,32 @@ async function mixGroupMembers(}};- let result = await runOnce(true);+ let useNormalize = true;+ let result = await runOnce(useNormalize);if (!result.success && groupNormalizeOptionUnsupported(result.stderr)) {- result = await runOnce(false);+ useNormalize = false;+ result = await runOnce(useNormalize);+ }++ // The same defence `mixAudioTracks` has, which this forked without: a+ // member's volume automation becomes an ffmpeg `volume` expression whose+ // evaluator limits are build-dependent, so a dense envelope can fail the+ // whole run. Ungrouped, that track degrades to base volume with a warning;+ // grouped, it took the entire composition's audio down with it.+ let degradedAutomation = false;+ const hasAutomation = memberTracks.some((track) => (track.volumeKeyframes?.length ?? 0) > 0);+ if (!result.success && !signal?.aborted && hasAutomation) {+ const retry = await runOnce(useNormalize, true);+ if (retry.success) {+ result = retry;+ degradedAutomation = true;+ }}+if (signal?.aborted) return { success: false, error: "Group sub-mix cancelled" };if (!result.success)return { success: false, error: formatFfmpegError(result.exitCode, result.stderr) };- return { success: true };+ return { success: true, degradedAutomation };}export async function processCompositionAudio(@@ -1314,87 +1397,118 @@ export async function processCompositionAudio(// clock is composition time (offset 0): a group has no `data-start` of its// own, and members are already delayed to their composition positions// inside the sub-mix, so the group WAV's t=0 IS composition time.+ const groupsDegradedAutomation: string[] = [];+ let groupIndex = -1;for (const [groupId, memberTracks] of groupTracks) {+ groupIndex += 1;const meta = groupMeta.get(groupId);if (!meta) continue;- const groupWavPath = join(workDir, `group-${groupId}.wav`);- const subMix = await mixGroupMembers(- memberTracks,- groupWavPath,- totalDuration,- effectiveSignal,- config,- );- if (!subMix.success) {+ const pathId = safePathSegment(groupId, groupIndex);+ const groupWavPath = join(workDir, `group-${pathId}.wav`);+ // Same contract the per-element loop above gives: a malformed `data-fx-chain`+ // or `data-automation` on a BUS threw straight out of processCompositionAudio,+ // bypassing the MixResult/failures[] shape the caller handles and skipping+ // `bail()`, so the temp dir leaked too. An AudioFxRenderError stays fatal+ // for the same reason it is fatal per element: shipping the dry signal in+ // place of a processed one sounds plausible and is not what was authored.+ try {+ const subMix = await mixGroupMembers(+ memberTracks,+ groupWavPath,+ totalDuration,+ effectiveSignal,+ config,+ );+ if (!subMix.success) {+ failures.push({+ stage: "mix",+ reason: "ffmpeg_failed",+ owner: "system",+ retryable: false,+ elementId: groupId,+ detail: boundedDetail(+ `Group sub-mix failed for group ${groupId}: ${subMix.error ?? "unknown"}`,+ ),+ });+ continue;+ }+ if (subMix.degradedAutomation) groupsDegradedAutomation.push(groupId);++ // Composition-time automation (offset 0, duration totalDuration) — same+ // resolve/lane/bake path a member uses, just anchored at the group clock+ // instead of a clip's own start.+ const automation = meta.automation+ ? resolveAutomation(+ parseAutomation(meta.automation),+ meta.fxChain ? parseAudioFxChain(meta.fxChain) : undefined,+ )+ : null;+ const laneKeyframes = automation ? volumeLaneKeyframes(automation, 0, totalDuration) : null;+ const envelope =+ laneKeyframes && laneKeyframes.length > 0+ ? { keyframes: laneKeyframes, trackStart: 0, baseVolume: meta.volume }+ : null;++ let groupSrcPath = groupWavPath;+ let bakedEnvelope = false;+ if (meta.fxChain) {+ const chain = parseAudioFxChain(meta.fxChain);+ const fxResult = await applyAudioFxChain(+ groupSrcPath,+ chain,+ join(workDir, `group-${pathId}-fx.wav`),+ {+ trackId: groupId,+ signal: effectiveSignal,+ ...(automation ? { automation } : {}),+ ...(envelope ? { envelope } : {}),+ },+ );+ groupSrcPath = fxResult.path;+ bakedEnvelope = fxResult.envelopeBaked;+ }+ if (envelope && !bakedEnvelope) {+ bakedEnvelope = applyVolumeEnvelopeToWav(+ groupSrcPath,+ envelope.keyframes,+ envelope.trackStart,+ envelope.baseVolume,+ );+ }++ // `end` is already the render's totalDuration, so the outer mix's own+ // atrim-to-totalDuration clips this track exactly the same way it would+ // an ungrouped one whose clip ran to the end of the render — a group's FX+ // tail gets the same "never past the end of the video" treatment member+ // tails get, for free, with no separate tailSeconds bookkeeping needed.+ tracks.push({+ id: groupId,+ srcPath: groupSrcPath,+ start: 0,+ end: totalDuration,+ mediaStart: 0,+ duration: totalDuration,+ volume: bakedEnvelope ? 1.0 : meta.volume,+ // Same fallback an ungrouped track gets: when the envelope could not be+ // baked into the samples, hand the keyframes to the outer mix's volume+ // expression instead of dropping the group's automation on the floor.+ ...(bakedEnvelope || !laneKeyframes?.length ? {} : { volumeKeyframes: laneKeyframes }),+ });+ } catch (err: unknown) {+ if (err instanceof AudioFxRenderError) throw err;failures.push({stage: "mix",- reason: "ffmpeg_failed",+ reason: "internal",owner: "system",retryable: false,elementId: groupId,detail: boundedDetail(- `Group sub-mix failed for group ${groupId}: ${subMix.error ?? "unknown"}`,+ `Audio processing failed for group ${groupId}: ${+ err instanceof Error ? err.message : String(err)+ }`,),});- continue;- }-- // Composition-time automation (offset 0, duration totalDuration) — same- // resolve/lane/bake path a member uses, just anchored at the group clock- // instead of a clip's own start.- const automation = meta.automation- ? resolveAutomation(- parseAutomation(meta.automation),- meta.fxChain ? parseAudioFxChain(meta.fxChain) : undefined,- )- : null;- const laneKeyframes = automation ? volumeLaneKeyframes(automation, 0, totalDuration) : null;- const envelope =- laneKeyframes && laneKeyframes.length > 0- ? { keyframes: laneKeyframes, trackStart: 0, baseVolume: meta.volume }- : null;-- let groupSrcPath = groupWavPath;- let bakedEnvelope = false;- if (meta.fxChain) {- const chain = parseAudioFxChain(meta.fxChain);- const fxResult = await applyAudioFxChain(- groupSrcPath,- chain,- join(workDir, `group-${groupId}-fx.wav`),- {- trackId: groupId,- signal: effectiveSignal,- ...(automation ? { automation } : {}),- ...(envelope ? { envelope } : {}),- },- );- groupSrcPath = fxResult.path;- bakedEnvelope = fxResult.envelopeBaked;- }- if (envelope && !bakedEnvelope) {- bakedEnvelope = applyVolumeEnvelopeToWav(- groupSrcPath,- envelope.keyframes,- envelope.trackStart,- envelope.baseVolume,- );}-- // `end` is already the render's totalDuration, so the outer mix's own- // atrim-to-totalDuration clips this track exactly the same way it would- // an ungrouped one whose clip ran to the end of the render — a group's FX- // tail gets the same "never past the end of the video" treatment member- // tails get, for free, with no separate tailSeconds bookkeeping needed.- tracks.push({- id: groupId,- srcPath: groupSrcPath,- start: 0,- end: totalDuration,- mediaStart: 0,- duration: totalDuration,- volume: bakedEnvelope ? 1.0 : meta.volume,- });}if (failures.length > 0) return bail();@@ -1406,9 +1520,21 @@ export async function processCompositionAudio(/* ignore */}+ // A group whose sub-mix had to drop member automation reports it the same+ // way mixAudioTracks reports its own degradation: on a SUCCESSFUL result, so+ // the render ships and the caller can still say what was lost.+ const degradedNote =+ groupsDegradedAutomation.length > 0+ ? `Volume automation exceeded this ffmpeg build's expression limits in group(s) ${groupsDegradedAutomation.join(", ")}; rendered at base volume`+ : undefined;+return {...mixResult,durationMs: Date.now() - startMs,- error: mixResult.error,+ // Both, when both degraded. `mixResult.error ?? degradedNote` reported only+ // the outer mix and dropped the one that names which GROUPS lost their+ // members' automation — two different losses, and the operator needs to+ // hear about the one they can act on.+ error: [mixResult.error, degradedNote].filter(Boolean).join("; ") || undefined,};}diff --git a/packages/engine/src/services/audioVolumeEnvelope.test.ts b/packages/engine/src/services/audioVolumeEnvelope.test.tsindex d0cb183de0..5d453181a5 100644--- a/packages/engine/src/services/audioVolumeEnvelope.test.ts+++ b/packages/engine/src/services/audioVolumeEnvelope.test.ts@@ -1,11 +1,14 @@import { afterEach, describe, expect, it } from "vitest";+import { spawnSync } from "node:child_process";import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";+import { getFfmpegBinary } from "../utils/ffmpegBinaries.js";import { applyVolumeEnvelopeToWav } from "./audioVolumeEnvelope.js";const SAMPLE_RATE = 48000;const CHANNELS = 2;+const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"], { encoding: "utf-8" }).status === 0;/** Build a PCM s16le stereo WAV whose every sample equals `value`. */function writeConstantWav(path: string, frames: number, value: number): void {@@ -173,4 +176,145 @@ describe("applyVolumeEnvelopeToWav", () => {),).toBe(false);});++ // The group sub-mix writes float precisely so an over-unity member sum keeps+ // its headroom until the group's own fader and FX act on it. If the baker+ // could not read that file it returned false, and the group's automation was+ // dropped on the floor by the caller.+ describe("32-bit float input", () => {+ /** Stereo float32 WAV, every sample `value` — over 1.0 on purpose. */+ function writeConstantFloatWav(path: string, frames: number, value: number): void {+ const dataSize = frames * CHANNELS * 4;+ const buffer = Buffer.alloc(44 + dataSize);+ buffer.write("RIFF", 0, "ascii");+ buffer.writeUInt32LE(36 + dataSize, 4);+ buffer.write("WAVE", 8, "ascii");+ buffer.write("fmt ", 12, "ascii");+ buffer.writeUInt32LE(16, 16);+ buffer.writeUInt16LE(3, 20); // WAVE_FORMAT_IEEE_FLOAT+ buffer.writeUInt16LE(CHANNELS, 22);+ buffer.writeUInt32LE(SAMPLE_RATE, 24);+ buffer.writeUInt32LE(SAMPLE_RATE * CHANNELS * 4, 28);+ buffer.writeUInt16LE(CHANNELS * 4, 32);+ buffer.writeUInt16LE(32, 34);+ buffer.write("data", 36, "ascii");+ buffer.writeUInt32LE(dataSize, 40);+ for (let i = 0; i < frames * CHANNELS; i += 1) buffer.writeFloatLE(value, 44 + i * 4);+ writeFileSync(path, buffer);+ }++ const floatSampleAt = (path: string, frame: number, channel = 0): number =>+ readFileSync(path).readFloatLE(44 + (frame * CHANNELS + channel) * 4);++ it("scales float samples and keeps them above 1.0 unclamped", () => {+ const path = join(tmp(), "float.wav");+ writeConstantFloatWav(path, SAMPLE_RATE, 1.4);++ expect(+ applyVolumeEnvelopeToWav(+ path,+ [+ { time: 0, volume: 1 },+ { time: 1, volume: 1 },+ ],+ 0,+ 1,+ ),+ ).toBe(true);++ // Unity envelope: unchanged, and NOT clamped down to 1.0.+ expect(floatSampleAt(path, 0)).toBeCloseTo(1.4, 5);+ expect(floatSampleAt(path, SAMPLE_RATE - 1)).toBeCloseTo(1.4, 5);+ });++ it("applies the envelope across the file", () => {+ const path = join(tmp(), "float-fade.wav");+ writeConstantFloatWav(path, SAMPLE_RATE, 1.4);++ expect(+ applyVolumeEnvelopeToWav(+ path,+ [+ { time: 0, volume: 1 },+ { time: 1, volume: 0 },+ ],+ 0,+ 1,+ ),+ ).toBe(true);++ expect(floatSampleAt(path, 0)).toBeCloseTo(1.4, 5);+ expect(floatSampleAt(path, Math.floor(SAMPLE_RATE / 2))).toBeCloseTo(0.7, 2);+ expect(floatSampleAt(path, SAMPLE_RATE - 1)).toBeCloseTo(0, 3);+ });++ /**+ * The fixtures above are hand-built canonical 44-byte headers, which is NOT+ * what the group sub-mix actually hands this function: ffmpeg's `pcm_f32le`+ * writes an 18-byte `fmt ` chunk plus a `fact` chunk, putting `data` at+ * offset 92. Every assertion above would still pass if this function could+ * not read a real one — and an unreadable file returns false, which the+ * caller reads as "no automation here" and drops the group's envelope.+ */+ it.skipIf(!HAS_FFMPEG)("reads what ffmpeg actually writes, not just a canonical header", () => {+ const path = join(tmp(), "ffmpeg-f32.wav");+ const made = spawnSync(+ getFfmpegBinary(),+ [+ "-nostdin",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "aevalsrc=0.5*sin(2*PI*440*t)|0.5*sin(2*PI*440*t):d=1:s=48000",+ "-acodec",+ "pcm_f32le",+ "-ar",+ "48000",+ path,+ ],+ { encoding: "utf-8" },+ );+ expect(made.status).toBe(0);++ const before = readFileSync(path);+ // The format tag is the load-bearing part; the chunk LAYOUT is this+ // build's quirk, so it is logged as context rather than required — a+ // build emitting a canonical 16-byte fmt with data at 44 is legal and+ // handled, and pinning 18/92 would fail on the good case.+ expect(before.readUInt16LE(20)).toBe(3); // WAVE_FORMAT_IEEE_FLOAT++ expect(+ applyVolumeEnvelopeToWav(+ path,+ [+ { time: 0, volume: 1 },+ { time: 1, volume: 0 },+ ],+ 0,+ 1,+ ),+ ).toBe(true);++ // Locate `data` the way the parser does, then check the fade landed.+ let at = 12;+ let dataOffset = -1;+ const after = readFileSync(path);+ while (at + 8 <= after.length) {+ const id = after.toString("ascii", at, at + 4);+ const size = after.readUInt32LE(at + 4);+ if (id === "data") {+ dataOffset = at + 8;+ break;+ }+ at += 8 + size + (size % 2);+ }+ expect(dataOffset).toBeGreaterThan(0);+ // Faded to silence by the end (stereo float = 8 bytes per frame). This is+ // the assertion that matters: the parser read a real file and the bake+ // landed, whatever chunk layout the build chose.+ expect(Math.abs(after.readFloatLE(dataOffset + (SAMPLE_RATE - 2) * 8))).toBeLessThan(0.02);+ });+ });});diff --git a/packages/engine/src/services/audioVolumeEnvelope.ts b/packages/engine/src/services/audioVolumeEnvelope.tsindex d64cc33a4c..47064bc956 100644--- a/packages/engine/src/services/audioVolumeEnvelope.ts+++ b/packages/engine/src/services/audioVolumeEnvelope.ts@@ -22,13 +22,17 @@ import { normaliseEnvelope } from "@hyperframes/core/media-volume-envelope";import { riffChunks } from "./wavChunks.js";const PCM_FORMAT = 1; // WAVE_FORMAT_PCM-const SUPPORTED_BITS = 16;+const FLOAT_FORMAT = 3; // WAVE_FORMAT_IEEE_FLOATinterface WavLayout {numChannels: number;sampleRate: number;dataOffset: number;dataSize: number;+ /** 16-bit integer, or 32-bit float — the group sub-mix writes float so an+ * over-unity member sum is not hard-clipped before the group's own FX and+ * fader get to act on it. */+ float: boolean;}/**@@ -39,34 +43,49 @@ interface WavLayout {* and trailing chunks (LIST/fact/etc.) are skipped harmlessly. Returns null on* anything unexpected so the caller falls back to the expression path.*/+interface WavFmt {+ numChannels: number;+ sampleRate: number;+ /** 16-bit integer PCM, or 32-bit IEEE float. Anything else is unreadable. */+ float: boolean;+}++/** The `fmt ` chunk, or null for a format this cannot safely edit in place. */+function readFmtChunk(buffer: Buffer, body: number): WavFmt | null {+ const format = buffer.readUInt16LE(body);+ const bits = buffer.readUInt16LE(body + 14);+ const float = format === FLOAT_FORMAT;+ if (!float && format !== PCM_FORMAT) return null;+ if (bits !== (float ? 32 : 16)) return null;+ const numChannels = buffer.readUInt16LE(body + 2);+ if (numChannels < 1) return null;+ return { numChannels, sampleRate: buffer.readUInt32LE(body + 4), float };+}++function isRiffWave(buffer: Buffer): boolean {+ return (+ buffer.length >= 12 &&+ buffer.toString("ascii", 0, 4) === "RIFF" &&+ buffer.toString("ascii", 8, 12) === "WAVE"+ );+}+function parseWavLayout(buffer: Buffer): WavLayout | null {- if (buffer.length < 12 || buffer.toString("ascii", 0, 4) !== "RIFF") return null;- if (buffer.toString("ascii", 8, 12) !== "WAVE") return null;+ if (!isRiffWave(buffer)) return null;- let fmt: { numChannels: number; sampleRate: number; bitsPerSample: number } | null = null;+ let fmt: WavFmt | null = null;let data: { offset: number; size: number } | null = null;for (const { id, body, size } of riffChunks(buffer)) {if (id === "fmt " && body + 16 <= buffer.length) {- if (buffer.readUInt16LE(body) !== PCM_FORMAT) return null;- fmt = {- numChannels: buffer.readUInt16LE(body + 2),- sampleRate: buffer.readUInt32LE(body + 4),- bitsPerSample: buffer.readUInt16LE(body + 14),- };+ fmt = readFmtChunk(buffer, body);} else if (id === "data") {data = { offset: body, size: Math.min(size, buffer.length - body) };}}if (!fmt || !data) return null;- if (fmt.bitsPerSample !== SUPPORTED_BITS || fmt.numChannels < 1) return null;- return {- numChannels: fmt.numChannels,- sampleRate: fmt.sampleRate,- dataOffset: data.offset,- dataSize: data.size,- };+ return { ...fmt, dataOffset: data.offset, dataSize: data.size };}/**@@ -103,11 +122,40 @@ export function createEnvelopeWalker(};}+/** Every sample scaled by the envelope, in place, in whichever of the two+ * formats the layout reports. Float is NOT clamped: it is the format the group+ * sub-mix writes precisely so an over-unity sum keeps its headroom until+ * something downstream chooses to reduce it. */+function scaleSamples(+ buffer: Buffer,+ layout: WavLayout,+ gainAt: (seconds: number) => number,+): void {+ const { numChannels, sampleRate, dataOffset, dataSize, float } = layout;+ const bytesPerSample = float ? 4 : 2;+ const frameBytes = numChannels * bytesPerSample;+ const frameCount = Math.floor(dataSize / frameBytes);+ const scaleOne = float+ ? (at: number, gain: number) => buffer.writeFloatLE(buffer.readFloatLE(at) * gain, at)+ : (at: number, gain: number) => {+ const scaled = Math.round(buffer.readInt16LE(at) * gain);+ buffer.writeInt16LE(scaled < -32768 ? -32768 : scaled > 32767 ? 32767 : scaled, at);+ };++ for (let frame = 0; frame < frameCount; frame += 1) {+ const gain = gainAt(frame / sampleRate);+ const base = dataOffset + frame * frameBytes;+ for (let channel = 0; channel < numChannels; channel += 1) {+ scaleOne(base + channel * bytesPerSample, gain);+ }+ }+}+/*** Multiply a prepared WAV's samples by a time-varying gain envelope in place.*- * @returns `true` if the envelope was applied; `false` if the file isn't the- * expected 16-bit PCM (caller should fall back to the expression path).+ * @returns `true` if the envelope was applied; `false` if the file is neither+ * 16-bit PCM nor 32-bit float (caller should fall back to the expression path).*/export function applyVolumeEnvelopeToWav(wavPath: string,@@ -123,20 +171,7 @@ export function applyVolumeEnvelopeToWav(const layout = parseWavLayout(buffer);if (!layout) return false;- const { numChannels, sampleRate, dataOffset, dataSize } = layout;- const bytesPerSample = SUPPORTED_BITS / 8;- const frameBytes = numChannels * bytesPerSample;- const frameCount = Math.floor(dataSize / frameBytes);-- for (let frame = 0; frame < frameCount; frame += 1) {- const gain = gainAt(frame / sampleRate);- const base = dataOffset + frame * frameBytes;- for (let channel = 0; channel < numChannels; channel += 1) {- const at = base + channel * bytesPerSample;- const scaled = Math.round(buffer.readInt16LE(at) * gain);- buffer.writeInt16LE(scaled < -32768 ? -32768 : scaled > 32767 ? 32767 : scaled, at);- }- }+ scaleSamples(buffer, layout, gainAt);// Write to a uniquely-named sibling then atomically rename over the// original. The random name avoids following a pre-planted symlink at a