Skip to content

Commit e937e60

Browse files
committed
fix(producer): an export over the peak ceiling loses only what it must
The delivery limiter cut every peak over -1 dBTP down to -3, a fixed 2 dB margin for its detector. It now limits at -1, measures the encode, and lowers the ceiling only by what that encode measured over.
1 parent f55990e commit e937e60

3 files changed

Lines changed: 152 additions & 39 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { spawnSync } from "node:child_process";
2+
import { createHash } from "node:crypto";
3+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4+
import { tmpdir } from "node:os";
5+
import { join } from "node:path";
6+
import { afterEach, describe, expect, it } from "vitest";
7+
import { encodeAac, getFfmpegBinary, resolveHeadlessShellPath } from "@hyperframes/engine";
8+
import { limitDeliveryPeaks } from "./audioDeliveryLimit.js";
9+
import { measureTruePeakDbfs } from "./audioTruePeak.js";
10+
11+
const ready = (path: string | undefined | null, flag: string) =>
12+
!!path && spawnSync(path, [flag], { encoding: "utf8" }).status === 0;
13+
const browser = (() => {
14+
try {
15+
return resolveHeadlessShellPath();
16+
} catch {
17+
// A configured path that does not exist: no browser to limit with.
18+
return null;
19+
}
20+
})();
21+
const CAN_RUN = ready(getFfmpegBinary(), "-version") && ready(browser, "--version");
22+
23+
const dirs: string[] = [];
24+
afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })));
25+
26+
/** A drum hit every 0.5 s over a quiet bed, true peak about +0.1 dBTP, as float PCM; and its AAC. */
27+
async function mixOverTheCeiling() {
28+
const dir = mkdtempSync(join(tmpdir(), "hf-delivery-limit-"));
29+
dirs.push(dir);
30+
const sourcePath = join(dir, "audio-source.wav");
31+
const hit = "0.98*sin(2*PI*90*t)*exp(-mod(t,0.5)*25)";
32+
const made = spawnSync(getFfmpegBinary(), [
33+
...["-v", "error", "-y", "-f", "lavfi", "-i"],
34+
`aevalsrc='${hit}+0.02*sin(2*PI*1000*t)|${hit}+0.02*sin(2*PI*1500*t)':s=48000:d=6`,
35+
...["-c:a", "pcm_f32le", sourcePath],
36+
]);
37+
if (made.status !== 0) throw new Error(String(made.stderr));
38+
const audioPath = join(dir, "audio.m4a");
39+
const encoded = await encodeAac(sourcePath, audioPath, 6, { timeout: 60_000 });
40+
if (!encoded.success) throw new Error(encoded.stderr);
41+
return { sourcePath, audioPath };
42+
}
43+
44+
describe.skipIf(!CAN_RUN)("limitDeliveryPeaks on a real mix", () => {
45+
// fails without the fix: one pass at a fixed -3 dBTP left this mix at about -2.9 dBTP, 1.9 dB more off every hit
46+
// than the -1 dBTP rule asks.
47+
it("brings the encode under -1 dBTP losing no more than 0.2 dB past it, the same bytes every time", async () => {
48+
const runs = [];
49+
for (let run = 0; run < 2; run++) {
50+
const mix = await mixOverTheCeiling();
51+
const before = await measureTruePeakDbfs(mix.audioPath, { timeoutMs: 60_000 });
52+
expect(before).toBeGreaterThan(-1);
53+
const limited = await limitDeliveryPeaks({
54+
...mix,
55+
targetDurationSeconds: 6,
56+
timeoutMs: 120_000,
57+
});
58+
expect(limited.success).toBe(true);
59+
const after = await measureTruePeakDbfs(mix.audioPath, { timeoutMs: 60_000 });
60+
runs.push({
61+
after,
62+
bytes: createHash("sha256").update(readFileSync(mix.audioPath)).digest("hex"),
63+
});
64+
}
65+
expect(runs[0]!.after).toBeLessThanOrEqual(-1);
66+
expect(runs[0]!.after).toBeGreaterThanOrEqual(-1.2);
67+
expect(runs[1]!.bytes).toBe(runs[0]!.bytes);
68+
}, 300_000);
69+
});

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

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ const INPUT = {
77
targetDurationSeconds: 8,
88
timeoutMs: 1000,
99
};
10-
const LIMITED = "/w/audio-source-limited.wav";
10+
const LIMITED = ["/w/audio-source-limited-a.wav", "/w/audio-source-limited-b.wav"];
1111

12-
function deps(peak: number) {
12+
/** `peaks`: what each measure reads in turn, the first encode's then each limited encode's; the last one repeats. */
13+
function deps(...peaks: number[]) {
14+
let read = 0;
1315
return {
14-
measure: vi.fn(async () => peak),
15-
applyChain: vi.fn(async () => ({ path: LIMITED, envelopeBaked: false })),
16+
measure: vi.fn(async () => peaks[Math.min(read++, peaks.length - 1)]!),
17+
applyChain: vi.fn(async () => ({ path: LIMITED[0]!, envelopeBaked: false })),
1618
encode: vi.fn(async () => ({ success: true })),
1719
rename: vi.fn(),
1820
sourceExists: vi.fn(() => true),
@@ -30,21 +32,46 @@ describe("limitDeliveryPeaks", () => {
3032
expect(d.encode).not.toHaveBeenCalled();
3133
});
3234

33-
it("re-encodes a mix over the ceiling through a true-peak limit 2 dB under it", async () => {
34-
const d = deps(2.4);
35+
const ceilings = (d: ReturnType<typeof deps>) =>
36+
d.applyChain.mock.calls.map(
37+
([, chain]) =>
38+
(chain as { nodes: { params: { ceiling: number } }[] }).nodes[0]!.params.ceiling,
39+
);
40+
41+
it("limits a mix over the ceiling at the ceiling itself when its encode lands under", async () => {
42+
const d = deps(2.4, -1.1);
3543
await limitDeliveryPeaks(INPUT, d as unknown as Deps);
44+
expect(ceilings(d)).toEqual([-1]);
3645
expect(d.applyChain).toHaveBeenCalledWith(
3746
INPUT.sourcePath,
38-
{
39-
version: 1,
40-
nodes: [{ type: "truepeak", id: "delivery", params: { ceiling: -3 } }],
41-
},
42-
LIMITED,
47+
expect.anything(),
48+
LIMITED[0],
4349
expect.anything(),
4450
);
45-
expect(d.encode).toHaveBeenCalledWith(LIMITED, INPUT.audioPath, 8, expect.anything());
51+
expect(d.encode).toHaveBeenCalledWith(LIMITED[0], INPUT.audioPath, 8, expect.anything());
4652
// The whole-mix cut behind this measures against the limited mix, not the original.
47-
expect(d.rename).toHaveBeenCalledWith(LIMITED, INPUT.sourcePath, { copyFallback: true });
53+
expect(d.rename).toHaveBeenCalledWith(LIMITED[0], INPUT.sourcePath, { copyFallback: true });
54+
});
55+
56+
it("lowers the ceiling by what each encode measured over, from the original mix, never past -3", async () => {
57+
const d = deps(2.4, -0.4, -0.9, 0.5);
58+
await limitDeliveryPeaks(INPUT, d as unknown as Deps);
59+
expect(ceilings(d).map((c) => Number(c.toFixed(2)))).toEqual([-1, -1.65, -1.8]);
60+
expect(d.applyChain.mock.calls.every(([from]) => from === INPUT.sourcePath)).toBe(true);
61+
expect(d.rename).toHaveBeenCalledWith(LIMITED[0], INPUT.sourcePath, { copyFallback: true });
62+
63+
const deep = deps(2.4, 3, 3);
64+
await limitDeliveryPeaks(INPUT, deep as unknown as Deps);
65+
expect(ceilings(deep)).toEqual([-1, -3]);
66+
});
67+
68+
it("keeps the last good pass when a later limit cannot run", async () => {
69+
const d = deps(2.4, -0.5);
70+
d.applyChain.mockResolvedValueOnce({ path: LIMITED[0]!, envelopeBaked: false });
71+
d.applyChain.mockRejectedValueOnce(new Error("browser gone"));
72+
await limitDeliveryPeaks(INPUT, d as unknown as Deps);
73+
expect(d.encode).toHaveBeenCalledTimes(1);
74+
expect(d.rename).toHaveBeenCalledWith(LIMITED[0], INPUT.sourcePath, { copyFallback: true });
4875
});
4976

5077
it("leaves the first encode for the whole-mix cut when the limit cannot run, and says so", async () => {

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

Lines changed: 43 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ import {
99
import { AAC_DELIVERY_TRUE_PEAK_DBFS } from "./audioPadTrim.js";
1010
import { measureTruePeakDbfs } from "./audioTruePeak.js";
1111

12-
// The worklet's 4x detector can land up to 1.7 dB over its ceiling, hence 2 dB under the -1 dBTP limit.
13-
const LIMIT_CEILING_DBTP = AAC_DELIVERY_TRUE_PEAK_DBFS - 2;
14-
const LIMIT_CHAIN = {
12+
// Each pass lowers the ceiling by what the last encode measured over it; past -3 dBTP the whole-mix cut takes over.
13+
const LIMIT_PASSES = 3;
14+
const LOWEST_CEILING_DBTP = AAC_DELIVERY_TRUE_PEAK_DBFS - 2;
15+
const PASS_HEADROOM_DB = 0.05;
16+
const limitChain = (ceiling: number) => ({
1517
version: 1 as const,
16-
nodes: [{ type: "truepeak", id: "delivery", params: { ceiling: LIMIT_CEILING_DBTP } }],
17-
};
18+
nodes: [{ type: "truepeak", id: "delivery", params: { ceiling } }],
19+
});
1820

1921
interface DeliveryLimitDeps {
2022
measure: typeof measureTruePeakDbfs;
@@ -45,30 +47,45 @@ export async function limitDeliveryPeaks(
4547
): Promise<{ success: boolean; error?: string; failureReason?: "external_interruption" }> {
4648
const { audioPath, sourcePath, signal, timeoutMs } = input;
4749
if (!deps.sourceExists(sourcePath)) return { success: true };
48-
const peak = await deps.measure(audioPath, { timeoutMs, signal });
50+
let peak = await deps.measure(audioPath, { timeoutMs, signal });
4951
if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS) return { success: true };
5052

51-
const limitedPath = join(dirname(sourcePath), "audio-source-limited.wav");
52-
try {
53-
await deps.applyChain(sourcePath, LIMIT_CHAIN, limitedPath, { trackId: "delivery", signal });
54-
} catch (error) {
55-
if (signal?.aborted) throw error;
56-
input.warn?.("[audio] true-peak limit failed, the whole-mix cut applies", {
57-
error: error instanceof Error ? error.message : String(error),
53+
const alternating = ["a", "b"].map((k) => join(dirname(sourcePath), `audio-source-limited-${k}.wav`));
54+
let encodedFrom: string | undefined;
55+
let ceiling = AAC_DELIVERY_TRUE_PEAK_DBFS;
56+
for (let pass = 0; pass < LIMIT_PASSES; pass++) {
57+
const limitedPath = alternating[pass % 2]!;
58+
try {
59+
await deps.applyChain(sourcePath, limitChain(ceiling), limitedPath, {
60+
trackId: "delivery",
61+
signal,
62+
});
63+
} catch (error) {
64+
if (signal?.aborted) throw error;
65+
input.warn?.("[audio] true-peak limit failed, the whole-mix cut applies", {
66+
error: error instanceof Error ? error.message : String(error),
67+
});
68+
break;
69+
}
70+
const encoded = await deps.encode(limitedPath, audioPath, input.targetDurationSeconds, {
71+
signal,
72+
timeout: timeoutMs,
5873
});
59-
return { success: true };
74+
if (!encoded.success) {
75+
return {
76+
success: false,
77+
error: `[audioDeliveryLimit] ${describeFfmpegFailure(encoded, timeoutMs)}`,
78+
failureReason: encoded.failureReason,
79+
};
80+
}
81+
encodedFrom = limitedPath;
82+
peak = await deps.measure(audioPath, { timeoutMs, signal });
83+
if (peak <= AAC_DELIVERY_TRUE_PEAK_DBFS || ceiling <= LOWEST_CEILING_DBTP) break;
84+
ceiling = Math.max(
85+
ceiling - (peak - AAC_DELIVERY_TRUE_PEAK_DBFS) - PASS_HEADROOM_DB,
86+
LOWEST_CEILING_DBTP,
87+
);
6088
}
61-
const encoded = await deps.encode(limitedPath, audioPath, input.targetDurationSeconds, {
62-
signal,
63-
timeout: timeoutMs,
64-
});
65-
if (!encoded.success) {
66-
return {
67-
success: false,
68-
error: `[audioDeliveryLimit] ${describeFfmpegFailure(encoded, timeoutMs)}`,
69-
failureReason: encoded.failureReason,
70-
};
71-
}
72-
deps.rename(limitedPath, sourcePath, { copyFallback: true });
89+
if (encodedFrom) deps.rename(encodedFrom, sourcePath, { copyFallback: true });
7390
return { success: true };
7491
}

0 commit comments

Comments
 (0)