// The sync report: after a build, where each clip's own sound lands in the // finished cut against where its picture is scheduled. `/sync.json` // `{ at, fps, items: [{ id, start, lagMs, peak }] }`. // // The method is the one the Huck desync was measured with (lag.py): a few // seconds of the segment's sound, past its crossfade, cross-correlated against // the final's sound around the same slot, both mono at 4 kHz. `lagMs` > 0 is // sound LATER than its picture; `peak` (≈ 0..1) is how well the two matched // -- a muted or near-silent clip matches weakly and its lag means little. import { execFile } from "node:child_process"; import { writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { AUDIO_ON_CLOCK } from "./clip-audio.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; export const SYNC_FILE = "sync.json"; export const SYNC_RATE = 4000; /** Below this the match is too weak for a lag to be called a fault. */ export const SYNC_WEAK_PEAK = 0.3; /** `seconds` of `file`'s sound from `from`, mono f32 at `rate`, on its own clock. */ export async function pcmMono(file, from, seconds, rate = SYNC_RATE) { const { stdout } = await execFileP(FFMPEG(), [ "-nostdin", "-v", "error", "-ss", Math.max(0, from).toFixed(3), "-t", seconds.toFixed(3), "-i", file, "-vn", "-af", AUDIO_ON_CLOCK, "-ac", "1", "-ar", String(rate), "-f", "f32le", "-", ], { encoding: "buffer", maxBuffer: 1 << 28 }); return new Float32Array(stdout.buffer, stdout.byteOffset, Math.floor(stdout.length / 4)); } /** * Where `a` sits in `b`: the offset (samples) of the best match of `a` inside * `b`, and that match's strength -- lag.py's normalised correlation peak. */ export function bestMatch(a, b, { from = 0, to = Infinity } = {}) { const n = a.length; const m = Math.min(b.length - n + 1, to + 1); if (n < 2 || m < 1) return null; let mean = 0; for (let i = 0; i < n; i += 1) mean += a[i]; mean /= n; let v = 0; for (let i = 0; i < n; i += 1) v += (a[i] - mean) ** 2; const sd = Math.sqrt(v / n) + 1e-9; const an = new Float32Array(n); for (let i = 0; i < n; i += 1) an[i] = (a[i] - mean) / sd; let bm = 0; for (let i = 0; i < b.length; i += 1) bm += b[i]; bm /= b.length; let bv = 0; const bn = new Float32Array(b.length); for (let i = 0; i < b.length; i += 1) { bn[i] = b[i] - bm; bv += bn[i] * bn[i]; } const bsd = Math.sqrt(bv / b.length) + 1e-9; let best = -Infinity; let k = Math.max(0, from); for (let o = Math.max(0, from); o < m; o += 1) { let c = 0; for (let j = 0; j < n; j += 1) c += an[j] * bn[o + j]; if (c > best) { best = c; k = o; } } return { offset: k, peak: best / n / bsd }; } /** `x` averaged down by `f`. */ function decimate(x, f) { const out = new Float32Array(Math.floor(x.length / f)); for (let i = 0; i < out.length; i += 1) { let s = 0; for (let j = 0; j < f; j += 1) s += x[i * f + j]; out[i] = s / f; } return out; } /** * bestMatch, found coarse first: at a quarter of the rate over every offset, * then at the full rate within ±8 samples of the coarse peak -- the same * answer as the full search on speech, a tenth of the work. */ export function bestMatchFast(a, b, f = 4) { const coarse = bestMatch(decimate(a, f), decimate(b, f)); if (!coarse) return bestMatch(a, b); const at = coarse.offset * f; return bestMatch(a, b, { from: at - 2 * f, to: at + 2 * f }); } /** * The window of a segment `seconds` long that is measured: past the joins at * either end (`D`), up to `span` seconds from `lead` in. Null when the segment * has under a second of its own between them. */ export function measureWindow(seconds, D = 0.5, { lead = 3, span = 6 } = {}) { const from = Math.min(lead, Math.max(D + 0.1, (seconds - span) / 2)); const len = Math.min(span, seconds - D - 0.1 - from); return len >= 1 ? { from, len } : null; } /** * One clip's lag in the final: its segment's sound over `measureWindow`, * found in the final's within ±`slack` of where its slot puts it. */ export async function clipLag({ segment, final, start, seconds, D = 0.5, slack = 2.5, rate = SYNC_RATE }) { const w = measureWindow(seconds, D); if (!w) return null; const a = await pcmMono(segment, w.from, w.len, rate); const lo = start + w.from - slack; const b = await pcmMono(final, lo, w.len + 2 * slack, rate); // A slot near the cut's head cannot look `slack` back: what it can. const back = Math.min(slack, start + w.from); if (a.length < rate * 0.9 || b.length < a.length) return null; const hit = bestMatchFast(a, b); if (!hit) return null; return { lagMs: Math.round((hit.offset / rate - back) * 1000), peak: Number(hit.peak.toFixed(2)) }; } /** * The report for a finished cut: every clip of `items` (`{ id, segment, start, * seconds }`, starts in the cut's clock) measured, written to `/sync.json`. * `onLog(line)` hears each clip off by more than a frame. */ export async function writeSyncReport({ outDir, final, items, fps, D = 0.5, onLog = () => {} }) { const out = []; for (const it of items) { const r = await clipLag({ segment: it.segment, final, start: it.start, seconds: it.seconds, D }).catch(() => null); const row = { id: it.id, start: Number(it.start.toFixed(3)), lagMs: r?.lagMs ?? null, peak: r?.peak ?? null }; out.push(row); if (r && Math.abs(r.lagMs) > 1000 / fps) { onLog(`sync: ${it.id} sound ${r.lagMs > 0 ? "late" : "early"} by ${Math.abs(r.lagMs)} ms` + (r.peak < SYNC_WEAK_PEAK ? ` (weak match, peak ${r.peak})` : "")); } } const doc = { at: new Date().toISOString(), fps, items: out }; await writeFile(path.join(outDir, SYNC_FILE), JSON.stringify(doc, null, 2) + "\n"); return doc; }