Skip to content

Write HTML. Render video. Built for agents.

fix(engine): sample-accurate volume automation so dense fades keep their audio (#1117)

Miguel Ángel95d2a949b767
diff --git a/packages/engine/src/services/audioMixer.test.ts b/packages/engine/src/services/audioMixer.test.ts
index e1bf245650..f60fc7a710 100644
--- a/packages/engine/src/services/audioMixer.test.ts
+++ b/packages/engine/src/services/audioMixer.test.ts
@@ -108,6 +108,121 @@ describe("processCompositionAudio", () => {
expect(filter).toContain("adelay=2000|2000");
});
+ it("bounds expression nesting for dense keyframe automation without dropping the envelope", async () => {
+ const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-"));
+ const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-"));
+ tempDirs.push(baseDir, workDir);
+
+ writeFileSync(join(baseDir, "bgm.wav"), "stub");
+
+ // Mirrors the 60 Hz timeline probe: a 10s eased fade emits hundreds of
+ // keyframes. The nested-if volume expression must not grow one level per
+ // keyframe — past ~95 levels FFmpeg fails filter-graph init and the audio
+ // track is dropped entirely (GH #1066 follow-up).
+ const keyframes = Array.from({ length: 300 }, (_, i) => {
+ const time = (i / 299) * 10;
+ const volume =
+ time < 3 ? 0.8 * (time / 3) ** 2 : time < 7 ? 0.8 : 0.8 * (1 - (time - 7) / 3) ** 2;
+ return { time, volume };
+ });
+
+ const result = await processCompositionAudio(
+ [
+ {
+ id: "bgm",
+ src: "bgm.wav",
+ start: 0,
+ end: 10,
+ mediaStart: 0,
+ layer: 0,
+ volume: 0,
+ volumeKeyframes: keyframes,
+ type: "audio",
+ },
+ ],
+ baseDir,
+ workDir,
+ join(baseDir, "out.m4a"),
+ 10,
+ );
+
+ expect(result.success).toBe(true);
+
+ const mixArgs = runFfmpegMock.mock.calls[1]?.[0];
+ const filterIndex = mixArgs.indexOf("-filter_complex");
+ const filter = mixArgs[filterIndex + 1];
+
+ // One nested `if(lt(...))` is emitted per segment; cap it well under the
+ // FFmpeg evaluator's nesting limit (MAX_VOLUME_SEGMENTS = 32).
+ const nestingDepth = (filter.match(/if\(lt\(t/g) ?? []).length;
+ expect(nestingDepth).toBeGreaterThan(1);
+ expect(nestingDepth).toBeLessThan(32);
+
+ // The simplified envelope still spans the clip: silent start, audible peak.
+ expect(filter).toContain(":eval=frame");
+ expect(filter).toMatch(/volume=if\(lt\(t\\,[0-9.]+\)\\,0\+/);
+ });
+
+ it("falls back to a static-volume mix instead of dropping audio when the automated mix fails", async () => {
+ const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-"));
+ const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-"));
+ tempDirs.push(baseDir, workDir);
+
+ writeFileSync(join(baseDir, "bgm.wav"), "stub");
+
+ // Simulate an ffmpeg build that rejects the automation expression: the
+ // first mix attempt fails, the static-volume retry succeeds. (prepare =
+ // call 0, automated mix = call 1, fallback mix = call 2.)
+ runFfmpegMock
+ .mockImplementationOnce(async () => ({
+ success: true,
+ durationMs: 1,
+ stderr: "",
+ exitCode: 0,
+ }))
+ .mockImplementationOnce(async () => ({
+ success: false,
+ durationMs: 1,
+ stderr: "Error initializing filters",
+ exitCode: 234,
+ }));
+
+ const result = await processCompositionAudio(
+ [
+ {
+ id: "bgm",
+ src: "bgm.wav",
+ start: 0,
+ end: 5,
+ mediaStart: 0,
+ layer: 0,
+ volume: 0.8,
+ volumeKeyframes: [
+ { time: 0, volume: 0.8 },
+ { time: 5, volume: 0 },
+ ],
+ type: "audio",
+ },
+ ],
+ baseDir,
+ workDir,
+ join(baseDir, "out.m4a"),
+ 5,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.tracksProcessed).toBe(1);
+ expect(runFfmpegMock).toHaveBeenCalledTimes(3);
+ // Degradation is surfaced, not silent — the track rendered at base volume.
+ expect(result.error).toMatch(/base volume/i);
+
+ // The fallback mix omits the automation expression (base volume only).
+ const fallbackArgs = runFfmpegMock.mock.calls[2]?.[0];
+ const fallbackFilter = fallbackArgs[fallbackArgs.indexOf("-filter_complex") + 1];
+ expect(fallbackFilter).not.toContain(":eval=frame");
+ expect(fallbackFilter).toContain("volume=0.8");
+ });
+
it("prepares percent-encoded non-Latin audio srcs from decoded filesystem paths", async () => {
const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-"));
const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-"));
diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts
index 05bf083cb8..bb31a70991 100644
--- a/packages/engine/src/services/audioMixer.ts
+++ b/packages/engine/src/services/audioMixer.ts
@@ -14,6 +14,7 @@ import { runFfmpeg } from "../utils/runFfmpeg.js";
import { unwrapTemplate } from "../utils/htmlTemplate.js";
import { resolveProjectRelativeSrc } from "./videoFrameExtractor.js";
import type { AudioElement, AudioTrack, MixResult } from "./audioMixer.types.js";
+import { applyVolumeEnvelopeToWav } from "./audioVolumeEnvelope.js";
export type { AudioElement, MixResult } from "./audioMixer.types.js";
@@ -30,10 +31,89 @@ function escapeExpressionCommas(expression: string): string {
return expression.replace(/\\/g, "\\\\").replace(/,/g, "\\,");
}
-function buildVolumeExpression(track: AudioTrack): string {
+/**
+ * Upper bound on volume-automation keyframes folded into the FFmpeg `volume`
+ * expression. The expression nests one `if(lt(...))` per keyframe, and
+ * FFmpeg's expression evaluator has a finite nesting depth: past ~95 levels
+ * (build-dependent — lower on some Linux ffmpeg builds) `volume=...:eval=frame`
+ * fails filter-graph init, which fails the whole mix and drops the audio track
+ * entirely. The 60 Hz timeline probe routinely emits 100–300 keyframes for a
+ * multi-second fade (GH #1066 follow-up: a 171-keyframe GSAP fade rendered with
+ * no audio). 32 segments keeps a wide safety margin and is far more resolution
+ * than a piecewise-linear volume envelope needs.
+ */
+const MAX_VOLUME_SEGMENTS = 32;
+
+/**
+ * Volume delta below which a keyframe is collinear enough to drop. Kept tight
+ * (0.5% linear) so the rendered piecewise-linear envelope tracks the GSAP curve
+ * the browser plays in preview to within ~0.2 dB across the audible range — well
+ * under the ~1 dB loudness JND, so render stays WYSIWYG with preview. A full
+ * ease-in/ease-out fade still reduces to ~25 segments, inside MAX_VOLUME_SEGMENTS.
+ */
+const VOLUME_SIMPLIFY_EPSILON = 0.005;
+
+/**
+ * Reduce a sorted keyframe list to a perceptually-equivalent piecewise-linear
+ * envelope with a bounded segment count.
+ *
+ * Ramer–Douglas–Peucker drops control points lying within
+ * `VOLUME_SIMPLIFY_EPSILON` of the line through their neighbours (a linear fade
+ * collapses to its two endpoints; an eased fade to a handful). A uniform
+ * downsample backstop then bounds pathological inputs (e.g. audio-rate volume
+ * oscillation) to `MAX_VOLUME_SEGMENTS`. Endpoints are always preserved so the
+ * envelope still spans the full clip.
+ */
+function simplifyVolumeKeyframes(
+ keyframes: { time: number; volume: number }[],
+): { time: number; volume: number }[] {
+ if (keyframes.length < 3) return keyframes;
+
+ const keep = new Array<boolean>(keyframes.length).fill(false);
+ keep[0] = true;
+ keep[keyframes.length - 1] = true;
+ const stack: [number, number][] = [[0, keyframes.length - 1]];
+ while (stack.length > 0) {
+ const [startIndex, endIndex] = stack.pop()!;
+ const start = keyframes[startIndex]!;
+ const end = keyframes[endIndex]!;
+ const span = end.time - start.time;
+ let maxDistance = VOLUME_SIMPLIFY_EPSILON;
+ let splitIndex = -1;
+ for (let i = startIndex + 1; i < endIndex; i += 1) {
+ const point = keyframes[i]!;
+ const interpolated =
+ span === 0
+ ? start.volume
+ : start.volume + ((end.volume - start.volume) * (point.time - start.time)) / span;
+ const distance = Math.abs(point.volume - interpolated);
+ if (distance > maxDistance) {
+ maxDistance = distance;
+ splitIndex = i;
+ }
+ }
+ if (splitIndex !== -1) {
+ keep[splitIndex] = true;
+ stack.push([startIndex, splitIndex], [splitIndex, endIndex]);
+ }
+ }
+
+ const simplified = keyframes.filter((_, i) => keep[i]);
+ if (simplified.length <= MAX_VOLUME_SEGMENTS) return simplified;
+
+ const step = (simplified.length - 1) / (MAX_VOLUME_SEGMENTS - 1);
+ const sampled: { time: number; volume: number }[] = [];
+ for (let i = 0; i < MAX_VOLUME_SEGMENTS; i += 1) {
+ const point = simplified[Math.round(i * step)]!;
+ if (sampled.length === 0 || point.time > sampled.at(-1)!.time) sampled.push(point);
+ }
+ return sampled;
+}
+
+function buildVolumeExpression(track: AudioTrack, ignoreKeyframes = false): string {
const trimDuration = track.end - track.start;
const staticVolume = clampVolume(track.volume);
- const keyframes = (track.volumeKeyframes ?? [])
+ const keyframes = (ignoreKeyframes ? [] : (track.volumeKeyframes ?? []))
.filter((keyframe) => Number.isFinite(keyframe.time) && Number.isFinite(keyframe.volume))
.map((keyframe) => ({
time: Math.max(0, Math.min(trimDuration, keyframe.time - track.start)),
@@ -57,14 +137,19 @@ function buildVolumeExpression(track: AudioTrack): string {
}
}
- if (deduped.length === 1) {
- return `volume=${formatFilterNumber(deduped[0]!.volume)}`;
+ // Collapse the densely-sampled probe output to a bounded piecewise-linear
+ // envelope. Without this, the nested-if expression below grows one level per
+ // keyframe and overflows FFmpeg's expression evaluator (see MAX_VOLUME_SEGMENTS).
+ const simplified = simplifyVolumeKeyframes(deduped);
+
+ if (simplified.length === 1) {
+ return `volume=${formatFilterNumber(simplified[0]!.volume)}`;
}
- let expression = formatFilterNumber(deduped.at(-1)!.volume);
- for (let i = deduped.length - 2; i >= 0; i -= 1) {
- const current = deduped[i]!;
- const next = deduped[i + 1]!;
+ let expression = formatFilterNumber(simplified.at(-1)!.volume);
+ for (let i = simplified.length - 2; i >= 0; i -= 1) {
+ const current = simplified[i]!;
+ const next = simplified[i + 1]!;
const currentTime = formatFilterNumber(current.time);
const nextTime = formatFilterNumber(next.time);
const currentVolume = formatFilterNumber(current.volume);
@@ -299,42 +384,58 @@ async function mixAudioTracks(
const outputDir = dirname(outputPath);
if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true });
- const inputs: string[] = [];
- const filterParts: string[] = [];
-
- tracks.forEach((track, i) => {
- inputs.push("-i", track.srcPath);
- const delayMs = Math.round(track.start * 1000);
- const trimDuration = track.end - track.start;
- const volumeFilter = buildVolumeExpression(track);
- filterParts.push(
- `[${i}:a]atrim=0:${trimDuration},${volumeFilter},adelay=${delayMs}|${delayMs},apad=whole_dur=${totalDuration}[a${i}]`,
- );
- });
-
- const mixInputs = tracks.map((_, i) => `[a${i}]`).join("");
- const weights = tracks.map(() => "1").join(" ");
- const mixFilter = `${mixInputs}amix=inputs=${tracks.length}:duration=longest:dropout_transition=0:normalize=0:weights='${weights}'[mixed]`;
- const postMixGainFilter = `[mixed]volume=${masterOutputGain}[out]`;
- const fullFilter = [...filterParts, mixFilter, postMixGainFilter].join(";");
+ const buildArgs = (ignoreAutomation: boolean): string[] => {
+ const inputs: string[] = [];
+ const filterParts: string[] = [];
+ tracks.forEach((track, i) => {
+ inputs.push("-i", track.srcPath);
+ const delayMs = Math.round(track.start * 1000);
+ const trimDuration = track.end - track.start;
+ const volumeFilter = buildVolumeExpression(track, ignoreAutomation);
+ filterParts.push(
+ `[${i}:a]atrim=0:${trimDuration},${volumeFilter},adelay=${delayMs}|${delayMs},apad=whole_dur=${totalDuration}[a${i}]`,
+ );
+ });
- const args = [
- ...inputs,
- "-filter_complex",
- fullFilter,
- "-map",
- "[out]",
- "-acodec",
- "aac",
- "-b:a",
- "192k",
- "-t",
- String(totalDuration),
- "-y",
- outputPath,
- ];
+ const mixInputs = tracks.map((_, i) => `[a${i}]`).join("");
+ const weights = tracks.map(() => "1").join(" ");
+ const mixFilter = `${mixInputs}amix=inputs=${tracks.length}:duration=longest:dropout_transition=0:normalize=0:weights='${weights}'[mixed]`;
+ const postMixGainFilter = `[mixed]volume=${masterOutputGain}[out]`;
+ const fullFilter = [...filterParts, mixFilter, postMixGainFilter].join(";");
+
+ return [
+ ...inputs,
+ "-filter_complex",
+ fullFilter,
+ "-map",
+ "[out]",
+ "-acodec",
+ "aac",
+ "-b:a",
+ "192k",
+ "-t",
+ String(totalDuration),
+ "-y",
+ outputPath,
+ ];
+ };
- const result = await runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout });
+ let result = await runFfmpeg(buildArgs(false), { signal, timeout: ffmpegProcessTimeout });
+
+ // Defense in depth: volume automation is folded into an FFmpeg `volume`
+ // expression whose evaluator limits are build-dependent (see
+ // MAX_VOLUME_SEGMENTS). If that ever fails the mix, retry once without the
+ // automation so the track renders at its base volume rather than being
+ // dropped from the output entirely — a missing fade beats missing audio.
+ let degradedAutomation = false;
+ const hasAutomation = tracks.some((track) => (track.volumeKeyframes?.length ?? 0) > 0);
+ if (!result.success && !signal?.aborted && hasAutomation) {
+ const retry = await runFfmpeg(buildArgs(true), { signal, timeout: ffmpegProcessTimeout });
+ if (retry.success) {
+ result = retry;
+ degradedAutomation = true;
+ }
+ }
if (signal?.aborted) {
return {
@@ -360,6 +461,9 @@ async function mixAudioTracks(
outputPath,
durationMs: result.durationMs,
tracksProcessed: tracks.length,
+ error: degradedAutomation
+ ? "Volume automation exceeded this ffmpeg build's expression limits; rendered at base volume"
+ : undefined,
};
}
@@ -452,6 +556,19 @@ export async function processCompositionAudio(
audioSrcPath = trimmedPath;
}
+ // 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
+ // keyframes on the track for buildVolumeExpression to handle.
+ let bakedEnvelope = false;
+ if (element.volumeKeyframes && element.volumeKeyframes.length > 0) {
+ bakedEnvelope = applyVolumeEnvelopeToWav(
+ audioSrcPath,
+ element.volumeKeyframes,
+ element.start,
+ element.volume ?? 1.0,
+ );
+ }
tracks.push({
id: element.id,
srcPath: audioSrcPath,
@@ -459,8 +576,9 @@ export async function processCompositionAudio(
end: element.end,
mediaStart: element.mediaStart,
duration: element.end - element.start,
- volume: element.volume ?? 1.0,
- volumeKeyframes: element.volumeKeyframes,
+ // Gain is already in the samples when baked, so mix at unity.
+ volume: bakedEnvelope ? 1.0 : (element.volume ?? 1.0),
+ volumeKeyframes: bakedEnvelope ? undefined : element.volumeKeyframes,
});
} catch (err: unknown) {
errors.push(`Error: ${element.id} — ${err instanceof Error ? err.message : String(err)}`);
diff --git a/packages/engine/src/services/audioVolumeEnvelope.test.ts b/packages/engine/src/services/audioVolumeEnvelope.test.ts
new file mode 100644
index 0000000000..d0cb183de0
--- /dev/null
+++ b/packages/engine/src/services/audioVolumeEnvelope.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { applyVolumeEnvelopeToWav } from "./audioVolumeEnvelope.js";
+
+const SAMPLE_RATE = 48000;
+const CHANNELS = 2;
+
+/** Build a PCM s16le stereo WAV whose every sample equals `value`. */
+function writeConstantWav(path: string, frames: number, value: number): void {
+ const bytesPerSample = 2;
+ const dataSize = frames * CHANNELS * bytesPerSample;
+ 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(1, 20); // PCM
+ buffer.writeUInt16LE(CHANNELS, 22);
+ buffer.writeUInt32LE(SAMPLE_RATE, 24);
+ buffer.writeUInt32LE(SAMPLE_RATE * CHANNELS * bytesPerSample, 28);
+ buffer.writeUInt16LE(CHANNELS * bytesPerSample, 32);
+ buffer.writeUInt16LE(16, 34);
+ buffer.write("data", 36, "ascii");
+ buffer.writeUInt32LE(dataSize, 40);
+ for (let i = 0; i < frames * CHANNELS; i += 1) buffer.writeInt16LE(value, 44 + i * 2);
+ writeFileSync(path, buffer);
+}
+
+function sampleAt(path: string, frame: number, channel = 0): number {
+ const buffer = readFileSync(path);
+ return buffer.readInt16LE(44 + (frame * CHANNELS + channel) * 2);
+}
+
+describe("applyVolumeEnvelopeToWav", () => {
+ const dirs: string[] = [];
+ const tmp = () => {
+ const d = mkdtempSync(join(tmpdir(), "hf-env-"));
+ dirs.push(d);
+ return d;
+ };
+ afterEach(() => {
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
+ });
+
+ it("applies a linear fade sample-accurately", () => {
+ const path = join(tmp(), "a.wav");
+ const frames = SAMPLE_RATE; // 1 second
+ writeConstantWav(path, frames, 10000);
+
+ // Fade 0 -> 1 over the full second.
+ const applied = applyVolumeEnvelopeToWav(
+ path,
+ [
+ { time: 0, volume: 0 },
+ { time: 1, volume: 1 },
+ ],
+ 0,
+ 0,
+ );
+ expect(applied).toBe(true);
+
+ expect(sampleAt(path, 0)).toBe(0); // gain 0
+ expect(sampleAt(path, frames / 2)).toBeCloseTo(5000, -2); // gain ~0.5
+ expect(sampleAt(path, frames - 1)).toBeGreaterThan(9900); // gain ~1
+ });
+
+ it("offsets keyframes by the track start (composition time -> track-relative)", () => {
+ const path = join(tmp(), "b.wav");
+ const frames = SAMPLE_RATE;
+ writeConstantWav(path, frames, 10000);
+
+ // Track starts at 5s; the fade runs from comp-time 5s..6s -> wav 0s..1s.
+ applyVolumeEnvelopeToWav(
+ path,
+ [
+ { time: 5, volume: 0 },
+ { time: 6, volume: 1 },
+ ],
+ 5,
+ 0,
+ );
+
+ expect(sampleAt(path, 0)).toBe(0);
+ expect(sampleAt(path, frames / 2)).toBeCloseTo(5000, -2);
+ });
+
+ it("holds base volume before the first keyframe and the last value after", () => {
+ const path = join(tmp(), "c.wav");
+ const frames = SAMPLE_RATE * 3; // 3 seconds
+ writeConstantWav(path, frames, 10000);
+
+ // Base 0.8 held until a fade-out begins at 2s.
+ applyVolumeEnvelopeToWav(
+ path,
+ [
+ { time: 2, volume: 0.8 },
+ { time: 3, volume: 0 },
+ ],
+ 0,
+ 0.8,
+ );
+
+ expect(sampleAt(path, SAMPLE_RATE)).toBeCloseTo(8000, -2); // 1s: base 0.8
+ expect(sampleAt(path, frames - 1)).toBeLessThan(200); // 3s: faded to ~0
+ });
+
+ it("handles thousands of keyframes without failing (no expression ceiling)", () => {
+ const path = join(tmp(), "d.wav");
+ const frames = SAMPLE_RATE * 2;
+ writeConstantWav(path, frames, 10000);
+
+ const keyframes = Array.from({ length: 5000 }, (_, i) => ({
+ time: (i / 4999) * 2,
+ volume: Math.abs(Math.sin(i / 50)),
+ }));
+ expect(applyVolumeEnvelopeToWav(path, keyframes, 0, 0)).toBe(true);
+ });
+
+ it("parses chunks in any order (data before fmt)", () => {
+ const path = join(tmp(), "order.wav");
+ const frames = 4;
+ const dataSize = frames * CHANNELS * 2;
+ // Lay the data chunk before fmt to exercise order-independent scanning.
+ const buffer = Buffer.alloc(12 + (8 + dataSize) + (8 + 16));
+ buffer.write("RIFF", 0, "ascii");
+ buffer.writeUInt32LE(buffer.length - 8, 4);
+ buffer.write("WAVE", 8, "ascii");
+ let o = 12;
+ buffer.write("data", o, "ascii");
+ buffer.writeUInt32LE(dataSize, o + 4);
+ for (let i = 0; i < frames * CHANNELS; i += 1) buffer.writeInt16LE(10000, o + 8 + i * 2);
+ o += 8 + dataSize;
+ buffer.write("fmt ", o, "ascii");
+ buffer.writeUInt32LE(16, o + 4);
+ buffer.writeUInt16LE(1, o + 8);
+ buffer.writeUInt16LE(CHANNELS, o + 10);
+ buffer.writeUInt32LE(SAMPLE_RATE, o + 12);
+ buffer.writeUInt16LE(16, o + 22);
+ writeFileSync(path, buffer);
+
+ expect(applyVolumeEnvelopeToWav(path, [{ time: 0, volume: 0 }], 0, 0)).toBe(true);
+ expect(readFileSync(path).readInt16LE(12 + 8)).toBe(0); // first sample muted
+ });
+
+ it("rejects non-16-bit PCM so the caller can fall back", () => {
+ const path = join(tmp(), "e.wav");
+ // 24-bit PCM header (bitsPerSample = 24); body contents are irrelevant.
+ const buffer = Buffer.alloc(44);
+ buffer.write("RIFF", 0, "ascii");
+ buffer.write("WAVE", 8, "ascii");
+ buffer.write("fmt ", 12, "ascii");
+ buffer.writeUInt32LE(16, 16);
+ buffer.writeUInt16LE(1, 20);
+ buffer.writeUInt16LE(CHANNELS, 22);
+ buffer.writeUInt32LE(SAMPLE_RATE, 24);
+ buffer.writeUInt16LE(24, 34);
+ buffer.write("data", 36, "ascii");
+ buffer.writeUInt32LE(0, 40);
+ writeFileSync(path, buffer);
+
+ expect(
+ applyVolumeEnvelopeToWav(
+ path,
+ [
+ { time: 0, volume: 0 },
+ { time: 1, volume: 1 },
+ ],
+ 0,
+ 0,
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/packages/engine/src/services/audioVolumeEnvelope.ts b/packages/engine/src/services/audioVolumeEnvelope.ts
new file mode 100644
index 0000000000..8cf99c12d1
--- /dev/null
+++ b/packages/engine/src/services/audioVolumeEnvelope.ts
@@ -0,0 +1,165 @@
+/**
+ * Sample-accurate volume automation.
+ *
+ * The audio mixer's primary path for time-varying volume bakes the envelope
+ * directly into the prepared PCM rather than encoding it as an FFmpeg `volume`
+ * expression. The expression approach nests one `if(lt(t,...))` per keyframe and
+ * overflows FFmpeg's expression evaluator past ~95 levels (a dense GSAP fade
+ * emits hundreds of keyframes), which fails the whole mix and drops the audio
+ * track. Multiplying the samples in-house has no such ceiling, is exact at every
+ * sample, and keeps the downstream ffmpeg `amix`/AAC encode untouched — so the
+ * output (and the golden baselines) only change where a fade is actually applied.
+ *
+ * The prepared tracks are always `pcm_s16le`, 48 kHz, stereo (see
+ * `prepareAudioTrack` / `extractAudioFromVideo`). Anything else is rejected so
+ * the caller can fall back to the expression path rather than corrupting audio.
+ */
+
+import { readFileSync, renameSync, writeFileSync } from "fs";
+import { randomBytes } from "crypto";
+import type { AudioVolumeKeyframe } from "./audioMixer.types.js";
+
+const PCM_FORMAT = 1; // WAVE_FORMAT_PCM
+const SUPPORTED_BITS = 16;
+
+interface WavLayout {
+ numChannels: number;
+ sampleRate: number;
+ dataOffset: number;
+ dataSize: number;
+}
+
+/**
+ * Locate the `fmt ` and `data` chunks and validate the format we know how to edit.
+ *
+ * Scans every chunk rather than assuming an ordering: the loop always advances
+ * past a chunk's body (using its declared size), so `data` may precede `fmt `
+ * and trailing chunks (LIST/fact/etc.) are skipped harmlessly. Returns null on
+ * anything unexpected so the caller falls back to the expression path.
+ */
+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;
+
+ let offset = 12;
+ let fmt: { numChannels: number; sampleRate: number; bitsPerSample: number } | null = null;
+ let data: { offset: number; size: number } | null = null;
+
+ while (offset + 8 <= buffer.length) {
+ const chunkId = buffer.toString("ascii", offset, offset + 4);
+ const chunkSize = buffer.readUInt32LE(offset + 4);
+ const body = offset + 8;
+ if (chunkId === "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),
+ };
+ } else if (chunkId === "data") {
+ data = { offset: body, size: Math.min(chunkSize, buffer.length - body) };
+ }
+ // Chunks are word-aligned: an odd size carries a trailing pad byte.
+ offset = body + chunkSize + (chunkSize % 2);
+ }
+
+ 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,
+ };
+}
+
+/**
+ * Normalise keyframes to track-relative seconds, sorted and de-duplicated, with
+ * `baseVolume` filling any gap before the first keyframe. Returns the breakpoints
+ * the gain envelope is linearly interpolated between.
+ */
+function toRelativeEnvelope(
+ keyframes: AudioVolumeKeyframe[],
+ trackStart: number,
+ baseVolume: number,
+): { time: number; volume: number }[] {
+ const points = keyframes
+ .filter((k) => Number.isFinite(k.time) && Number.isFinite(k.volume))
+ .map((k) => ({
+ time: Math.max(0, k.time - trackStart),
+ volume: Math.max(0, Math.min(1, k.volume)),
+ }))
+ .sort((a, b) => a.time - b.time);
+
+ const deduped: { time: number; volume: number }[] = [];
+ for (const point of points) {
+ const previous = deduped.at(-1);
+ if (previous && Math.abs(previous.time - point.time) < 1e-9) previous.volume = point.volume;
+ else deduped.push(point);
+ }
+
+ if (deduped.length === 0) return deduped;
+ if (deduped[0]!.time > 0) {
+ deduped.unshift({ time: 0, volume: Math.max(0, Math.min(1, baseVolume)) });
+ }
+ return deduped;
+}
+
+/**
+ * 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).
+ */
+export function applyVolumeEnvelopeToWav(
+ wavPath: string,
+ keyframes: AudioVolumeKeyframe[],
+ trackStart: number,
+ baseVolume: number,
+): boolean {
+ const envelope = toRelativeEnvelope(keyframes, trackStart, baseVolume);
+ if (envelope.length === 0) return false;
+
+ try {
+ const buffer = readFileSync(wavPath);
+ 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);
+
+ let segment = 0;
+ for (let frame = 0; frame < frameCount; frame += 1) {
+ const time = frame / sampleRate;
+ while (segment < envelope.length - 2 && time >= envelope[segment + 1]!.time) segment += 1;
+
+ const a = envelope[segment]!;
+ const b = envelope[segment + 1] ?? a;
+ const span = b.time - a.time;
+ const progress = span <= 0 ? 0 : Math.min(1, Math.max(0, (time - a.time) / span));
+ const gain = a.volume + (b.volume - a.volume) * progress;
+
+ 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);
+ }
+ }
+
+ // Write to a uniquely-named sibling then atomically rename over the
+ // original. The random name avoids following a pre-planted symlink at a
+ // predictable path, and the rename means a crash mid-write can't leave a
+ // truncated WAV for the downstream mix.
+ const tempPath = `${wavPath}.${randomBytes(6).toString("hex")}.tmp`;
+ writeFileSync(tempPath, buffer);
+ renameSync(tempPath, wavPath);
+ return true;
+ } catch {
+ // Any read/parse/write failure → leave the file untouched and let the
+ // caller fall back to the ffmpeg expression path rather than losing audio.
+ return false;
+ }
+}