Skip to content

Commit 27f1b2e

Browse files
committed
fix(producer): a true-peak scan with no summary fails instead of reading 0 dBFS
A run whose stderr has no Peak line threw before the parser moved; it parsed as 0 dBFS after, which would lower and re-encode audio that was never measured. It throws again. When one segment scan fails, the others are stopped, and only 48 kHz audio is split into segments, since ebur128 resamples any other rate.
1 parent 4296fb8 commit 27f1b2e

2 files changed

Lines changed: 76 additions & 7 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { runFfmpeg, type RunFfmpegResult } from "@hyperframes/engine";
3+
import { measureTruePeakDbfs } from "./audioTruePeak.js";
4+
5+
vi.mock("@hyperframes/engine", async (importOriginal) => ({
6+
...(await importOriginal<typeof import("@hyperframes/engine")>()),
7+
runFfmpeg: vi.fn(),
8+
}));
9+
10+
const FRAME =
11+
"[Parsed_ebur128_0 @ 0x1] t: 0.1 M:-20.0 S:-20.0 I:-20.0 LUFS FTPK: -3.0 dBFS TPK: -3.0 dBFS";
12+
const SUMMARY = " True peak:\n Peak: -3.0 dBFS";
13+
const ran = (success: boolean, stderr: string): RunFfmpegResult => ({
14+
success,
15+
exitCode: success ? 0 : 1,
16+
stderr,
17+
durationMs: 1,
18+
terminationReason: "exit",
19+
});
20+
const segments = { durationSeconds: 180, sampleRate: 48_000 };
21+
22+
afterEach(() => vi.mocked(runFfmpeg).mockReset());
23+
24+
describe("measureTruePeakDbfs against ffmpeg's stderr", () => {
25+
it("throws when ffmpeg prints no true-peak summary", async () => {
26+
vi.mocked(runFfmpeg).mockImplementation(async (_, opts) => {
27+
opts?.onStderr?.(`${FRAME}\n`);
28+
return ran(true, FRAME);
29+
});
30+
await expect(measureTruePeakDbfs("in.m4a", { timeoutMs: 1000 })).rejects.toThrow(
31+
"FFmpeg did not report AAC true peak",
32+
);
33+
});
34+
35+
it("measures a rate other than 48 kHz in one whole-file pass", async () => {
36+
vi.mocked(runFfmpeg).mockResolvedValue(ran(true, `${FRAME}\n${SUMMARY}`));
37+
const peak = await measureTruePeakDbfs("in.m4a", {
38+
timeoutMs: 1000,
39+
segments: { ...segments, sampleRate: 44_100 },
40+
});
41+
expect(peak).toBe(-3);
42+
expect(runFfmpeg).toHaveBeenCalledOnce();
43+
});
44+
45+
it("stops the other segment scans when one fails", async () => {
46+
const others: (AbortSignal | undefined)[] = [];
47+
vi.mocked(runFfmpeg).mockImplementation(async (args, opts) => {
48+
if (args.some((arg) => arg.startsWith("atrim=start_sample=0:"))) return ran(false, "boom");
49+
others.push(opts?.signal);
50+
const signal = opts?.signal;
51+
if (signal) await new Promise((stop) => signal.addEventListener("abort", stop));
52+
return ran(false, "stopped");
53+
});
54+
await expect(measureTruePeakDbfs("in.m4a", { timeoutMs: 1000, segments })).rejects.toThrow();
55+
expect(others.map((signal) => signal?.aborted)).toEqual([true, true]);
56+
});
57+
});

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

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,16 @@ async function scanTruePeak(
4848
}
4949
const summary = [...result.stderr.matchAll(/^\s*Peak:\s*([+-]?(?:[\d.]+|inf)) dBFS$/gim)];
5050
return {
51-
peak: checkedDbfs(toDbfs(summary.at(-1)?.[1] ?? "")),
51+
peak: checkedDbfs(toDbfs(summary.at(-1)?.[1] ?? "nan")),
5252
firstBlock: checkedDbfs(firstBlock ?? Number.NEGATIVE_INFINITY),
5353
laterBlocks: checkedDbfs(laterBlocks),
5454
};
5555
}
5656

5757
/**
5858
* The true peak one `ebur128=peak=true` pass over the whole file reports, measured as parallel
59-
* segments when the length and rate are known. Same value to the printed digit, not an estimate.
59+
* segments when the length is known and the rate is 48 kHz. Same value to the printed digit,
60+
* not an estimate.
6061
*/
6162
export async function measureTruePeakDbfs(
6263
audioPath: string,
@@ -68,21 +69,32 @@ export async function measureTruePeakDbfs(
6869
): Promise<number> {
6970
const { timeoutMs, signal, segments } = options;
7071
const wholeFile = async () => (await scanTruePeak(audioPath, "", timeoutMs, signal)).peak;
71-
// ebur128 logs one peak per 100 ms block; its 4x oversampler reads 15 samples back, 16 ahead.
72-
const block = (segments?.sampleRate ?? 0) / 10;
73-
const count = segments && Number.isInteger(block) ? aacSegmentCount(segments.durationSeconds) : 1;
72+
// ebur128 resamples any other rate to 48 kHz, which would move samples near each cut.
73+
// It logs one peak per 100 ms block; its 4x oversampler reads 15 samples back, 16 ahead.
74+
const block = 4800;
75+
const count = segments?.sampleRate === 48_000 ? aacSegmentCount(segments.durationSeconds) : 1;
7476
if (!segments || count === 1) return wholeFile();
7577

7678
const cut = (k: number) => k * Math.floor((segments.durationSeconds * 10) / count) * block;
79+
const peers = new AbortController();
80+
const segmentSignal = signal ? AbortSignal.any([signal, peers.signal]) : peers.signal;
7781
const scans = await Promise.all(
7882
Array.from({ length: count }, (_, k) => {
7983
// A later segment starts one block early and drops that block: its oversampler starts
8084
// from mirrored history there, and the previous segment stops 16 samples short.
8185
const start = k === 0 ? 0 : cut(k) - block;
8286
const end = k === count - 1 ? "" : `:end_sample=${cut(k + 1)}`;
83-
return scanTruePeak(audioPath, `atrim=start_sample=${start}${end},`, timeoutMs, signal);
87+
return scanTruePeak(
88+
audioPath,
89+
`atrim=start_sample=${start}${end},`,
90+
timeoutMs,
91+
segmentSignal,
92+
);
8493
}),
85-
);
94+
).catch((error: unknown) => {
95+
peers.abort();
96+
throw error;
97+
});
8698
const last = scans[count - 1]!;
8799
const counted = Math.max(scans[0]!.peak, ...scans.slice(1).map((scan) => scan.laterBlocks));
88100
// The last segment's final partial block is logged only in its summary, which also holds its

0 commit comments

Comments
 (0)