Skip to content

Commit 58707af

Browse files
fix(producer): reserve AAC correction headroom (#3693)
1 parent 4aa6e17 commit 58707af

2 files changed

Lines changed: 65 additions & 4 deletions

File tree

‎packages/producer/src/services/render/audioPadTrim.test.ts‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
*/
1515

1616
import { describe, expect, it, mock } from "bun:test";
17+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
18+
import { tmpdir } from "node:os";
19+
import { join } from "node:path";
1720
import {
1821
buildPadTrimAudioArgs,
1922
buildPadTrimAudioPlan,
@@ -306,7 +309,7 @@ describe("padOrTrimAudioToVideoFrameCount", () => {
306309
expect(captured.args).toHaveLength(1);
307310
});
308311

309-
it("attenuates the duration-normalized artifact from its measured AAC true peak", async () => {
312+
it("attenuates the duration-normalized artifact with AAC correction headroom", async () => {
310313
const calls: string[][] = [];
311314
const { input } = harness({
312315
video: { frameCount: 90, fpsNum: 30, fpsDen: 1 },
@@ -326,9 +329,59 @@ describe("padOrTrimAudioToVideoFrameCount", () => {
326329
expect(result.error).toBe("synthetic correction stop");
327330
expect(calls).toHaveLength(2);
328331
const correctionArgs = calls[1]!;
329-
expect(correctionArgs[correctionArgs.indexOf("-af") + 1]).toBe("volume=-2.500dB");
332+
expect(correctionArgs[correctionArgs.indexOf("-af") + 1]).toBe("volume=-3.000dB");
330333
expect(correctionArgs[correctionArgs.indexOf("-t") + 1]).toBe("3.000000");
331334
});
335+
336+
it("uses correction headroom to converge within three AAC passes", async () => {
337+
const dir = mkdtempSync(join(tmpdir(), "hf-aac-convergence-"));
338+
const corrections: number[] = [];
339+
let attenuationDb = 0;
340+
const { input } = harness({
341+
video: { frameCount: 90, fpsNum: 30, fpsDen: 1 },
342+
audio: { durationSeconds: 3 },
343+
});
344+
input.videoPath = join(dir, "video.mp4");
345+
input.audioPath = join(dir, "source.m4a");
346+
input.outputPath = join(dir, "normalized.m4a");
347+
input.probeAudioTruePeakDbfs = async () => attenuationDb * 0.4;
348+
input.runFfmpeg = async (args) => {
349+
const filter = args[args.indexOf("-af") + 1];
350+
if (filter?.startsWith("volume=")) {
351+
attenuationDb = Number(filter.slice("volume=".length, -2));
352+
corrections.push(attenuationDb);
353+
}
354+
writeFileSync(args.at(-1)!, "");
355+
return { success: true };
356+
};
357+
358+
try {
359+
const result = await padOrTrimAudioToVideoFrameCount(input);
360+
361+
expect(result.success, result.error).toBe(true);
362+
expect(corrections).toEqual([-1.5, -2.4, -2.94]);
363+
} finally {
364+
rmSync(dir, { recursive: true, force: true });
365+
}
366+
});
367+
368+
it("reports every measured peak and attenuation when correction is exhausted", async () => {
369+
const peaks = [0, -0.4, -0.6, -0.8];
370+
let probeIndex = 0;
371+
const { input } = harness({
372+
video: { frameCount: 90, fpsNum: 30, fpsDen: 1 },
373+
audio: { durationSeconds: 3 },
374+
});
375+
input.probeAudioTruePeakDbfs = async () => peaks[probeIndex++]!;
376+
377+
const result = await padOrTrimAudioToVideoFrameCount(input);
378+
379+
expect(result.success).toBe(false);
380+
expect(result.error).toContain("pass 0: 0.000 dBFS at 0.000 dB attenuation");
381+
expect(result.error).toContain("pass 1: -0.400 dBFS at -1.500 dB attenuation");
382+
expect(result.error).toContain("pass 2: -0.600 dBFS at -2.600 dB attenuation");
383+
expect(result.error).toContain("pass 3: -0.800 dBFS at -3.500 dB attenuation");
384+
});
332385
});
333386

334387
// ── Public-path path redaction ────────────────────────────────────────────

‎packages/producer/src/services/render/audioPadTrim.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const AUDIO_DURATION_TOLERANCE_SECONDS = 0.001;
4242

4343
/** Delivery headroom applied after every AAC encode in this stage. */
4444
export const AAC_DELIVERY_TRUE_PEAK_DBFS = -1;
45+
const AAC_TRUE_PEAK_CORRECTION_HEADROOM_DB = 0.5;
4546
const MAX_TRUE_PEAK_CORRECTION_PASSES = 3;
4647

4748
export interface ProbeVideoFrameInfo {
@@ -431,10 +432,15 @@ async function enforceAacTruePeak(
431432
try {
432433
scratchDir = mkdtempSync(join(dirname(input.audioPath), ".true-peak-"));
433434
const correctedPath = join(scratchDir, "audio.m4a");
435+
const correctionTargetDbfs = AAC_DELIVERY_TRUE_PEAK_DBFS - AAC_TRUE_PEAK_CORRECTION_HEADROOM_DB;
436+
const measurements: string[] = [];
434437
let attenuationDb = 0;
435438
let measuredPath = input.audioPath;
436439
for (let pass = 0; pass <= MAX_TRUE_PEAK_CORRECTION_PASSES; pass += 1) {
437440
const truePeakDbfs = await input.probeTruePeak(measuredPath, input.signal);
441+
measurements.push(
442+
`pass ${pass}: ${truePeakDbfs.toFixed(3)} dBFS at ${attenuationDb.toFixed(3)} dB attenuation`,
443+
);
438444
if (Number.isNaN(truePeakDbfs) || truePeakDbfs === Number.POSITIVE_INFINITY) {
439445
return { success: false, error: "audioPadTrim: FFmpeg reported an invalid true peak" };
440446
}
@@ -444,7 +450,9 @@ async function enforceAacTruePeak(
444450
}
445451
if (pass === MAX_TRUE_PEAK_CORRECTION_PASSES) break;
446452

447-
attenuationDb += AAC_DELIVERY_TRUE_PEAK_DBFS - truePeakDbfs;
453+
// Aim below the acceptance ceiling because this correction itself is
454+
// another lossy AAC encode and can regenerate content-dependent peaks.
455+
attenuationDb += correctionTargetDbfs - truePeakDbfs;
448456
const result = await input.runner(
449457
buildAacTruePeakCorrectionArgs(
450458
input.audioPath,
@@ -467,7 +475,7 @@ async function enforceAacTruePeak(
467475
}
468476
return {
469477
success: false,
470-
error: `audioPadTrim: AAC true peak remained above ${AAC_DELIVERY_TRUE_PEAK_DBFS} dBFS after ${MAX_TRUE_PEAK_CORRECTION_PASSES} correction passes`,
478+
error: `audioPadTrim: AAC true peak remained above ${AAC_DELIVERY_TRUE_PEAK_DBFS} dBFS after ${MAX_TRUE_PEAK_CORRECTION_PASSES} correction passes; ${measurements.join("; ")}`,
471479
};
472480
} catch (err) {
473481
return {

0 commit comments

Comments
 (0)