Skip to content

Write HTML. Render video. Built for agents.

fix(producer): constrain delivered AAC true peak (#3644)

Miguel Ángelcb44fe1c0b7b
diff --git a/packages/producer/src/services/render/audioPadTrim.integration.test.ts b/packages/producer/src/services/render/audioPadTrim.integration.test.ts
index 5c7162fe8f..65ce5c966c 100644
--- a/packages/producer/src/services/render/audioPadTrim.integration.test.ts
+++ b/packages/producer/src/services/render/audioPadTrim.integration.test.ts
@@ -3,14 +3,40 @@ import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
+import { getFfmpegBinary, muxVideoWithAudio } from "@hyperframes/engine";
import { padOrTrimAudioToVideoFrameCount } from "./audioPadTrim.js";
const dirs: string[] = [];
afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })));
+function measureLoudness(path: string): { integratedLufs: number; truePeakDbfs: number } {
+ const result = spawnSync(
+ getFfmpegBinary(),
+ [
+ "-nostdin",
+ "-hide_banner",
+ "-nostats",
+ "-i",
+ path,
+ "-af",
+ "ebur128=peak=true",
+ "-f",
+ "null",
+ "-",
+ ],
+ { encoding: "utf8" },
+ );
+ const integrated = [...result.stderr.matchAll(/^\s*I:\s*([+-]?[\d.]+) LUFS$/gm)].at(-1)?.[1];
+ const truePeak = [...result.stderr.matchAll(/^\s*Peak:\s*([+-]?[\d.]+) dBFS$/gm)].at(-1)?.[1];
+ if (result.status !== 0 || integrated === undefined || truePeak === undefined) {
+ throw new Error(`Could not measure loudness: ${result.stderr}`);
+ }
+ return { integratedLufs: Number(integrated), truePeakDbfs: Number(truePeak) };
+}
+
const hasFfmpeg = (() => {
try {
- execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+ execFileSync(getFfmpegBinary(), ["-version"], { stdio: "ignore" });
execFileSync("ffprobe", ["-version"], { stdio: "ignore" });
return true;
} catch {
@@ -79,4 +105,77 @@ describe.skipIf(!hasFfmpeg)("audio pad real-media packet contract", () => {
expect(duration).toBeLessThan(16.1);
expect(Number(packets.at(-1)?.duration_time)).toBeLessThan(0.1);
});
+
+ it("keeps the delivered AAC below its true-peak ceiling", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-aac-peak-"));
+ dirs.push(dir);
+ const source = join(dir, "source.wav");
+ const mixed = join(dir, "mixed.m4a");
+ const video = join(dir, "video.mp4");
+ const normalized = join(dir, "normalized.m4a");
+ const delivered = join(dir, "delivered.mp4");
+ const ffmpeg = getFfmpegBinary();
+
+ const sourceResult = spawnSync(ffmpeg, [
+ "-nostdin",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "aevalsrc=if(gte(sin(2*PI*5000*t)\\,0)\\,0.60042\\,-0.60042)|if(gte(sin(2*PI*5000*t)\\,0)\\,0.60042\\,-0.60042):s=48000:d=3:c=stereo",
+ "-c:a",
+ "pcm_f32le",
+ source,
+ ]);
+ expect(sourceResult.status, sourceResult.stderr?.toString()).toBe(0);
+ const mixResult = spawnSync(ffmpeg, [
+ "-nostdin",
+ "-v",
+ "error",
+ "-i",
+ source,
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ mixed,
+ ]);
+ expect(mixResult.status, mixResult.stderr?.toString()).toBe(0);
+ const videoResult = spawnSync(ffmpeg, [
+ "-nostdin",
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=black:size=16x16:rate=30:duration=3",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ video,
+ ]);
+ expect(videoResult.status, videoResult.stderr?.toString()).toBe(0);
+
+ const normalizedResult = await padOrTrimAudioToVideoFrameCount({
+ videoPath: video,
+ audioPath: mixed,
+ outputPath: normalized,
+ probeVideoFrameInfo: async () => ({ frameCount: 90, fpsNum: 30, fpsDen: 1 }),
+ probeAudioInfo: async () => ({ durationSeconds: 3.029333 }),
+ });
+ expect(normalizedResult.success, normalizedResult.error).toBe(true);
+ expect(normalizedResult.operation).toBe("trim");
+
+ const muxResult = await muxVideoWithAudio(video, normalized, delivered);
+ expect(muxResult.success, muxResult.error).toBe(true);
+ const sourceLevel = measureLoudness(source);
+ const deliveredLevel = measureLoudness(delivered);
+ expect(sourceLevel.truePeakDbfs).toBeCloseTo(-1.5, 1);
+ expect(deliveredLevel.truePeakDbfs).toBeLessThanOrEqual(-1);
+ expect(
+ Math.abs(deliveredLevel.integratedLufs - sourceLevel.integratedLufs),
+ ).toBeLessThanOrEqual(3);
+ });
});
diff --git a/packages/producer/src/services/render/audioPadTrim.test.ts b/packages/producer/src/services/render/audioPadTrim.test.ts
index c72f95efbb..095e4c119f 100644
--- a/packages/producer/src/services/render/audioPadTrim.test.ts
+++ b/packages/producer/src/services/render/audioPadTrim.test.ts
@@ -111,7 +111,7 @@ describe("buildPadTrimAudioArgs", () => {
});
describe("padOrTrimAudioToVideoFrameCount", () => {
- // Build a minimal harness that stubs out the three injectables.
+ // Build a minimal harness that stubs out the duration probes and ffmpeg runner.
function harness(opts: {
video: ProbeVideoFrameInfo | "throw";
audio: AudioProbeInfo | "throw";
@@ -292,6 +292,43 @@ describe("padOrTrimAudioToVideoFrameCount", () => {
failureReason: "external_interruption",
});
});
+
+ it("accepts silence as already below the AAC true-peak ceiling", async () => {
+ const { input, captured } = harness({
+ video: { frameCount: 90, fpsNum: 30, fpsDen: 1 },
+ audio: { durationSeconds: 3 },
+ });
+ input.probeAudioTruePeakDbfs = async () => Number.NEGATIVE_INFINITY;
+
+ const result = await padOrTrimAudioToVideoFrameCount(input);
+
+ expect(result.success).toBe(true);
+ expect(captured.args).toHaveLength(1);
+ });
+
+ it("attenuates the duration-normalized artifact from its measured AAC true peak", async () => {
+ const calls: string[][] = [];
+ const { input } = harness({
+ video: { frameCount: 90, fpsNum: 30, fpsDen: 1 },
+ audio: { durationSeconds: 3.029333 },
+ });
+ input.probeAudioTruePeakDbfs = async () => 1.5;
+ input.runFfmpeg = async (args) => {
+ calls.push(args);
+ return calls.length === 1
+ ? { success: true }
+ : { success: false, error: "synthetic correction stop" };
+ };
+
+ const result = await padOrTrimAudioToVideoFrameCount(input);
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe("synthetic correction stop");
+ expect(calls).toHaveLength(2);
+ const correctionArgs = calls[1]!;
+ expect(correctionArgs[correctionArgs.indexOf("-af") + 1]).toBe("volume=-2.500dB");
+ expect(correctionArgs[correctionArgs.indexOf("-t") + 1]).toBe("3.000000");
+ });
});
// ── Public-path path redaction ────────────────────────────────────────────
diff --git a/packages/producer/src/services/render/audioPadTrim.ts b/packages/producer/src/services/render/audioPadTrim.ts
index 2ec2ea8e70..e4ecb4e5d1 100644
--- a/packages/producer/src/services/render/audioPadTrim.ts
+++ b/packages/producer/src/services/render/audioPadTrim.ts
@@ -20,7 +20,8 @@
*/
import { spawn } from "node:child_process";
-import { rmSync } from "node:fs";
+import { mkdtempSync, renameSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
import {
extractAudioMetadata,
formatFfmpegError,
@@ -39,6 +40,10 @@ import { redactKnownPaths, redactTelemetryString } from "@hyperframes/core";
*/
const AUDIO_DURATION_TOLERANCE_SECONDS = 0.001;
+/** Delivery headroom applied after every AAC encode in this stage. */
+export const AAC_DELIVERY_TRUE_PEAK_DBFS = -1;
+const MAX_TRUE_PEAK_CORRECTION_PASSES = 3;
+
export interface ProbeVideoFrameInfo {
/** Number of video frames in the stream. */
frameCount: number;
@@ -73,6 +78,7 @@ export interface PadTrimAudioInput {
*/
probeVideoFrameInfo?: (videoPath: string) => Promise<ProbeVideoFrameInfo>;
probeAudioInfo?: (audioPath: string, signal?: AbortSignal) => Promise<AudioProbeInfo>;
+ probeAudioTruePeakDbfs?: (audioPath: string, signal?: AbortSignal) => Promise<number>;
runFfmpeg?: (args: string[]) => Promise<{
success: boolean;
error?: string;
@@ -110,6 +116,31 @@ export interface PadTrimAudioPlan {
cleanupPaths: string[];
}
+function buildAacTruePeakCorrectionArgs(
+ inputPath: string,
+ outputPath: string,
+ targetDurationSeconds: number,
+ attenuationDb: number,
+): string[] {
+ return [
+ "-i",
+ inputPath,
+ "-map",
+ "0:a:0",
+ "-vn",
+ "-af",
+ `volume=${attenuationDb.toFixed(3)}dB`,
+ "-t",
+ formatSeconds(targetDurationSeconds),
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ "-y",
+ outputPath,
+ ];
+}
+
/**
* Pure helper: decide the pad/trim operation and build the ffmpeg argv
* sequence that materializes it. Exported separately so unit tests can pin
@@ -258,6 +289,11 @@ export async function padOrTrimAudioToVideoFrameCount(
((videoPath: string) => defaultProbeVideoFrameInfo(videoPath, input.signal));
const probeAudio = input.probeAudioInfo ?? defaultProbeAudioInfo;
const runner = input.runFfmpeg ?? ((args: string[]) => defaultRunFfmpeg(args, input.signal));
+ // Injected runners usually do not materialize media. Tests that exercise
+ // peak correction opt in with a matching probe; production always uses the
+ // real post-codec measurement.
+ const probeTruePeak =
+ input.probeAudioTruePeakDbfs ?? (input.runFfmpeg ? undefined : defaultProbeAudioTruePeakDbfs);
// Probe video and audio in parallel — the two ffprobe invocations are
// independent and account for most of this function's wall-clock time.
@@ -346,6 +382,27 @@ export async function padOrTrimAudioToVideoFrameCount(
} finally {
for (const path of plan.cleanupPaths) rmSync(path, { force: true });
}
+
+ if (probeTruePeak) {
+ const correction = await enforceAacTruePeak({
+ audioPath: input.outputPath,
+ targetDurationSeconds,
+ signal: input.signal,
+ probeTruePeak,
+ runner,
+ });
+ if (!correction.success) {
+ return {
+ success: false,
+ outputPath: input.outputPath,
+ targetDurationSeconds,
+ sourceDurationSeconds: audioInfo.durationSeconds,
+ operation: plan.operation,
+ error: correction.error,
+ failureReason: correction.failureReason,
+ };
+ }
+ }
return {
success: true,
outputPath: input.outputPath,
@@ -355,6 +412,76 @@ export async function padOrTrimAudioToVideoFrameCount(
};
}
+interface EnforceAacTruePeakInput {
+ audioPath: string;
+ targetDurationSeconds: number;
+ signal?: AbortSignal;
+ probeTruePeak: (audioPath: string, signal?: AbortSignal) => Promise<number>;
+ runner: (args: string[]) => Promise<{
+ success: boolean;
+ error?: string;
+ failureReason?: "external_interruption";
+ }>;
+}
+
+async function enforceAacTruePeak(
+ input: EnforceAacTruePeakInput,
+): Promise<{ success: boolean; error?: string; failureReason?: "external_interruption" }> {
+ let scratchDir: string | undefined;
+ try {
+ scratchDir = mkdtempSync(join(dirname(input.audioPath), ".true-peak-"));
+ const correctedPath = join(scratchDir, "audio.m4a");
+ let attenuationDb = 0;
+ let measuredPath = input.audioPath;
+ for (let pass = 0; pass <= MAX_TRUE_PEAK_CORRECTION_PASSES; pass += 1) {
+ const truePeakDbfs = await input.probeTruePeak(measuredPath, input.signal);
+ if (Number.isNaN(truePeakDbfs) || truePeakDbfs === Number.POSITIVE_INFINITY) {
+ return { success: false, error: "audioPadTrim: FFmpeg reported an invalid true peak" };
+ }
+ if (truePeakDbfs <= AAC_DELIVERY_TRUE_PEAK_DBFS) {
+ if (measuredPath === correctedPath) renameSync(correctedPath, input.audioPath);
+ return { success: true };
+ }
+ if (pass === MAX_TRUE_PEAK_CORRECTION_PASSES) break;
+
+ attenuationDb += AAC_DELIVERY_TRUE_PEAK_DBFS - truePeakDbfs;
+ const result = await input.runner(
+ buildAacTruePeakCorrectionArgs(
+ input.audioPath,
+ correctedPath,
+ input.targetDurationSeconds,
+ attenuationDb,
+ ),
+ );
+ if (!result.success) {
+ return {
+ success: false,
+ error: sanitizeProbeFailure(
+ result.error ?? "audioPadTrim: failed to constrain AAC true peak",
+ [input.audioPath, correctedPath],
+ ),
+ failureReason: result.failureReason,
+ };
+ }
+ measuredPath = correctedPath;
+ }
+ return {
+ success: false,
+ error: `audioPadTrim: AAC true peak remained above ${AAC_DELIVERY_TRUE_PEAK_DBFS} dBFS after ${MAX_TRUE_PEAK_CORRECTION_PASSES} correction passes`,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ error: `audioPadTrim: failed to validate AAC true peak: ${sanitizeProbeFailure(
+ err,
+ scratchDir ? [input.audioPath, scratchDir] : [input.audioPath],
+ )}`,
+ };
+ } finally {
+ if (scratchDir) rmSync(scratchDir, { recursive: true, force: true });
+ }
+}
+
function failResult(
outputPath: string,
target: number,
@@ -461,6 +588,26 @@ async function defaultProbeAudioInfo(
};
}
+async function defaultProbeAudioTruePeakDbfs(
+ audioPath: string,
+ signal?: AbortSignal,
+): Promise<number> {
+ const result = await runFfmpeg(
+ ["-i", audioPath, "-map", "0:a:0", "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"],
+ { signal },
+ );
+ if (!result.success) {
+ throw new Error(`[audioPadTrim] ${formatFfmpegError(result.exitCode, result.stderr)}`);
+ }
+ const matches = [...result.stderr.matchAll(/^\s*Peak:\s*([+-]?(?:[\d.]+|inf)) dBFS$/gim)];
+ const token = matches.at(-1)?.[1]?.toLowerCase();
+ const value = token === "-inf" ? Number.NEGATIVE_INFINITY : Number(token);
+ if (Number.isNaN(value) || value === Number.POSITIVE_INFINITY) {
+ throw new Error("[audioPadTrim] FFmpeg did not report AAC true peak");
+ }
+ return value;
+}
+
async function defaultRunFfmpeg(
args: string[],
signal?: AbortSignal,