// Every clip's sound lands with its picture, whatever its audio's timestamps say. // // A segment is in sync by its TIMESTAMPS: one whose audio starts late (a cut // that reaches before its window's media begins) or has a hole (a source's HLS // seam) plays right on its own. The joins count SAMPLES -- apad, atrim's // reset, acrossfade, concat -- so, unaligned, the late start and the hole moved // that clip's sound and every later clip's early (469 ms and 68 ms on the Huck // cut, 2026-10-22). These segments put a tone burst exactly 1.0 s into each by // its timestamps: the second's audio starts 0.5 s late, the third's has a // 60 ms hole before its tone. In every join path -- one crossfade pass, a // batched one, the hard-cut concat filter -- each burst must start within a // frame of 1.0 s after its segment does. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { buildXfadeBatches, hardCutFilterArgs, xfadeConcatArgs, xfadeGraph } from "./build-video.mjs"; const have = spawnSync("ffmpeg", ["-version"]).status === 0; const FPS = 30; const RENDER = { width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, transition: 0.5, preset: "ultrafast", palette: { bg: "#12101a" } }; const SECONDS = 4; /** * A 4 s segment whose sound has a 0.5 s tone burst at TIMESTAMP 1.0 s. * `late`: the audio stream starts this late (s). `hole`: a gap of this many * seconds opens in the audio's timestamps at 0.5 s. */ function segment(dir, name, { late = 0, hole = 0 } = {}) { const out = path.join(dir, `${name}.mp4`); // The tone in SAMPLE time, so that after the shifts it sits at pts 1.0. const on = 1.0 - late - hole; const shift = [ late ? `asetpts=PTS+${late}/TB` : null, hole ? `asetpts='PTS+gte(T,0.5)*${hole}/TB'` : null, ].filter(Boolean); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=gray:s=320x180:r=${FPS}:d=${SECONDS}`, "-f", "lavfi", "-i", `sine=f=1000:r=48000:d=${(SECONDS - late - hole - 0.02).toFixed(3)}`, "-filter_complex", `[1:a]volume=enable='not(between(t,${on.toFixed(3)},${(on + 0.5).toFixed(3)}))':volume=0,aformat=channel_layouts=stereo${shift.length ? "," + shift.join(",") : ""}[a]`, "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", out, ]); assert.equal(r.status, 0, String(r.stderr)); return out; } /** The time (s) of the first loud 5 ms window at or after `after`, in a file's decoded sound. */ function onsetAfter(file, after) { const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { maxBuffer: 1 << 26 }); const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, r.stdout.length / 2); const w = 40; for (let i = Math.floor(after * 8000); i + w < pcm.length; i += w) { let sum = 0; for (let k = i; k < i + w; k += 1) sum += pcm[k] * pcm[k]; if (Math.sqrt(sum / w) > 1000) return i / 8000; } return null; } function run(args) { const r = spawnSync("ffmpeg", args, { maxBuffer: 1 << 26 }); assert.equal(r.status, 0, String(r.stderr)); } /** Each segment's burst, measured in `file` against where its segment starts there. */ function assertOnsets(file, starts, what) { starts.forEach((s, i) => { const got = onsetAfter(file, s + 0.6); assert.ok(got != null, `${what}: no burst in segment ${i}`); assert.ok(Math.abs(got - (s + 1.0)) <= 1 / FPS, `${what}: segment ${i}'s burst at ${got.toFixed(3)}, expected ${(s + 1).toFixed(3)}`); }); } test("the joins lay each clip's sound on its own clock: a late start and a hole stay in sync", { skip: !have && "no ffmpeg" }, async () => { const dir = mkdtempSync(path.join(tmpdir(), "av-clock-")); try { const segs = [ segment(dir, "plain"), segment(dir, "late", { late: 0.5 }), segment(dir, "hole", { hole: 0.06 }), segment(dir, "after"), ]; // The fixtures are what they say: the late one's audio starts at 0.5 s. const st = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", segs[1]]); assert.ok(Math.abs(Number(String(st.stdout).trim()) - 0.5) < 0.03, `late fixture starts at ${String(st.stdout).trim()}`); const D = RENDER.transition; const durs = segs.map(() => SECONDS); const xStarts = durs.map((_, i) => i * (SECONDS - D)); // One crossfade pass. const one = path.join(dir, "one.mp4"); const g = xfadeGraph(durs, D, null, RENDER); run(["-v", "error", "-y", ...segs.flatMap((s) => ["-i", s]), "-filter_complex", g.parts.join(";"), "-map", g.vlab, "-map", g.alab, "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", one]); assertOnsets(one, xStarts, "one pass"); // Batched: two batches of two, then the join pass over the batch files. const batches = await buildXfadeBatches({ segments: segs, durs, batches: [{ from: 0, to: 2 }, { from: 2, to: 4 }], render: RENDER, dir: path.join(dir, "batches"), }); const batched = path.join(dir, "batched.mp4"); run(xfadeConcatArgs({ segments: segs, durs, render: RENDER, outPath: batched, dip: false, batches })); assertOnsets(batched, xStarts, "batched"); // Hard cuts through the concat filter (a cut with joins). const hard = path.join(dir, "hard.mp4"); run(hardCutFilterArgs(segs, [null, null, null, null], RENDER, hard)); assertOnsets(hard, durs.map((_, i) => i * SECONDS), "hard cut"); } finally { rmSync(dir, { recursive: true, force: true }); } });