Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit c21316a839d95af8cdfa56050a18989acdbdace0
parent 559077ea4c3be3f39479ab218ed23a6b11d7f9e0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 10:13:30 -0400

report video: sync.json after every build -- each clip's sound found in the cut

sync-report.mjs measures each clip's own sound against its slot in the
finished cut (lag.py's method in node: mono 4 kHz, cross-correlated past the
joins, coarse then fine), writes <out>/sync.json {at, fps, items: [{id,
start, lagMs, peak}]} and says any clip off by more than a frame. Runs after
the full build and --chrome-only; REPORT_VIDEO_SYNC=0 skips it; never fails
a build. AUDIO_ON_CLOCK moves to clip-audio.mjs.

On the Huck cut's current final it reads exactly what lag.py read (0, -68,
-469 ms); on the sound re-assembled with the fix, every clip 0 ms.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/report-to-video/build-video.mjs | 44+++++++++++++++++++++++++++++++++++---------
Aumtool/report-to-video/clip-audio.mjs | 15+++++++++++++++
Aumtool/report-to-video/sync-report.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/sync-report.test.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 273 insertions(+), 9 deletions(-)

diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -146,6 +146,8 @@ import { // The effects region (`render.chrome.fx`, release 35): pure, in fx.mjs. import { fxOn, fxQuoteSpan, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs"; import { stampsDrawn, validateClaims } from "./factcheck.mjs"; +import { AUDIO_ON_CLOCK } from "./clip-audio.mjs"; +import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; @@ -750,6 +752,7 @@ export function clipFetchArgs({ url, from, to, fmt, dest, extra = [] }) { // Common's (lib/evidenceClip.mjs) since a report site cuts its evidence clips // with the same arguments: re-exported, never re-spelled. export { cutArgs }; +export { AUDIO_ON_CLOCK }; /** * The span a clip's source is needed over: its extent, widened by the fetch @@ -4073,15 +4076,6 @@ export async function cutOffsets(segments, D, fps, joins = null) { } /** - * A sound laid on its own timestamps from 0: silence where its first sample - * starts late or where a hole opens, samples dropped where two overlap -- - * whatever is more than 10 ms off (a third of a frame); no resampling, and a - * stream with neither passes sample for sample. Every filter after it that - * counts samples (apad, acrossfade, concat) then counts the clock. - */ -export const AUDIO_ON_CLOCK = "aresample=async=1:min_hard_comp=0.01:first_pts=0"; - -/** * The crossfade concat's filtergraph from the cut's segment lengths (`durs`, * holds included) and the per-input joins. Without joins, the graph it always was. */ @@ -5071,6 +5065,36 @@ export function concatRecordText(segments, joins = null) { * with them (the deck's holds and moves) the concat filter over each input's * chain, one encode -- the copy cannot host a filtergraph. */ +/** + * The sync report over a finished cut (sync-report.mjs): each clip's own + * sound found in `final`, against its slot in the cut's clock (cutOffsets, + * holds included), written to `<outDir>/sync.json`; a clip off by more than a + * frame is said. Cards, teasers and the rest have no source sound to check. + * `REPORT_VIDEO_SYNC=0` skips it. Never fails a build: a report it cannot + * make is said. + */ +export async function reportSync({ outDir, final, entries, segments, D, render, joins = null, env = process.env }) { + if (env.REPORT_VIDEO_SYNC === "0") return null; + try { + const { starts, durs } = await cutOffsets(segments, D, render.fps, joins); + const items = entries + .map((e, i) => ({ e, i })) + .filter(({ e }) => isClipEntry(e) && e.id !== WALL_ENTRY.id) + // The segment's own length (the hold is silence the file does not carry). + .map(({ e, i }) => ({ id: e.id, segment: segments[i], start: starts[i], seconds: durs[i] - (joins?.[i]?.hold ?? 0) })); + const doc = await writeSyncReport({ + outDir, final, items, fps: render.fps, D, + onLog: (message) => EMIT("note", { message }), + }); + const off = doc.items.filter((it) => it.lagMs != null && Math.abs(it.lagMs) > 1000 / render.fps).length; + EMIT("sync", { file: path.join(outDir, SYNC_FILE), clips: doc.items.length, off }); + return doc; + } catch (err) { + EMIT("note", { message: `sync report not made: ${err?.message ?? err}` }); + return null; + } +} + async function concatHardCut(segments, outDir, outPath, { record = false, joins = null, render = null, dips = null } = {}) { if (joins) { await execFileP(FFMPEG, hardCutFilterArgs(segments, joins, render, outPath, dips), { maxBuffer: 1 << 26 }); @@ -5735,6 +5759,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ? null : await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); + await reportSync({ outDir, final: dirs.final, entries, segments: segs, D, render, joins }); await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; @@ -5895,6 +5920,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ? null : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); + await reportSync({ outDir, final, entries, segments, D, render, joins }); // A branded cut with a `thumbnail` gets one beside it. The cut is already // done, so a thumbnail that cannot be made is said, not thrown. diff --git a/umtool/report-to-video/clip-audio.mjs b/umtool/report-to-video/clip-audio.mjs @@ -0,0 +1,15 @@ +// A clip's sound at its segment encode: laid on its own clock, and the +// per-clip `audio` knobs (offset, gain, fades). +// +// No imports from build-video.mjs: it imports this file, and so do the sync +// report and umtool's writers (K2's updateClip validates through +// validateClipAudio). + +/** + * A sound laid on its own timestamps from 0: silence where its first sample + * starts late or where a hole opens, samples dropped where two overlap -- + * whatever is more than 10 ms off (a third of a frame); no resampling, and a + * stream with neither passes sample for sample. Every filter after it that + * counts samples (apad, acrossfade, concat) then counts the clock. + */ +export const AUDIO_ON_CLOCK = "aresample=async=1:min_hard_comp=0.01:first_pts=0"; diff --git a/umtool/report-to-video/sync-report.mjs b/umtool/report-to-video/sync-report.mjs @@ -0,0 +1,145 @@ +// The sync report: after a build, where each clip's own sound lands in the +// finished cut against where its picture is scheduled. `<out>/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 `<outDir>/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; +} diff --git a/umtool/report-to-video/sync-report.test.mjs b/umtool/report-to-video/sync-report.test.mjs @@ -0,0 +1,78 @@ +// The sync report finds each clip's own sound in the finished cut. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { xfadeGraph } from "./build-video.mjs"; +import { bestMatch, bestMatchFast, measureWindow, SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; + +const have = spawnSync("ffmpeg", ["-version"]).status === 0; +const RENDER = { width: 160, height: 90, fps: 30, audioRate: 48000, audioChannels: 2 }; + +test("measureWindow: past the joins, up to six seconds from three in; none under a second", () => { + assert.deepEqual(measureWindow(30, 0.5), { from: 3, len: 6 }); + assert.deepEqual(measureWindow(8, 0.5), { from: 1, len: 6 }); + const w = measureWindow(4, 0.5); + assert.equal(w.from, 0.6); + assert.ok(Math.abs(w.len - 2.8) < 1e-9); + assert.equal(measureWindow(1.5, 0.5), null); +}); + +test("bestMatch / bestMatchFast: the offset a copy sits at", () => { + let seed = 7; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31) - 0.5; + // Low-passed noise, as speech is to a 4 kHz decode. + const b = new Float32Array(4000); + let y = 0; + for (let i = 0; i < b.length; i += 1) b[i] = y = 0.7 * y + rnd(); + const a = b.slice(1234, 1234 + 1000); + assert.equal(bestMatch(a, b).offset, 1234); + assert.equal(bestMatchFast(a, b).offset, 1234); + assert.ok(bestMatch(a, b).peak > 0.95); +}); + +function segment(dir, name, seed) { + const out = path.join(dir, `${name}.mp4`); + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", + "-f", "lavfi", "-i", "color=c=gray:s=160x90:r=30:d=8", + "-f", "lavfi", "-i", `anoisesrc=d=8:c=pink:r=48000:a=0.3:seed=${seed}`, + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ac", "2", out, + ]); + assert.equal(r.status, 0, String(r.stderr)); + return out; +} + +test("writeSyncReport: in sync it reads 0; a cut whose sound is 100 ms late reads +100", { skip: !have && "no ffmpeg" }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "sync-report-")); + try { + const segs = [segment(dir, "a", 1), segment(dir, "b", 2), segment(dir, "c", 3)]; + const D = 0.5; + const g = xfadeGraph([8, 8, 8], D, null, RENDER); + const final = path.join(dir, "final.mp4"); + let r = spawnSync("ffmpeg", ["-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", final]); + assert.equal(r.status, 0, String(r.stderr)); + const items = segs.map((s, i) => ({ id: `c${i}`, segment: s, start: i * (8 - D), seconds: 8 })); + const logs = []; + const doc = await writeSyncReport({ outDir: dir, final, items, fps: 30, D, onLog: (l) => logs.push(l) }); + for (const it of doc.items) assert.ok(Math.abs(it.lagMs) <= 2, `${it.id} lag ${it.lagMs}`); + assert.deepEqual(logs, []); + assert.deepEqual(JSON.parse(readFileSync(path.join(dir, SYNC_FILE), "utf8")).items.map((it) => it.id), ["c0", "c1", "c2"]); + + const late = path.join(dir, "late.mp4"); + r = spawnSync("ffmpeg", ["-v", "error", "-y", "-i", final, "-af", "adelay=100:all=1", "-c:v", "copy", "-c:a", "aac", late]); + assert.equal(r.status, 0, String(r.stderr)); + const bad = await writeSyncReport({ outDir: dir, final: late, items, fps: 30, D, onLog: (l) => logs.push(l) }); + for (const it of bad.items) assert.ok(Math.abs(it.lagMs - 100) <= 2, `${it.id} lag ${it.lagMs}`); + assert.equal(logs.length, 3); + assert.match(logs[0], /^sync: c0 sound late by 10\d ms/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});