diff --git a/tools/aqua-feel/SYNC.md b/tools/aqua-feel/SYNC.md index e65b1c8..4426cca 100644 --- a/tools/aqua-feel/SYNC.md +++ b/tools/aqua-feel/SYNC.md @@ -14,13 +14,16 @@ capture feels in sync. Nothing here heard or saw anything. node feel.mjs sync --wav capture.wav --track frames.csv [--events hits.txt] [--fps 60] [--kind luma|flux] # a video with one audio and one video stream (needs ffmpeg + ffprobe on PATH) node feel.mjs sync --video capture.mp4 [--events hits.txt] [--kind luma|flux] -# options: --profile default|bt1359|ebu-r37|atsc-is191 --lead-ms N --lag-ms N --json out.json --no-gate -node sync.test.mjs # 19 checks on synthetic fixtures +# options: --profile default|bt1359|ebu-r37|atsc-is191 --lead-ms N --lag-ms N --pair-window-ms N (default 300) +# --min-gap-ms N --allow-unpaired --json out.json --no-gate +# ffmpeg/ffprobe: on PATH, or FFMPEG=/path FFPROBE=/path (a static ffmpeg without ffprobe works) +node sync.test.mjs # 34 checks on synthetic fixtures (35 with ffmpeg: FFMPEG=/path/to/ffmpeg also runs a real browser capture) node sync-fixture.mjs DIR 80 60 # write a fixture (audio 80 ms late, 60 fps) to try the CLI on ``` -Exit 0 when every pair is `inside-window` or `borderline`; 1 when any pair is outside the window, an event has no onset, or nothing -paired; 2 on a tool error. `--no-gate` always exits 0. +Exit 0 when no pair is detectably outside the window; 1 when any pair is outside, an event or onset is unpaired or has no partner, a pairing is ambiguous, +or nothing paired; 2 on a tool error (bad option, unreadable or malformed input). `--no-gate` always exits 0. `--allow-unpaired` stops stray +onsets (background hits that have no counterpart) from failing the check. **Inputs.** `frames.csv`: one row per video frame, `t,value` in seconds (a header line is skipped), or one value per line with `--fps`. `value` is mean frame luminance (`--kind luma`, default: a flash or cut is a positive step) or a frame-difference magnitude @@ -31,14 +34,18 @@ offsets are applied so both clocks are the container's. **Lag convention.** `lag = audio onset - visual onset`. Positive means the sound comes after the picture (audio late); negative means the sound comes first (audio early). With `--events`, each logged event is matched to the nearest audio and nearest visual onset within 300 ms, and `a-ev` / `v-ev` give each side's offset from the logged time, so you can tell which side is late. Without an -event log, onsets pair by proximity (within 300 ms, one-to-one). +event log, audio onsets pair with visual onsets by proximity (within 300 ms, one-to-one, nearest first). **A pair is `ambiguous-pairing` and fails the check when +another onset of the same kind lies inside the pairing window**: with hits closer together than about twice the lag, the nearest onset is not +necessarily the right one and no amount of arithmetic can tell. Narrow `--pair-window-ms` if you know the lag is small, or space your events out. +Parsers refuse input they cannot read (timecodes, a third column, empty cells, non-increasing times) rather than guess. ## How onsets are found - **Audio:** log-magnitude spectral flux (1024-sample window, 128-sample hop, 60 Hz and up), half-wave rectified; peaks over - median + 8 robust sigmas, at least 50 ms apart; each is then refined on the samples to the first one within 20 dB of the local peak. + median + 8 robust sigmas, at least 50 ms apart; each is then refined on the samples to the first one that rises above both 10% of the local peak and + 2.5 times the steady bed (the median block peak of the 0.1 s before, after removing the median as DC). A bed louder than a tenth of the hit still defeats it. - **Visual:** the positive step (luma) or the value (flux) of the track; peaks over median + 8 robust sigmas and at least 10% of the - track's range, at least 100 ms apart; the onset is the first frame of the rise reaching 50% of the peak. + track's range, at least 100 ms apart (`--min-gap-ms` changes it, for both trains; flashes closer than that merge into one onset and the events beyond the first go unpaired); the onset is the first frame of the rise reaching 50% of the peak. ## Verdict @@ -51,9 +58,10 @@ Per pair, against a window of how far audio may lead (`lead`) or trail (`lag`) t | `ebu-r37` | 40 | 60 | EBU R37 (2007) limit for emission, sound before / after picture. Figure taken from a secondary summary, the EBU text was not read | | `atsc-is191` | 15 | 45 | ATSC IS-191 (2003) limit at the DTV encoder input. Secondary summary; the same document gives +30 / -90 ms end to end. The document itself was not read | -Verdict words: `inside-window`; `audio-late-detectable` / `audio-early-detectable` (outside the window by more than the measurement -uncertainty); `borderline` (the window edge lies within the uncertainty); `no-audio-onset` / `no-visual-onset` / `no-onsets` (the -logged event had no onset within 300 ms). `pass` means every pair is `inside-window` or `borderline` and none is missing. +Verdict words: `inside-window` (the whole truth interval, below, lies inside the window); `audio-late-detectable` / `audio-early-detectable` (the whole interval lies outside); +`borderline` (the interval straddles a window edge: not shown to be outside, so it does not fail the gate, and the report says "NOT DETECTABLY OUTSIDE" rather than "WITHIN"); +`ambiguous-pairing`; `no-audio-onset` / `no-visual-onset` / `no-onsets` (the logged event had no onset within the pairing window, so a sound further than 300 ms from its event +reads as absent). `pass` means no pair is detectably outside, ambiguous or missing, and nothing is unpaired (unless `--allow-unpaired`). Sources: [ITU-R BT.1359-1](https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.1359-1-199811-I!!PDF-E.pdf) (the PDF text was fragmentary in the search; figures confirmed against secondary summaries), and the TV Technology articles [AV synchronization, how bad is bad](https://www.tvtechnology.com/opinions/av-synchronization-how-bad-is-bad) and @@ -62,9 +70,11 @@ lip-sync is more sensitive than a game impact) and on the viewer; they are popul ## Uncertainty -Reported as `uncertaintyMs`: half a frame period plus half an audio hop (about +/-9.7 ms at 60 fps, +/-18 ms at 30 fps). A visual -onset can only land on a frame, and a frame stamps when the picture started to be displayed, not when the light reached the eye. -Treat lags closer together than the uncertainty as equal. +A visual onset can only land on a frame, and a frame is stamped when its picture started to be displayed. A change at time tau first shows in the first frame +stamped at or after tau, so the measured visual time is late by 0 to one frame period, and the measured lag (audio minus visual) is **biased low** by that much. The audio +onset is good to about half a hop (1.4 ms). Each pair therefore reports `lagLowMs = lag - 1.4` and `lagHighMs = lag + frame period + 1.4`: the truth lies in that interval +(16.7 + 2.7 ms wide at 60 fps; 33.3 + 2.7 ms at 30 fps), and the verdict is read off the interval. This holds for events on and off the frame grid in the fixtures +(`sync.test.mjs`). The display's own latency (the time from stamp to light) is not in it. ## What the metric cannot tell you @@ -77,12 +87,13 @@ Treat lags closer together than the uncertainty as equal. that outlives the event) is not modelled. - **Anything about the chain you did not capture.** If the capture is of the app's output, display latency, speaker/Bluetooth latency and a player's own sync are not in it. A capture can be in sync and the playback chain still be 150 ms off. -- **Variable frame rate.** Constant fps is assumed from `avg_frame_rate` (video) or the track's own timestamps (CSV, which can be - exact). A VFR video drifts. +- **Variable frame rate.** A video is resampled by presentation time to constant frame rate (ffmpeg `fps` filter), so a VFR browser capture works, but the frame period + used in the interval is the resampled one, not the source's real gaps. A CSV track keeps its own timestamps. +- **Stereo is mixed to mono**, so an antiphase stereo track cancels to silence and reads as no onsets. - **Content that is not onset-shaped.** Continuous music against continuous motion has no onsets to compare; the tool returns few or none, and silence in either track is reported as no pass, not as sync. - **Measurements from downscaled luminance.** A flash that is local (a small icon) moves the mean luminance little and may fall below the 10%-of-range floor; use a cropped frame-diff track in that case. -- **The video path is untested.** `--video` (ffmpeg/ffprobe decode) was written without ffmpeg on the machine it was built on and has never run; the WAV + track path is what the fixtures exercise. -- **The tuned constants.** The 8-sigma threshold, window sizes, 300 ms pairing window and 10% floor were set against synthetic - fixtures only (`sync-fixture.mjs`: tone-burst hits against 4-frame flashes, known offset). They have not been tuned on a real capture. +- **One real clip.** `fixtures/browser-capture.webm` is a headless-Chromium MediaRecorder capture (WebAudio beeps and canvas flashes scheduled at the same instants, vp8 + opus, recipe in `fixtures/record-browser-capture.cjs`). It is a test that the video path runs and pairs, not a validation of the lag it reports: nothing independent says what the true lag of that clip is. No Playground UI or Perlines clip has been run. +- **The tuned constants.** The 8-sigma threshold, window sizes, 300 ms pairing window, 10% floors and 2.5x bed factor were set against synthetic + fixtures (`sync-fixture.mjs`: tone-burst hits against 4-frame flashes, known offset, with noise, tone and DC beds) and one browser clip. They have not been tuned on game or music content. diff --git a/tools/aqua-feel/feel.mjs b/tools/aqua-feel/feel.mjs index 9e5835f..d94f3ab 100644 --- a/tools/aqua-feel/feel.mjs +++ b/tools/aqua-feel/feel.mjs @@ -5,7 +5,7 @@ // Usage: node feel.mjs run [--out DIR] [--only SUBSTR] [--no-gate] render, measure, write report + gallery, gate // node feel.mjs gate REPORT.json [THRESHOLDS.json] [--partial] re-gate a report (--partial: a subset; skips id-rule and waiver bookkeeping) // node feel.mjs compare BEFORE.json AFTER.json [--only SUBSTR] before/after table -// node feel.mjs sync --wav A.wav --track T.csv [--events E] | --video V [--fps N] [--kind luma|flux] [--profile P] [--json OUT] A/V synchrony (SYNC.md) +// node feel.mjs sync --wav A.wav --track T.csv [--events E] | --video V [--fps N] [--kind luma|flux] [--profile P] [--lead-ms N --lag-ms N] [--pair-window-ms N] [--min-gap-ms N] [--allow-unpaired] [--json OUT] A/V synchrony (SYNC.md) // node feel.mjs correlate TRIAL_EXPORT.json ... feel metrics vs listening-trial ratings import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; @@ -55,17 +55,22 @@ async function run() { } async function sync() { - const { syncAnalyze, readWav, readTrack, readEvents, readVideo, formatSync } = await import("./sync.mjs"); - const wav = flag("--wav"), trk = flag("--track"), vid = flag("--video"), evs = flag("--events"), fps = Number(flag("--fps") ?? 0) || undefined; - const kind = flag("--kind") ?? "luma", profile = flag("--profile") ?? "default", json = flag("--json"), noGate = bool("--no-gate"); - const lead = flag("--lead-ms"), lag = flag("--lag-ms"); - let audio, sampleRate, audioStartS = 0, visual; + const { syncAnalyze, readWav, readTrack, readEvents, readVideo, formatSync, PROFILES } = await import("./sync.mjs"); try { + const val = (n) => { const i = args.indexOf(n); if (i < 0) return undefined; if (i + 1 >= args.length || args[i + 1].startsWith("--")) throw new Error(`${n} needs a value`); return args.splice(i, 2)[1]; }; + const num = (n) => { const x = val(n); if (x === undefined) return undefined; if (!Number.isFinite(Number(x)) || x.trim() === "") throw new Error(`${n} needs a number, got "${x}"`); return Number(x); }; + const wav = val("--wav"), trk = val("--track"), vid = val("--video"), evs = val("--events"), fps = num("--fps"), json = val("--json"); + const kind = val("--kind") ?? "luma", profile = val("--profile") ?? "default", lead = num("--lead-ms"), lag = num("--lag-ms"), pw = num("--pair-window-ms"), gap = num("--min-gap-ms"); + const noGate = bool("--no-gate"), allowUnpaired = bool("--allow-unpaired"); + if (args.length) throw new Error(`unknown argument ${args[0]}`); + if (!["luma", "flux"].includes(kind)) throw new Error(`--kind is luma or flux, got "${kind}"`); + if (!PROFILES[profile]) throw new Error(`--profile is one of ${Object.keys(PROFILES).join(", ")}, got "${profile}"`); + let audio, sampleRate, audioStartS = 0, visual; if (vid) { const v = readVideo(vid); audio = v.audio.samples; sampleRate = v.audio.sampleRate; audioStartS = v.audio.startS; visual = kind === "flux" ? v.flux : v.luma; } else if (wav && trk) { const w = readWav(readFileSync(wav)); audio = w.samples; sampleRate = w.sampleRate; visual = readTrack(readFileSync(trk, "utf8"), fps); } else throw new Error("give --video FILE, or --wav FILE with --track FILE"); const r = syncAnalyze({ audio, sampleRate, audioStartS, visual, visualKind: kind, profile, events: evs ? readEvents(readFileSync(evs, "utf8")) : undefined, - leadMs: lead === undefined ? undefined : Number(lead), lagMs: lag === undefined ? undefined : Number(lag) }); + leadMs: lead, lagMs: lag, pairWindowMs: pw ?? 300, minGapMs: gap, allowUnpaired }); r.caveat = "Nothing here was heard or seen: two onset lists compared. The metric is not the verdict; see SYNC.md."; console.log(formatSync(r)); if (json) writeFileSync(json, JSON.stringify(r, null, 1)); diff --git a/tools/aqua-feel/fixtures/browser-capture.events.txt b/tools/aqua-feel/fixtures/browser-capture.events.txt new file mode 100644 index 0000000..91263c9 --- /dev/null +++ b/tools/aqua-feel/fixtures/browser-capture.events.txt @@ -0,0 +1,7 @@ +1,hit0 +1.9,hit1 +2.8,hit2 +3.4,hit3 +4.5,hit4 +5.2,hit5 +6.3,hit6 diff --git a/tools/aqua-feel/fixtures/browser-capture.webm b/tools/aqua-feel/fixtures/browser-capture.webm new file mode 100644 index 0000000..4d0abcf Binary files /dev/null and b/tools/aqua-feel/fixtures/browser-capture.webm differ diff --git a/tools/aqua-feel/fixtures/record-browser-capture.cjs b/tools/aqua-feel/fixtures/record-browser-capture.cjs new file mode 100644 index 0000000..b6c1591 --- /dev/null +++ b/tools/aqua-feel/fixtures/record-browser-capture.cjs @@ -0,0 +1,38 @@ +// Recipe for fixtures/browser-capture.webm (needs playwright-core and a chromium headless shell; edit the executablePath). Records a real browser A/V clip: WebAudio beeps + canvas flashes at the same scheduled instants, muxed by MediaRecorder. Not the Playground UI. +const { chromium } = require('playwright-core'); +const fs = require('fs'); +(async () => { + // CHROME=/path/to/chrome-headless-shell node record-browser-capture.cjs (writes clip.webm and events.txt in the cwd) + const browser = await chromium.launch({ executablePath: process.env.CHROME, args: ['--autoplay-policy=no-user-gesture-required'] }); + const pg = await (await browser.newContext({ viewport: { width: 320, height: 180 } })).newPage(); + await pg.setContent(''); + const res = await pg.evaluate(async () => { + const c = document.getElementById('c'), g = c.getContext('2d'), ctx = new AudioContext(), dest = ctx.createMediaStreamDestination(); + await ctx.resume(); + const stream = new MediaStream([...c.captureStream(30).getVideoTracks(), ...dest.stream.getAudioTracks()]); + const rec = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp8,opus' }), chunks = []; + rec.ondataavailable = e => chunks.push(e.data); + const hits = [1.0, 1.9, 2.8, 3.4, 4.5, 5.2, 6.3]; // seconds after recording start (intended instants) + let flashes = [], t0, on = 0; + const draw = (now) => { + const t = (now - t0) / 1000; let lit = false; + for (const h of hits) if (t >= h && t < h + 0.12) lit = true; + g.fillStyle = lit ? '#fff' : `rgb(${20 + (Math.random() * 3) | 0},20,20)`; g.fillRect(0, 0, 320, 180); + if (lit && !on) flashes.push(t); on = lit ? 1 : 0; + if (t < 8) requestAnimationFrame(draw); else rec.stop(); + }; + const done = new Promise(r => rec.onstop = r); + rec.start(100); + t0 = performance.now(); const a0 = ctx.currentTime; + for (const h of hits) { const o = ctx.createOscillator(), gn = ctx.createGain(); o.frequency.value = 880; gn.gain.setValueAtTime(0, a0 + h); gn.gain.linearRampToValueAtTime(0.5, a0 + h + 0.002); gn.gain.exponentialRampToValueAtTime(0.001, a0 + h + 0.15); o.connect(gn); gn.connect(dest); o.start(a0 + h); o.stop(a0 + h + 0.2); } + requestAnimationFrame(draw); + await done; + const blob = new Blob(chunks, { type: 'video/webm' }), buf = new Uint8Array(await blob.arrayBuffer()); + let s = ''; for (let i = 0; i < buf.length; i += 8192) s += String.fromCharCode(...buf.subarray(i, i + 8192)); + return { b64: btoa(s), hits, flashes, baseLatency: ctx.baseLatency, outputLatency: ctx.outputLatency }; + }); + fs.writeFileSync('clip.webm', Buffer.from(res.b64, 'base64')); + fs.writeFileSync('events.txt', res.hits.map((h, i) => `${h},hit${i}`).join('\n') + '\n'); + console.log(JSON.stringify({ hits: res.hits, flashes: res.flashes, base: res.baseLatency, out: res.outputLatency, bytes: fs.statSync('clip.webm').size })); + await browser.close(); +})(); diff --git a/tools/aqua-feel/sync-fixture.mjs b/tools/aqua-feel/sync-fixture.mjs index 73897bb..142f729 100644 --- a/tools/aqua-feel/sync-fixture.mjs +++ b/tools/aqua-feel/sync-fixture.mjs @@ -7,14 +7,15 @@ import { wavFloat32 } from "./render.js"; export const FIXTURE_EVENTS_S = [0.5, 1.3, 2.2, 3.4, 4.1, 5.0]; -export function makeFixture({ offsetMs = 80, fps = 60, sampleRate = 48000, seconds = 6, noise = 0.003, events = FIXTURE_EVENTS_S, seed = 7 } = {}) { +// bed: steady tones [[hz, amp], ...] under the hits; dc: constant offset; gain: hit amplitude. Events need not sit on frame boundaries. +export function makeFixture({ offsetMs = 80, fps = 60, sampleRate = 48000, seconds = 6, noise = 0.003, events = FIXTURE_EVENTS_S, seed = 7, bed = [], dc = 0, gain = 0.6 } = {}) { let s = seed >>> 0; const rand = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32 - 0.5; }; const audio = new Float32Array(Math.round(sampleRate * seconds)); - for (let i = 0; i < audio.length; i++) audio[i] = noise * 2 * rand(); + for (let i = 0; i < audio.length; i++) { audio[i] = dc + noise * 2 * rand(); for (const [hz, amp] of bed) audio[i] += amp * Math.sin((2 * Math.PI * hz * i) / sampleRate); } for (const e of events) { // 40 ms decaying 880 Hz burst with a 1 ms ramp: a hit with a sharp but not instantaneous attack const start = Math.round((e + offsetMs / 1000) * sampleRate); for (let j = 0; j < 0.04 * sampleRate && start + j < audio.length; j++) { - const t = j / sampleRate; audio[start + j] += 0.6 * Math.min(1, t / 0.001) * Math.exp(-t / 0.012) * Math.sin(2 * Math.PI * 880 * t); + const t = j / sampleRate; audio[start + j] += gain * Math.min(1, t / 0.001) * Math.exp(-t / 0.012) * Math.sin(2 * Math.PI * 880 * t); } } const n = Math.round(fps * seconds), t = new Float64Array(n), v = new Float64Array(n); diff --git a/tools/aqua-feel/sync.mjs b/tools/aqua-feel/sync.mjs index bf31ae6..4e61596 100644 --- a/tools/aqua-feel/sync.mjs +++ b/tools/aqua-feel/sync.mjs @@ -36,50 +36,73 @@ export function readWav(buf) { return { samples: out, sampleRate: fmt.sr, channels: fmt.ch }; } -// Frame-diff track: lines of "t,value" (seconds) or a single "value" column with fps given. A non-numeric first line is a header. +// Frame-diff track: lines of "t,value" (seconds, strictly increasing) or a single "value" column with fps given. Only the first line may be a header. +// Anything else that does not parse is an error: a silently dropped or shifted row would give a plausible wrong lag. export function readTrack(text, fps) { const t = [], v = []; - for (const line of text.split(/\r?\n/)) { - if (!line.trim()) continue; - const f = line.trim().split(/[\s,;]+/).filter(Boolean).map(Number); - if (f.some(Number.isNaN)) { if (t.length || v.length) throw new Error(`bad track line: ${line}`); continue; } - if (f.length >= 2) { t.push(f[0]); v.push(f[1]); } + text.split(/\r?\n/).forEach((raw, ln) => { + const line = raw.trim(); if (!line) return; + const tok = line.split(/[\s,;]+/), f = tok.map(Number); + if (tok.some((x) => x === "") || f.some((x) => !Number.isFinite(x))) { if (ln === 0 && !t.length && !v.length) return; throw new Error(`track line ${ln + 1} is not numeric: ${raw}`); } + if (f.length > 2) throw new Error(`track line ${ln + 1} has ${f.length} columns; expected "t,value" or one value per line: ${raw}`); + if (f.length === 2) { if (t.length && f[0] <= t[t.length - 1]) throw new Error(`track line ${ln + 1}: time ${f[0]} does not increase`); t.push(f[0]); v.push(f[1]); } else { if (!fps) throw new Error("single-column track needs --fps"); t.push(v.length / fps); v.push(f[0]); } - } + }); if (v.length < 3) throw new Error("track has fewer than 3 frames"); return { t: Float64Array.from(t), v: Float64Array.from(v) }; } -// Events: JSON array of numbers or {t,label}, or text lines "t[,label]" (seconds). +// Events: JSON array of numbers or {t,label}, or text lines "t[,label]" in seconds ('#' comments; the first line may be a header). Anything else is an error. export function readEvents(text) { - const s = text.trim(); + const s = text.trim(), fin = (x, where) => { if (!Number.isFinite(x)) throw new Error(`event ${where} has no numeric time`); return x; }; + let out; if (s.startsWith("[") || s.startsWith("{")) { const j = JSON.parse(s), a = Array.isArray(j) ? j : j.events; - return a.map((e, i) => (typeof e === "number" ? { t: e, label: `e${i}` } : { t: Number(e.t), label: e.label ?? `e${i}` })); + if (!Array.isArray(a)) throw new Error("events JSON must be an array or {events:[...]}"); + out = a.map((e, i) => (typeof e === "number" ? { t: fin(e, i), label: `e${i}` } : e && typeof e === "object" ? { t: fin(Number(e.t), i), label: String(e.label ?? `e${i}`) } : fin(NaN, i))); + } else { + out = []; + s.split(/\r?\n/).forEach((raw, ln) => { + const l = raw.trim(); if (!l || l.startsWith("#")) return; + const m = l.match(/^([^,\s]+)(?:[,\s]+(.*))?$/), t = Number(m[1]); + if (!Number.isFinite(t)) { if (ln === 0 && !out.length) return; throw new Error(`events line ${ln + 1} does not start with a time in seconds: ${raw}`); } + out.push({ t, label: m[2]?.trim() || `e${out.length}` }); + }); } - return s.split(/\r?\n/).map((l, i) => l.trim()).filter((l) => l && !l.startsWith("#") && !Number.isNaN(Number(l.split(/[,\s]+/)[0]))) - .map((l, i) => { const [t, ...r] = l.split(/[,\s]+/); return { t: Number(t), label: r.join(" ") || `e${i}` }; }); + if (!out.length) throw new Error("the events log has no events"); + return out; } // Video via ffmpeg: audio as mono f32 at 48 kHz, video as 64x36 gray frames; per-frame mean luminance and mean |frame diff| (motion flux). -// Stream start_time offsets are applied so both clocks are the container's clock. Constant frame rate is assumed (avg_frame_rate). -export function readVideo(path, { ffmpeg = "ffmpeg", ffprobe = "ffprobe" } = {}) { - let probe; - try { probe = JSON.parse(execFileSync(ffprobe, ["-v", "error", "-show_streams", "-of", "json", path], { encoding: "utf8" })); } - catch (e) { throw new Error(`ffprobe failed (${e.code === "ENOENT" ? "not on PATH; give --wav and --track instead" : e.message})`); } - const vs = probe.streams.find((s) => s.codec_type === "video"), as = probe.streams.find((s) => s.codec_type === "audio"); - if (!vs || !as) throw new Error("file needs one video and one audio stream"); - const [n, d] = vs.avg_frame_rate.split("/").map(Number), fps = n / d, W = 64, H = 36; +// Stream start_time offsets are applied so both clocks are the container's clock; video is resampled to constant frame rate by pts. +export function readVideo(path, { ffmpeg = process.env.FFMPEG ?? "ffmpeg", ffprobe = process.env.FFPROBE ?? "ffprobe", targetFps } = {}) { + // Stream facts from ffprobe when present, else from `ffmpeg -i` (static ffmpeg builds ship without ffprobe; -i prints them to stderr and exits 1). + let vs, as; + try { + const probe = JSON.parse(execFileSync(ffprobe, ["-v", "error", "-show_streams", "-of", "json", path], { encoding: "utf8" })); + const sv = probe.streams.find((x) => x.codec_type === "video"), sa = probe.streams.find((x) => x.codec_type === "audio"); + if (sv && sa) { const [n, d] = sv.avg_frame_rate.split("/").map(Number); vs = { index: sv.index, fps: n / d, start: Number(sv.start_time ?? 0) || 0 }; as = { index: sa.index, start: Number(sa.start_time ?? 0) || 0 }; } + } catch (e) { if (e.code !== "ENOENT") throw new Error(`ffprobe failed: ${e.message}`); } + if (!vs) { + let err = ""; try { execFileSync(ffmpeg, ["-hide_banner", "-i", path], { encoding: "utf8", stdio: ["ignore", "ignore", "pipe"] }); } catch (e) { if (e.code === "ENOENT") throw new Error("neither ffprobe nor ffmpeg is on PATH (set FFMPEG/FFPROBE); give --wav and --track instead"); err = String(e.stderr ?? ""); } + const line = (kind) => err.split("\n").find((l) => new RegExp(`Stream #\\d+:(\\d+).*: ${kind}:`).test(l)); + const vl = line("Video"), al = line("Audio"); + if (!vl || !al) throw new Error("file needs one video and one audio stream"); + const idx = (l) => Number(l.match(/Stream #\d+:(\d+)/)[1]), st = (l) => Number(l.match(/\bstart (\d+(?:\.\d+)?)/)?.[1] ?? 0); + const fpsm = vl.match(/(\d+(?:\.\d+)?) fps/) ?? vl.match(/(\d+(?:\.\d+)?) tbr/); + vs = { index: idx(vl), fps: Number(fpsm?.[1] ?? 30), start: st(vl) }; as = { index: idx(al), start: st(al) }; + } + // Resample to constant frame rate by presentation time (a variable-frame-rate source, e.g. a browser capture, repeats frames), so frame f is at start + f/fps. + const fps = targetFps ?? vs.fps, W = 64, H = 36; const audioRaw = execFileSync(ffmpeg, ["-v", "error", "-i", path, "-map", `0:${as.index}`, "-vn", "-ac", "1", "-ar", "48000", "-f", "f32le", "-"], { maxBuffer: 1 << 30 }); - const videoRaw = execFileSync(ffmpeg, ["-v", "error", "-i", path, "-map", `0:${vs.index}`, "-an", "-vf", `scale=${W}:${H}:flags=area,format=gray`, "-vsync", "passthrough", "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 }); + const videoRaw = execFileSync(ffmpeg, ["-v", "error", "-i", path, "-map", `0:${vs.index}`, "-an", "-vf", `fps=${fps},scale=${W}:${H}:flags=area,format=gray`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 }); const frames = Math.floor(videoRaw.length / (W * H)), t = new Float64Array(frames), lum = new Float64Array(frames), flux = new Float64Array(frames); - const vOff = Number(vs.start_time ?? 0) || 0, aOff = Number(as.start_time ?? 0) || 0; for (let f = 0; f < frames; f++) { let s = 0, df = 0; for (let i = 0; i < W * H; i++) { const p = videoRaw[f * W * H + i]; s += p; if (f) df += Math.abs(p - videoRaw[(f - 1) * W * H + i]); } - t[f] = vOff + f / fps; lum[f] = s / (W * H) / 255; flux[f] = f ? df / (W * H) / 255 : 0; + t[f] = vs.start + f / fps; lum[f] = s / (W * H) / 255; flux[f] = f ? df / (W * H) / 255 : 0; } - const a = new Float32Array(audioRaw.buffer, audioRaw.byteOffset, Math.floor(audioRaw.length / 4)); - return { audio: { samples: a, sampleRate: 48000, startS: aOff }, luma: { t, v: lum }, flux: { t, v: flux }, fps }; + const a = new Float32Array(audioRaw.buffer.slice(audioRaw.byteOffset, audioRaw.byteOffset + audioRaw.length - (audioRaw.length % 4))); + return { audio: { samples: a, sampleRate: 48000, startS: as.start }, luma: { t, v: lum }, flux: { t, v: flux }, fps }; } // ---------- onset detection ---------- @@ -119,12 +142,18 @@ export function audioOnsets(x, sr, { startS = 0, k = 8, minGapS = 0.05 } = {}) { } // The window centre sits half a window after the first audible sample's frame start; the rise-start pick lands within one window of the true onset. const r = pickOnsets(flux, tt, { k, floor: 1e-3 * hi, minGapS, riseFrac: 0.25 }); - // The flux frame is only good to a window; refine each onset on the samples: the first |x| within 20 dB (10%) of the local peak, searched - // from one window before the flux time to one window after it (the window centre can sit up to N/2 early of a click inside it). + // The flux frame is only good to a window; refine each onset on the samples. DC and the steady bed are estimated from the stretch before the + // search window (block peaks of |x - median|, their median, so a previous hit's tail in one block does not count); the onset is the first sample + // whose deviation exceeds max(10% of the local peak, 2.5x the bed). Search: from one window before the rise start (the window centre can sit up to + // N/2 early of a click inside it) to one window after the flux peak (over a loud bed the rise start can sit far before the real onset). If nothing clears the bar the flux time stands. for (const o of r.onsets) { - const c = Math.round((o.t - startS) * sr), a0 = Math.max(0, c - N), a1 = Math.min(x.length, c + N); - let pk = 0; for (let i = a0; i < a1; i++) pk = Math.max(pk, Math.abs(x[i])); - for (let i = a0; i < a1; i++) if (Math.abs(x[i]) >= 0.1 * pk) { o.t = startS + i / sr; break; } + const c = Math.round((o.t - startS) * sr), cp = Math.round((o.peakT - startS) * sr), a0 = Math.max(0, c - N), a1 = Math.min(x.length, cp + N), b0 = Math.max(0, a0 - 8 * 512), blocks = []; + const dc = median(Array.from(x.subarray(b0, a1))); + for (let q = b0; q + 512 <= a0; q += 512) { let m = 0; for (let i = q; i < q + 512; i++) m = Math.max(m, Math.abs(x[i] - dc)); blocks.push(m); } + const bed = blocks.length ? median(blocks) : 0; + let pk = 0; for (let i = a0; i < a1; i++) pk = Math.max(pk, Math.abs(x[i] - dc)); + const bar = Math.max(0.1 * pk, 2.5 * bed); + for (let i = a0; i < a1; i++) if (Math.abs(x[i] - dc) >= bar && bar < pk) { o.t = startS + i / sr; break; } } r.resolutionMs = (1000 * HOP) / sr; r.windowMs = (1000 * N) / sr; return r; @@ -142,67 +171,89 @@ export function visualOnsets(track, { kind = "luma", k = 8, minGapS = 0.1 } = {} } // ---------- pairing and verdict ---------- -export function syncAnalyze({ audio, sampleRate, audioStartS = 0, visual, visualKind = "luma", events, profile = "default", leadMs, lagMs, pairWindowMs = 300 }) { - const prof = { ...(PROFILES[profile] ?? (() => { throw new Error(`unknown profile ${profile}`); })()) }; +// One-to-one greedy matching of onsets to anchors (events, or audio onsets) by distance, within windowS. Returns Map anchorIndex -> onsetIndex. +function match(anchors, onsets, windowS) { + const edges = []; + anchors.forEach((a, i) => onsets.forEach((o, j) => { const d = Math.abs(o.t - a); if (d <= windowS) edges.push([d, i, j]); })); + edges.sort((x, y) => x[0] - y[0]); + const ai = new Map(), oj = new Set(); + for (const [, i, j] of edges) if (!ai.has(i) && !oj.has(j)) { ai.set(i, j); oj.add(j); } + return ai; +} +const within = (list, t, windowS) => list.filter((o) => Math.abs(o.t - t) <= windowS).length; + +// Frame quantisation: a visual change at time tau first shows in the frame stamped at or after tau, so visual - tau is in [0, framePeriod) and the +// measured lag (audio - visual) is biased LOW by up to a frame period. The truth therefore lies in [lag - audioHop/2, lag + framePeriod + audioHop/2]; +// a pair is judged on that interval, not on a point. +export function syncAnalyze({ audio, sampleRate, audioStartS = 0, visual, visualKind = "luma", events, profile = "default", leadMs, lagMs, pairWindowMs = 300, minGapMs, allowUnpaired = false }) { + if (!PROFILES[profile]) throw new Error(`unknown profile ${profile}`); + const prof = { ...PROFILES[profile] }, custom = leadMs !== undefined || lagMs !== undefined; if (leadMs !== undefined) prof.leadMs = leadMs; if (lagMs !== undefined) prof.lagMs = lagMs; - const a = audioOnsets(audio, sampleRate, { startS: audioStartS }), v = visualOnsets(visual, { kind: visualKind }); - const uncertaintyMs = Math.max(a.resolutionMs, v.framePeriodMs) / 2 + a.resolutionMs / 2; // half a frame period, plus half an audio hop - const used = new Set(), pairs = []; - const nearest = (list, t) => { let best = -1, bd = Infinity; list.forEach((o, i) => { const d = Math.abs(o.t - t); if (d < bd) { bd = d; best = i; } }); return best; }; + if (custom) { prof.note = `profile ${profile} with the window overridden on the command line`; } + for (const [n, x] of [["leadMs", prof.leadMs], ["lagMs", prof.lagMs], ["pairWindowMs", pairWindowMs]]) if (!Number.isFinite(x) || x <= 0) throw new Error(`${n} must be a positive number`); + const gap = minGapMs === undefined ? {} : { minGapS: minGapMs / 1000 }; + const a = audioOnsets(audio, sampleRate, { startS: audioStartS, ...gap }), v = visualOnsets(visual, { kind: visualKind, ...gap }); + const hopMs = a.resolutionMs, periodMs = v.framePeriodMs, win = pairWindowMs / 1000; const classify = (lag) => { - const excess = lag < 0 ? -lag - prof.leadMs : lag - prof.lagMs; // >0: outside the window by that many ms - if (excess > uncertaintyMs) return lag < 0 ? "audio-early-detectable" : "audio-late-detectable"; - if (excess > -uncertaintyMs) return "borderline"; // the window edge lies inside the measurement uncertainty - return "inside-window"; + const lo = lag - hopMs / 2, hi = lag + periodMs + hopMs / 2; // truth interval, ms + if (lo >= -prof.leadMs && hi <= prof.lagMs) return "inside-window"; + if (lo > prof.lagMs) return "audio-late-detectable"; + if (hi < -prof.leadMs) return "audio-early-detectable"; + return "borderline"; }; - if (events?.length) { - for (const e of events) { - const ai = nearest(a.onsets, e.t), vi = nearest(v.onsets, e.t), ao = a.onsets[ai], vo = v.onsets[vi]; - const okA = ao && Math.abs(ao.t - e.t) * 1e3 <= pairWindowMs, okV = vo && Math.abs(vo.t - e.t) * 1e3 <= pairWindowMs; - const row = { label: e.label, eventS: e.t, audioS: okA ? ao.t : null, visualS: okV ? vo.t : null, audioVsEventMs: okA ? (ao.t - e.t) * 1e3 : null, visualVsEventMs: okV ? (vo.t - e.t) * 1e3 : null }; - row.lagMs = okA && okV ? (ao.t - vo.t) * 1e3 : null; - row.verdict = row.lagMs === null ? (okA ? "no-visual-onset" : okV ? "no-audio-onset" : "no-onsets") : classify(row.lagMs); - if (okA) used.add(`a${ai}`); if (okV) used.add(`v${vi}`); - pairs.push(row); - } + const pairs = [], usedA = new Set(), usedV = new Set(); + const row = (label, eventS, ao, vo, ambiguous) => { + const r = { label, eventS, audioS: ao?.t ?? null, visualS: vo?.t ?? null, audioVsEventMs: ao && eventS !== null ? (ao.t - eventS) * 1e3 : null, visualVsEventMs: vo && eventS !== null ? (vo.t - eventS) * 1e3 : null, lagMs: ao && vo ? (ao.t - vo.t) * 1e3 : null }; + if (r.lagMs !== null) { r.lagLowMs = r.lagMs - hopMs / 2; r.lagHighMs = r.lagMs + periodMs + hopMs / 2; } + r.verdict = r.lagMs === null ? (ao ? "no-visual-onset" : vo ? "no-audio-onset" : "no-onsets") : ambiguous ? "ambiguous-pairing" : classify(r.lagMs); + return r; + }; + if (events) { + const et = events.map((e) => e.t), ma = match(et, a.onsets, win), mv = match(et, v.onsets, win); + events.forEach((e, i) => { + const ao = ma.has(i) ? a.onsets[ma.get(i)] : undefined, vo = mv.has(i) ? v.onsets[mv.get(i)] : undefined; + if (ao) usedA.add(ma.get(i)); if (vo) usedV.add(mv.get(i)); + // another onset of the same train inside the window: the nearest need not be the right one + pairs.push(row(e.label, e.t, ao, vo, within(a.onsets, e.t, win) > 1 || within(v.onsets, e.t, win) > 1)); + }); } else { - a.onsets.forEach((ao, ai) => { - const vi = nearest(v.onsets, ao.t), vo = v.onsets[vi]; - if (vo && Math.abs(vo.t - ao.t) * 1e3 <= pairWindowMs && !used.has(`v${vi}`)) { - used.add(`a${ai}`); used.add(`v${vi}`); - const lagMs = (ao.t - vo.t) * 1e3; - pairs.push({ label: `a${ai}`, eventS: null, audioS: ao.t, visualS: vo.t, audioVsEventMs: null, visualVsEventMs: null, lagMs, verdict: classify(lagMs) }); - } + const m = match(a.onsets.map((o) => o.t), v.onsets, win); + a.onsets.forEach((ao, i) => { + if (!m.has(i)) return; + const vo = v.onsets[m.get(i)]; usedA.add(i); usedV.add(m.get(i)); + pairs.push(row(`a${i}`, null, ao, vo, within(v.onsets, ao.t, win) > 1 || within(a.onsets, vo.t, win) > 1)); }); } const lags = pairs.map((p) => p.lagMs).filter((x) => x !== null); + const count = (f) => pairs.filter(f).length; const summary = { pairs: lags.length, audioOnsets: a.onsets.length, visualOnsets: v.onsets.length, - unpairedAudio: a.onsets.filter((_, i) => !used.has(`a${i}`)).length, unpairedVisual: v.onsets.filter((_, i) => !used.has(`v${i}`)).length, + unpairedAudio: a.onsets.length - usedA.size, unpairedVisual: v.onsets.length - usedV.size, medianLagMs: lags.length ? median(lags) : null, minLagMs: lags.length ? Math.min(...lags) : null, maxLagMs: lags.length ? Math.max(...lags) : null, // Spread of the lags: a constant offset is a latency (fixable by a delay), a wide spread is jitter (not fixable by one number). spreadMs: lags.length ? Math.max(...lags) - Math.min(...lags) : null, - outsideWindow: pairs.filter((p) => /detectable$/.test(p.verdict)).length, borderline: pairs.filter((p) => p.verdict === "borderline").length, - missing: pairs.filter((p) => p.lagMs === null).length, + outsideWindow: count((p) => /detectable$/.test(p.verdict)), borderline: count((p) => p.verdict === "borderline"), ambiguous: count((p) => p.verdict === "ambiguous-pairing"), + missing: count((p) => p.lagMs === null), }; - summary.pass = summary.pairs > 0 && summary.outsideWindow === 0 && summary.missing === 0; + const unpaired = summary.unpairedAudio + summary.unpairedVisual; + summary.pass = summary.pairs > 0 && summary.outsideWindow === 0 && summary.missing === 0 && summary.ambiguous === 0 && (allowUnpaired || unpaired === 0); return { - schema: "aqua-feel.sync.v1", lagConvention: "lagMs = audio onset - visual onset; positive = audio late, negative = audio early", - profile: { name: profile, ...prof }, uncertaintyMs, visualKind, audioResolutionMs: a.resolutionMs, framePeriodMs: v.framePeriodMs, + schema: "aqua-feel.sync.v1", lagConvention: "lagMs = audio onset - visual onset; positive = audio late, negative = audio early. Truth lies in [lagLowMs, lagHighMs] (visual onsets are quantised up to the next frame)", + profile: { name: custom ? `${profile}+override` : profile, ...prof }, allowUnpaired, pairWindowMs, visualKind, audioResolutionMs: hopMs, framePeriodMs: periodMs, audioOnsets: a.onsets, visualOnsets: v.onsets, pairs, summary, }; } export function formatSync(r) { const f = (x, d = 1) => (x === null || x === undefined ? " - " : x.toFixed(d).padStart(7)); - const L = [`profile ${r.profile.name}: audio may lead by ${r.profile.leadMs} ms, lag by ${r.profile.lagMs} ms (${r.profile.note ?? "custom"})`, - `lag = audio - visual (+ = audio late). measurement uncertainty about +/-${r.uncertaintyMs.toFixed(1)} ms (frame period ${r.framePeriodMs.toFixed(1)} ms, audio hop ${r.audioResolutionMs.toFixed(1)} ms)`, + const L = [`profile ${r.profile.name}: audio may lead by ${r.profile.leadMs} ms, lag by ${r.profile.lagMs} ms (${r.profile.note})`, + `lag = audio - visual (+ = audio late). The visual onset is quantised up to the next frame (period ${r.framePeriodMs.toFixed(1)} ms), so the true lag lies in [lag - ${(r.audioResolutionMs / 2).toFixed(1)}, lag + ${(r.framePeriodMs + r.audioResolutionMs / 2).toFixed(1)}] ms`, "", "label event s audio s visual s a-ev ms v-ev ms lag ms verdict"]; for (const p of r.pairs) L.push(`${String(p.label).padEnd(10).slice(0, 10)} ${f(p.eventS, 3)} ${f(p.audioS, 3)} ${f(p.visualS, 3)} ${f(p.audioVsEventMs)} ${f(p.visualVsEventMs)} ${f(p.lagMs)} ${p.verdict}`); - const s = r.summary; - L.push("", `${s.pairs} paired, ${s.unpairedAudio} audio and ${s.unpairedVisual} visual onsets unpaired; median lag ${s.medianLagMs === null ? "-" : s.medianLagMs.toFixed(1)} ms, range ${s.minLagMs === null ? "-" : `${s.minLagMs.toFixed(1)}..${s.maxLagMs.toFixed(1)}`} ms (spread ${s.spreadMs === null ? "-" : s.spreadMs.toFixed(1)} ms)`, - `${s.outsideWindow} outside the window, ${s.borderline} borderline, ${s.missing} without both onsets. ${s.pass ? "WITHIN WINDOW" : "NOT WITHIN WINDOW"} by this metric.`, + const s = r.summary, rng = s.minLagMs === null ? "-" : `${s.minLagMs.toFixed(1)}..${s.maxLagMs.toFixed(1)}`; + L.push("", `${s.pairs} paired, ${s.unpairedAudio} audio and ${s.unpairedVisual} visual onsets unpaired${r.allowUnpaired ? " (allowed)" : " (fails the check unless --allow-unpaired)"}; median lag ${s.medianLagMs === null ? "-" : s.medianLagMs.toFixed(1)} ms, range ${rng} ms (spread ${s.spreadMs === null ? "-" : s.spreadMs.toFixed(1)} ms)`, + `${s.outsideWindow} outside the window, ${s.borderline} borderline, ${s.ambiguous} ambiguous (another onset within ${r.pairWindowMs} ms), ${s.missing} without both onsets. ${s.pass ? (s.borderline ? `NOT DETECTABLY OUTSIDE THE WINDOW (${s.borderline} borderline: the interval straddles the edge)` : "WITHIN WINDOW") : "NOT WITHIN WINDOW"} by this metric.`, "A metric over two onset lists, not a verdict: a person still has to watch and listen (SYNC.md)."); return L.join("\n"); } diff --git a/tools/aqua-feel/sync.test.mjs b/tools/aqua-feel/sync.test.mjs index 3ac1fa3..01985bd 100644 --- a/tools/aqua-feel/sync.test.mjs +++ b/tools/aqua-feel/sync.test.mjs @@ -1,6 +1,7 @@ // Checks of `aqua-feel sync` on synthetic fixtures with known offsets. No real capture is used. Usage: node sync.test.mjs import assert from "node:assert/strict"; -import { syncAnalyze, readWav, readTrack, readEvents, audioOnsets, visualOnsets, PROFILES } from "./sync.mjs"; +import { formatSync, syncAnalyze, readWav, readTrack, readEvents, audioOnsets, visualOnsets, PROFILES } from "./sync.mjs"; +import { readFileSync } from "node:fs"; import { wavFloat32 } from "./render.js"; import { makeFixture, FIXTURE_EVENTS_S } from "./sync-fixture.mjs"; @@ -8,44 +9,52 @@ let n = 0; const t = (name, fn) => { fn(); n++; console.log(`ok ${name}`); }; const run = (o, extra = {}) => { const fx = makeFixture(o); return { fx, r: syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, events: fx.events, ...extra }) }; }; -for (const off of [-60, -20, 0, 40, 80, 150, 250]) { - t(`recovers a ${off} ms offset at 60 fps within the stated uncertainty, every event`, () => { - const { r } = run({ offsetMs: off }); - assert.equal(r.pairs.length, FIXTURE_EVENTS_S.length); - for (const p of r.pairs) assert.ok(Math.abs(p.lagMs - off) <= r.uncertaintyMs, `${p.label}: ${p.lagMs} vs ${off} (+/-${r.uncertaintyMs})`); - assert.equal(r.summary.unpairedVisual, 0, "no spurious visual onsets"); - assert.equal(r.summary.unpairedAudio, 0, "no spurious audio onsets"); +// The truth must lie in the interval each pair reports ([lagLowMs, lagHighMs]); the interval is the claim, a point estimate is not. +const inInterval = (p, truth) => p.lagLowMs - 1e-9 <= truth && truth <= p.lagHighMs + 1e-9; +const OFFGRID = [0.5042, 1.3117, 2.2209, 3.4033, 4.1161, 5.0087]; // events between frame boundaries at 30 and 60 fps + +for (const fps of [30, 60]) for (const off of [-60, -20, 0, 40, 80, 150, 250]) { + t(`${fps} fps, ${off} ms offset: the truth is inside every pair's interval, events on and off the frame grid`, () => { + for (const events of [FIXTURE_EVENTS_S, OFFGRID]) { + const { r } = run({ offsetMs: off, fps, events }); + assert.equal(r.pairs.length, events.length); + for (const p of r.pairs) assert.ok(inInterval(p, off), `${p.label}: [${p.lagLowMs}, ${p.lagHighMs}] vs ${off}`); + assert.equal(r.summary.unpairedVisual, 0, "no spurious visual onsets"); assert.equal(r.summary.unpairedAudio, 0, "no spurious audio onsets"); + } }); } -t("30 fps: the visual onset lands on a frame at or after the event, so the lag error stays under one frame period", () => { - for (const off of [0, 80]) { - const { r } = run({ offsetMs: off, fps: 30 }); - for (const p of r.pairs) assert.ok(Math.abs(p.lagMs - off) <= 1000 / 30, `${p.lagMs} vs ${off}`); - } +t("the interval is no wider than one frame period plus one audio hop (it is a measurement, not a shrug)", () => { + const { r } = run({ offsetMs: 80, fps: 60 }), p = r.pairs[0]; + assert.ok(p.lagHighMs - p.lagLowMs <= r.framePeriodMs + r.audioResolutionMs + 1e-9); }); -t("verdict classes follow the default window (lead 25, lag 100) beyond the uncertainty", () => { - const verdictOf = (off) => run({ offsetMs: off }).r.summary; - assert.equal(verdictOf(0).pass, true); - assert.equal(verdictOf(80).pass, true, "80 ms late is inside the 100 ms lag window"); - assert.equal(verdictOf(150).pass, false); - assert.equal(run({ offsetMs: 150 }).r.pairs[0].verdict, "audio-late-detectable"); - assert.equal(run({ offsetMs: -60 }).r.pairs[0].verdict, "audio-early-detectable"); - assert.equal(run({ offsetMs: 100 }).r.pairs[0].verdict, "borderline", "the window edge sits inside the uncertainty"); +t("verdict classes follow the default window (lead 25, lag 100) judged on the interval", () => { + const v = (off, o = {}) => run({ offsetMs: off, ...o }).r; + assert.equal(v(0).summary.pass, true); + assert.equal(v(60).summary.pass, true, "60 ms late is inside the 100 ms lag window"); + assert.equal(v(150).pairs[0].verdict, "audio-late-detectable"); + assert.equal(v(-60).pairs[0].verdict, "audio-early-detectable"); + assert.equal(v(95).pairs[0].verdict, "borderline", "the interval straddles the 100 ms edge"); + assert.equal(v(95).summary.pass, true, "borderline is not detectably outside, so it does not fail the gate"); + assert.match(formatSync(v(95)), /borderline/, "but the report says so"); + assert.match(formatSync(v(0)), /WITHIN WINDOW/); assert.doesNotMatch(formatSync(v(95)), /WITHIN WINDOW/); + assert.equal(v(85, { fps: 120 }).pairs[0].verdict, "inside-window", "a finer frame clock narrows the interval"); + assert.equal(v(85, { fps: 30 }).pairs[0].verdict, "borderline", "a coarser one widens it"); }); t("the profile changes the verdict, not the measurement", () => { const a = run({ offsetMs: 70 }, { profile: "default" }).r, b = run({ offsetMs: 70 }, { profile: "ebu-r37" }).r; assert.equal(a.pairs[0].lagMs, b.pairs[0].lagMs); assert.equal(a.summary.pass, true); assert.equal(b.summary.pass, false); + assert.match(run({ offsetMs: 70 }, { lagMs: 200 }).r.profile.note, /overridden/, "an overridden window is not reported as the default profile"); assert.ok(PROFILES.default.leadMs === 25 && PROFILES.default.lagMs === 100); }); t("without an events log, onsets pair by proximity and the offset is still recovered", () => { const fx = makeFixture({ offsetMs: 60 }), r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual }); assert.equal(r.pairs.length, FIXTURE_EVENTS_S.length); - for (const p of r.pairs) assert.ok(Math.abs(p.lagMs - 60) <= r.uncertaintyMs); + for (const p of r.pairs) assert.ok(inInterval(p, 60)); }); t("jitter shows as spread, not as a median: alternate events 0 and 90 ms late", () => { @@ -69,6 +78,69 @@ t("an offset past the 300 ms pairing window is reported as missing, not as a 300 assert.equal(r.pairs[0].verdict, "no-audio-onset"); assert.equal(r.summary.pass, false); }); +// ---- regressions from the Soul pass on PR #32 ---- +t("a noise bed, a steady-tone bed or a DC offset under the hits does not move the audio onset (refinement is relative to the bed)", () => { + for (const o of [{ noise: 0.03 }, { bed: [[220, 0.05], [330, 0.03]] }, { dc: 0.25 }, { gain: 0.03, noise: 0.003 }, { dc: -0.3, noise: 0.02 }]) { + const { r } = run({ offsetMs: 50, ...o }); + assert.equal(r.pairs.length, 6, JSON.stringify(o)); + for (const p of r.pairs) assert.ok(inInterval(p, 50), `${JSON.stringify(o)} ${p.label}: ${p.lagMs}`); + } +}); + +t("dense hits: events 120 ms apart with a +80 ms lag are not silently paired to the previous hit", () => { + const ev = [0.5, 0.62, 0.74, 0.86, 0.98, 1.1, 1.22]; + const { r } = run({ offsetMs: 80, events: ev }); + // Either the pairing is right, or it is flagged; it is never a confident wrong lag with a pass. + for (const p of r.pairs) assert.ok(inInterval(p, 80) || p.verdict === "ambiguous-pairing" || p.lagMs === null, `${p.label}: ${p.lagMs} ${p.verdict}`); + assert.equal(r.summary.pass, false, "overlapping candidates inside the pairing window cannot pass"); + assert.ok(r.summary.ambiguous > 0); +}); + +t("an audio onset is never reused by two events", () => { + const { r } = run({ offsetMs: 200, events: [0.5, 0.58, 0.66, 0.74] }); + const used = r.pairs.map((p) => p.audioS).filter((x) => x !== null); + assert.equal(new Set(used).size, used.length); +}); + +t("a narrower --pair-window-ms resolves dense hits that the default calls ambiguous", () => { + const ev = [0.5, 0.62, 0.74, 0.86, 0.98]; + const { r } = run({ offsetMs: 30, events: ev }, { pairWindowMs: 50 }); + for (const p of r.pairs) assert.ok(inInterval(p, 30), `${p.label}: ${p.lagMs}`); + assert.equal(r.summary.ambiguous, 0); +}); + +t("flashes closer than the visual minimum gap merge, and then an event goes unpaired rather than getting another flash's lag", () => { + const { r } = run({ offsetMs: 0, events: [0.5, 0.56, 0.62, 1.5] }); + assert.equal(r.summary.pass, false); + for (const p of r.pairs) assert.ok(p.lagMs === null || inInterval(p, 0) || p.verdict === "ambiguous-pairing", `${p.label}: ${p.lagMs} ${p.verdict}`); +}); + +t("a stray sound or flash fails the check unless --allow-unpaired is given", () => { + const fx = makeFixture({ offsetMs: 0 }), a = Float32Array.from(fx.audio), click = makeFixture({ offsetMs: 0, events: [0.1] }).audio; + for (let i = 4000; i < 7000; i++) a[i] += click[i]; + const run2 = (o) => syncAnalyze({ audio: a, sampleRate: 48000, visual: fx.visual, events: fx.events, ...o }); + assert.equal(run2({}).summary.unpairedAudio, 1); assert.equal(run2({}).summary.pass, false); + assert.equal(run2({ allowUnpaired: true }).summary.pass, true); +}); + +t("bad options fail loudly: NaN window, unknown profile", () => { + const fx = makeFixture({}); + assert.throws(() => syncAnalyze({ audio: fx.audio, sampleRate: 48000, visual: fx.visual, lagMs: NaN }), /positive/); + assert.throws(() => syncAnalyze({ audio: fx.audio, sampleRate: 48000, visual: fx.visual, profile: "nope" }), /unknown profile/); +}); + +t("parsers refuse input that would give a plausible wrong answer", () => { + assert.throws(() => readEvents("0:00.5\n0:01.2\n"), /does not start with a time/); + assert.throws(() => readEvents("time,label\nfoo,bar\n"), /line 2/); + assert.deepEqual(readEvents("time,label\n0.5,a\n1.5,b, loud\n").map((e) => e.label), ["a", "b, loud"], "a header on line 1 is skipped; commas stay in the label"); + assert.throws(() => readEvents("[0.5, null]"), /no numeric time/); + assert.throws(() => readEvents('[{"time":2}]'), /no numeric time/); + assert.throws(() => readEvents("# only a comment\n"), /no events/); + assert.throws(() => readTrack("0,0,0.1\n1,0.1,0.2\n2,0.2,0.3\n"), /3 columns/); + assert.throws(() => readTrack("0.0,0.1\n0.0167,\n0.0333,0.3\n"), /not numeric/); + assert.throws(() => readTrack("0,0.1\n0.5,0.2\n0.4,0.3\n"), /does not increase/); +}); + t("silence and a flat track yield no onsets and no pass", () => { const r = syncAnalyze({ audio: new Float32Array(48000 * 2), sampleRate: 48000, visual: { t: Float64Array.from({ length: 120 }, (_, i) => i / 60), v: new Float64Array(120).fill(0.5) } }); assert.equal(r.summary.audioOnsets, 0); assert.equal(r.summary.visualOnsets, 0); assert.equal(r.summary.pass, false); @@ -105,4 +177,21 @@ t("readTrack takes header + t,value rows or a single column with fps; readEvents assert.deepEqual(readEvents('[{"t":2,"label":"x"},3]').map((e) => e.label), ["x", "e1"]); }); -console.log(`${n} sync checks passed. Synthetic fixtures only; nothing was heard or seen.`); +// The video path needs ffmpeg (FFMPEG=/path or on PATH); skipped, and said so, when there is none. +{ + const { readVideo } = await import("./sync.mjs"), { execFileSync } = await import("node:child_process"); + const ff = process.env.FFMPEG ?? "ffmpeg"; + let have = true; try { execFileSync(ff, ["-version"], { stdio: "ignore" }); } catch { have = false; } + if (!have) console.log("skip video path: no ffmpeg (set FFMPEG)"); + else t("a real browser capture (VFR vp8+opus webm): every logged hit pairs, and the lag is a constant (spread under one frame)", () => { + const v = readVideo(new URL("./fixtures/browser-capture.webm", import.meta.url).pathname, { ffmpeg: ff }); + const ev = readEvents(readFileSync(new URL("./fixtures/browser-capture.events.txt", import.meta.url), "utf8")); + const r = syncAnalyze({ audio: v.audio.samples, sampleRate: v.audio.sampleRate, audioStartS: v.audio.startS, visual: v.luma, events: ev }); + assert.equal(r.pairs.length, 7); assert.equal(r.summary.missing, 0); + assert.ok(r.summary.spreadMs < 1000 / v.fps, `spread ${r.summary.spreadMs}`); + assert.equal(r.summary.unpairedAudio + r.summary.unpairedVisual, 0); + for (const p of r.pairs) assert.ok(p.visualVsEventMs >= 0 && p.visualVsEventMs <= 1000 / v.fps, `flash ${p.visualVsEventMs} ms off its logged instant`); + }); +} + +console.log(`${n} sync checks passed. Fixtures only (synthetic, plus one browser capture when ffmpeg is present); nothing was heard or seen.`);