aqua-feel sync: audio-visual onset lag against perceptual windows
Zero-dependency check: audio spectral-flux onsets and visual luma/flux onsets, paired per logged event, lag in ms, verdict against default/BT.1359-1/EBU R37/ATSC IS-191 windows. Synthetic known-offset fixture and 19 checks. SYNC.md says what the metric cannot tell. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3d9a245717
commit
7e3c1fb5ff
7 changed files with 466 additions and 1 deletions
|
|
@ -9,6 +9,8 @@ The WAVs and the gallery exist so a person can press play.
|
|||
|
||||
To look at a finished audio file (wav/ogg/flac: spectrogram, onsets at 1 ms, level envelope, click/clip/double-hit/overlap/abrupt-end detectors, two-file compare) rather than a rendered patch, use `../aqua-ear`.
|
||||
|
||||
To check that sound and picture of a capture line up (video or WAV plus a frame-diff track), use `node feel.mjs sync`: see `SYNC.md`.
|
||||
|
||||
## Run
|
||||
|
||||
```
|
||||
|
|
|
|||
88
tools/aqua-feel/SYNC.md
Normal file
88
tools/aqua-feel/SYNC.md
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
# aqua-feel sync
|
||||
|
||||
Checks audio-visual synchrony of a capture: finds audio onsets and visual onsets, pairs them, reports the lag per event in ms and
|
||||
compares it with published detectability windows. Standalone: Node 18+, no npm dependencies (`feel.mjs` imports `sync.mjs`, which
|
||||
imports one FFT from `metrics.js`). ffmpeg and ffprobe are needed only to read a video file directly.
|
||||
|
||||
**The metric is not the verdict.** It compares two onset lists extracted from signals. A human ear and eye still decide whether a
|
||||
capture feels in sync. Nothing here heard or saw anything.
|
||||
|
||||
## Run
|
||||
|
||||
```
|
||||
# WAV + a per-frame track (no ffmpeg needed)
|
||||
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
|
||||
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.
|
||||
|
||||
**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
|
||||
(`--kind flux`, motion flux: a start of movement is a rise). `hits.txt`: seconds, optionally `,label` per line (`#` comments), or JSON
|
||||
`[0.5, {"t":1.3,"label":"hit"}]`. With a video, luminance and flux are computed on a 64x36 gray downscale; stream `start_time`
|
||||
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).
|
||||
|
||||
## 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.
|
||||
- **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.
|
||||
|
||||
## Verdict
|
||||
|
||||
Per pair, against a window of how far audio may lead (`lead`) or trail (`lag`) the picture before the offset is detectable:
|
||||
|
||||
| profile | lead ms | lag ms | source |
|
||||
|---|---|---|---|
|
||||
| `default` | 25 | 100 | the conservative range this tool was asked for; it is not one standard: it sits between the ATSC and ITU figures. Treat as a tripwire |
|
||||
| `bt1359` | 45 | 125 | ITU-R BT.1359-1 (1998), "Relative timing of sound and vision for broadcasting": detectability threshold +45 / -125 ms (acceptability +90 / -185) |
|
||||
| `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.
|
||||
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
|
||||
[ATSC recommends AV sync rules](https://tvtechnology.com/opinions/atsc-recommends-av-sync-rules). Windows depend on content (speech
|
||||
lip-sync is more sensitive than a game impact) and on the viewer; they are population thresholds, not a property of your capture.
|
||||
|
||||
## 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.
|
||||
|
||||
## What the metric cannot tell you
|
||||
|
||||
- **Whether it feels right.** Two onsets agreeing says the energy rose at the same time, not that the sound belongs to the picture.
|
||||
A person must watch and listen.
|
||||
- **That the pairing is the right pairing.** Onsets are matched by nearness. A sound that belongs to an earlier or later visual
|
||||
event can be paired with the wrong one; with an event log, the log is trusted, with none, nothing checks the pairing but you.
|
||||
- **Which onset the viewer attends to.** A swell, a reverb tail, a ramped attack or a low-frequency thump has a perceptual onset
|
||||
later than the first sample above the threshold; a flash with a fade reads late the same way. A decaying visual (afterimage, a bloom
|
||||
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.
|
||||
- **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.
|
||||
|
|
@ -5,6 +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 correlate TRIAL_EXPORT.json ... feel metrics vs listening-trial ratings
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
|
|
@ -53,7 +54,27 @@ async function run() {
|
|||
process.exit(!noGate && !report.gate.pass ? 1 : 0);
|
||||
}
|
||||
|
||||
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;
|
||||
try {
|
||||
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) });
|
||||
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));
|
||||
process.exit(!noGate && !r.summary.pass ? 1 : 0);
|
||||
} catch (e) { console.error(`sync: ${e.message}`); process.exit(2); }
|
||||
}
|
||||
|
||||
const cmds = {
|
||||
sync,
|
||||
run,
|
||||
gate() {
|
||||
const partial = bool("--partial"), report = readJson(args[0]), g = gate(report, readJson(args[1] ?? join(here, "thresholds.json")), { partial });
|
||||
|
|
|
|||
|
|
@ -3,5 +3,5 @@
|
|||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Headless feel meter for AquaSynth: renders every shipped patch and Ding offline and measures them. Measures; does not listen.",
|
||||
"scripts": { "test": "node test.mjs", "feel": "node feel.mjs", "shelf": "node shelf.mjs build", "shelf:check": "node shelf.mjs check" }
|
||||
"scripts": { "test": "node test.mjs && node sync.test.mjs", "feel": "node feel.mjs", "shelf": "node shelf.mjs build", "shelf:check": "node shelf.mjs check" }
|
||||
}
|
||||
|
|
|
|||
38
tools/aqua-feel/sync-fixture.mjs
Normal file
38
tools/aqua-feel/sync-fixture.mjs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Synthetic A/V fixture with a known offset: event times, a mono WAV of tone-burst "hits", and a per-frame luminance track of flashes.
|
||||
// The audio is the visual delayed by offsetMs (positive = audio late), so syncAnalyze must recover lag = offsetMs. Nothing here is a real capture.
|
||||
// CLI: node sync-fixture.mjs OUTDIR [offsetMs=80] [fps=60] writes OUTDIR/{fixture.wav,track.csv,events.txt,truth.json}
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
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 } = {}) {
|
||||
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 (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 n = Math.round(fps * seconds), t = new Float64Array(n), v = new Float64Array(n);
|
||||
for (let f = 0; f < n; f++) { // frame f is on screen from f/fps; a flash is bright for 4 frames starting at the first frame at or after the event
|
||||
t[f] = f / fps; v[f] = 0.1 + 0.01 * 2 * rand();
|
||||
for (const e of events) { const f0 = Math.ceil(e * fps - 1e-9); if (f >= f0 && f < f0 + 4) v[f] = 0.9; }
|
||||
}
|
||||
return { audio, sampleRate, visual: { t, v }, events: events.map((e, i) => ({ t: e, label: `hit${i}` })), offsetMs, fps };
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
const [dir, off = "80", fps = "60"] = process.argv.slice(2);
|
||||
if (!dir) { console.error("usage: node sync-fixture.mjs OUTDIR [offsetMs=80] [fps=60]"); process.exit(2); }
|
||||
const fx = makeFixture({ offsetMs: Number(off), fps: Number(fps) }); mkdirSync(dir, { recursive: true });
|
||||
const wav = wavFloat32(fx.audio); wav.writeUInt32LE(fx.sampleRate, 24); wav.writeUInt32LE(fx.sampleRate * 4, 28); // wavFloat32 writes 48 kHz; same rate here
|
||||
writeFileSync(join(dir, "fixture.wav"), wav);
|
||||
writeFileSync(join(dir, "track.csv"), "t,luma\n" + Array.from(fx.visual.t, (x, i) => `${x.toFixed(6)},${fx.visual.v[i].toFixed(5)}`).join("\n") + "\n");
|
||||
writeFileSync(join(dir, "events.txt"), fx.events.map((e) => `${e.t},${e.label}`).join("\n") + "\n");
|
||||
writeFileSync(join(dir, "truth.json"), JSON.stringify({ offsetMs: fx.offsetMs, fps: fx.fps, note: "audio = visual delayed by offsetMs; synthetic" }, null, 1));
|
||||
console.log(`wrote fixture to ${dir} (audio ${fx.offsetMs} ms late)`);
|
||||
}
|
||||
208
tools/aqua-feel/sync.mjs
Normal file
208
tools/aqua-feel/sync.mjs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
// aqua-feel sync: audio-visual synchrony check. Zero npm dependencies (node >= 18); ffmpeg/ffprobe only if you hand it a video.
|
||||
// NOTHING HERE HEARS OR SEES ANYTHING. It compares two onset lists extracted from signals; see SYNC.md for what that cannot tell you.
|
||||
// Library: syncAnalyze({ audio, sampleRate, visual:{t,v}, events, profile }) -> report. CLI wiring is in feel.mjs (`node feel.mjs sync ...`).
|
||||
import { readFileSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fft } from "./metrics.js";
|
||||
|
||||
// Lag convention: lag = audio onset time - visual onset time. Positive = audio LATE (after the picture); negative = audio EARLY.
|
||||
// Windows are [leadMs, lagMs]: audio may lead the picture by up to leadMs and trail it by up to lagMs before the offset is "detectable".
|
||||
// Sources: see SYNC.md. 'default' is the requested conservative profile; the rest are the published ones, secondary-source figures noted there.
|
||||
export const PROFILES = {
|
||||
default: { leadMs: 25, lagMs: 100, note: "conservative; between ATSC IS-191 and ITU-R BT.1359-1" },
|
||||
"bt1359": { leadMs: 45, lagMs: 125, note: "ITU-R BT.1359-1 (1998) detectability threshold" },
|
||||
"ebu-r37": { leadMs: 40, lagMs: 60, note: "EBU R37 (2007) emission limit, per secondary source" },
|
||||
"atsc-is191": { leadMs: 15, lagMs: 45, note: "ATSC IS-191 limit at the encoder input, per secondary source" },
|
||||
};
|
||||
|
||||
// ---------- input readers ----------
|
||||
export function readWav(buf) {
|
||||
if (buf.toString("latin1", 0, 4) !== "RIFF" || buf.toString("latin1", 8, 12) !== "WAVE") throw new Error("not a RIFF/WAVE file");
|
||||
let fmt, data;
|
||||
for (let p = 12; p + 8 <= buf.length;) {
|
||||
const id = buf.toString("latin1", p, p + 4), sz = buf.readUInt32LE(p + 4), body = p + 8;
|
||||
if (id === "fmt ") fmt = { tag: buf.readUInt16LE(body), ch: buf.readUInt16LE(body + 2), sr: buf.readUInt32LE(body + 4), bits: buf.readUInt16LE(body + 14) };
|
||||
if (id === "data") { data = buf.subarray(body, Math.min(buf.length, body + sz)); break; }
|
||||
p = body + sz + (sz & 1);
|
||||
}
|
||||
if (!fmt || !data) throw new Error("WAV has no fmt or data chunk");
|
||||
if (fmt.tag === 0xfffe) fmt.tag = buf.readUInt16LE(buf.indexOf("fmt ") + 8 + 24); // WAVE_FORMAT_EXTENSIBLE: sub-format tag
|
||||
const bps = fmt.bits / 8, frames = Math.floor(data.length / (bps * fmt.ch)), out = new Float32Array(frames);
|
||||
const get = fmt.tag === 3 && fmt.bits === 32 ? (o) => data.readFloatLE(o) : fmt.tag === 3 && fmt.bits === 64 ? (o) => data.readDoubleLE(o)
|
||||
: fmt.tag === 1 && fmt.bits === 16 ? (o) => data.readInt16LE(o) / 32768 : fmt.tag === 1 && fmt.bits === 24 ? (o) => data.readIntLE(o, 3) / 8388608
|
||||
: fmt.tag === 1 && fmt.bits === 32 ? (o) => data.readInt32LE(o) / 2147483648 : null;
|
||||
if (!get) throw new Error(`unsupported WAV format tag ${fmt.tag} / ${fmt.bits} bit`);
|
||||
for (let i = 0; i < frames; i++) { let s = 0; for (let c = 0; c < fmt.ch; c++) s += get((i * fmt.ch + c) * bps); out[i] = s / fmt.ch; } // mono mix
|
||||
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.
|
||||
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]); }
|
||||
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).
|
||||
export function readEvents(text) {
|
||||
const s = text.trim();
|
||||
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}` }));
|
||||
}
|
||||
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}` }; });
|
||||
}
|
||||
|
||||
// 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;
|
||||
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 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;
|
||||
}
|
||||
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 };
|
||||
}
|
||||
|
||||
// ---------- onset detection ----------
|
||||
const median = (a) => { const s = Float64Array.from(a).sort(); const n = s.length; return n ? (n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2) : 0; };
|
||||
|
||||
// Pick onsets from a nonnegative novelty curve nov[i] at times tt[i]. A peak is a local maximum above max(floor, med + k*1.4826*MAD) and
|
||||
// at least minGapS from the previous kept peak (the larger wins). The onset is the first sample of the rise that reaches riseFrac of the peak.
|
||||
function pickOnsets(nov, tt, { k, floor, minGapS, riseFrac }) {
|
||||
const med = median(nov), mad = median(nov.map((x) => Math.abs(x - med))), thr = Math.max(floor, med + k * 1.4826 * mad);
|
||||
const peaks = [];
|
||||
for (let i = 0; i < nov.length; i++) {
|
||||
if (nov[i] < thr || (i && nov[i] < nov[i - 1]) || (i + 1 < nov.length && nov[i] <= nov[i + 1])) continue;
|
||||
const last = peaks[peaks.length - 1];
|
||||
if (last && tt[i] - tt[last] < minGapS) { if (nov[i] > nov[last]) peaks[peaks.length - 1] = i; continue; }
|
||||
peaks.push(i);
|
||||
}
|
||||
return {
|
||||
threshold: thr,
|
||||
onsets: peaks.map((p) => {
|
||||
let i = p; while (i > 0 && nov[i - 1] >= riseFrac * nov[p] && tt[p] - tt[i - 1] < 0.1) i--;
|
||||
return { t: tt[i], peakT: tt[p], strength: nov[p] };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// Audio: log-magnitude spectral flux, 1024 window / 128 hop (2.7 ms at 48 kHz), half-wave rectified, summed over 60 Hz..Nyquist.
|
||||
export function audioOnsets(x, sr, { startS = 0, k = 8, minGapS = 0.05 } = {}) {
|
||||
const N = 1024, HOP = 128, win = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));
|
||||
const lo = Math.ceil((60 * N) / sr), hi = N / 2, frames = Math.max(0, Math.floor((x.length - N) / HOP) + 1);
|
||||
const flux = new Float64Array(frames), tt = new Float64Array(frames), prev = new Float64Array(hi + 1), re = new Float64Array(N), im = new Float64Array(N);
|
||||
for (let f = 0; f < frames; f++) {
|
||||
for (let i = 0; i < N; i++) { re[i] = x[f * HOP + i] * win[i]; im[i] = 0; }
|
||||
fft(re, im);
|
||||
let s = 0;
|
||||
for (let b = lo; b <= hi; b++) { const m = Math.log1p(1e3 * Math.hypot(re[b], im[b]) / N); if (f) s += Math.max(0, m - prev[b]); prev[b] = m; }
|
||||
flux[f] = s; tt[f] = startS + (f * HOP + N / 2) / sr; // a frame is stamped at its centre
|
||||
}
|
||||
// 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).
|
||||
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; }
|
||||
}
|
||||
r.resolutionMs = (1000 * HOP) / sr; r.windowMs = (1000 * N) / sr;
|
||||
return r;
|
||||
}
|
||||
|
||||
// Visual: onset = frame where the track rises. Luminance uses the positive frame-to-frame step; motion flux is already a change measure.
|
||||
export function visualOnsets(track, { kind = "luma", k = 8, minGapS = 0.1 } = {}) {
|
||||
const { t, v } = track, nov = new Float64Array(v.length);
|
||||
for (let i = 1; i < v.length; i++) nov[i] = kind === "luma" ? Math.max(0, v[i] - v[i - 1]) : Math.max(0, v[i]);
|
||||
const range = Math.max(...v) - Math.min(...v);
|
||||
const r = pickOnsets(nov, t, { k, floor: 0.1 * range + 1e-12, minGapS, riseFrac: 0.5 });
|
||||
const dts = []; for (let i = 1; i < t.length; i++) dts.push(t[i] - t[i - 1]);
|
||||
r.framePeriodMs = 1000 * median(dts);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---------- 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}`); })()) };
|
||||
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; };
|
||||
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";
|
||||
};
|
||||
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);
|
||||
}
|
||||
} 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 lags = pairs.map((p) => p.lagMs).filter((x) => x !== null);
|
||||
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,
|
||||
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,
|
||||
};
|
||||
summary.pass = summary.pairs > 0 && summary.outsideWindow === 0 && summary.missing === 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,
|
||||
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)`,
|
||||
"", "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.`,
|
||||
"A metric over two onset lists, not a verdict: a person still has to watch and listen (SYNC.md).");
|
||||
return L.join("\n");
|
||||
}
|
||||
108
tools/aqua-feel/sync.test.mjs
Normal file
108
tools/aqua-feel/sync.test.mjs
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// 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 { wavFloat32 } from "./render.js";
|
||||
import { makeFixture, FIXTURE_EVENTS_S } from "./sync-fixture.mjs";
|
||||
|
||||
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");
|
||||
});
|
||||
}
|
||||
|
||||
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("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("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.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);
|
||||
});
|
||||
|
||||
t("jitter shows as spread, not as a median: alternate events 0 and 90 ms late", () => {
|
||||
const fx = makeFixture({ offsetMs: 0 }), clean = makeFixture({ offsetMs: 90 }), a = Float32Array.from(fx.audio);
|
||||
const s0 = Math.round(FIXTURE_EVENTS_S[1] * 48000) - 100, s1 = Math.round(FIXTURE_EVENTS_S[1] * 48000) + 4800;
|
||||
for (let i = s0; i < s1; i++) a[i] = clean.audio[i]; // event 1 comes from the 90 ms-late render
|
||||
const r = syncAnalyze({ audio: a, sampleRate: 48000, visual: fx.visual, events: fx.events });
|
||||
assert.ok(r.summary.spreadMs > 80 && r.summary.spreadMs < 100, `spread ${r.summary.spreadMs}`);
|
||||
});
|
||||
|
||||
t("an event with no sound is reported, not paired to a neighbour", () => {
|
||||
const fx = makeFixture({ offsetMs: 0 }), a = Float32Array.from(fx.audio);
|
||||
for (let i = Math.round(2.0 * 48000); i < Math.round(2.6 * 48000); i++) a[i] = 0; // silence the 2.2 s hit
|
||||
const r = syncAnalyze({ audio: a, sampleRate: 48000, visual: fx.visual, events: fx.events });
|
||||
const p = r.pairs.find((x) => x.eventS === 2.2);
|
||||
assert.equal(p.verdict, "no-audio-onset"); assert.equal(p.lagMs, null); assert.equal(r.summary.pass, false);
|
||||
});
|
||||
|
||||
t("an offset past the 300 ms pairing window is reported as missing, not as a 300+ ms lag", () => {
|
||||
const { r } = run({ offsetMs: 400 });
|
||||
assert.equal(r.pairs[0].verdict, "no-audio-onset"); assert.equal(r.summary.pass, false);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
t("a sine-bed with a swell rather than a click still gives one audio onset near its start", () => {
|
||||
const sr = 48000, x = new Float32Array(sr * 3);
|
||||
for (let i = Math.round(1 * sr); i < x.length; i++) { const tt = (i - sr) / sr; x[i] = 0.5 * Math.min(1, tt / 0.01) * Math.sin(2 * Math.PI * 440 * tt); }
|
||||
const o = audioOnsets(x, sr).onsets;
|
||||
assert.equal(o.length, 1); assert.ok(Math.abs(o[0].t - 1.0) < 0.012, `${o[0].t}`);
|
||||
});
|
||||
|
||||
t("motion-flux track: a step in flux is an onset at its frame", () => {
|
||||
const tt = Float64Array.from({ length: 90 }, (_, i) => i / 30), v = new Float64Array(90); v[30] = 0.4; v[31] = 0.3;
|
||||
const o = visualOnsets({ t: tt, v }, { kind: "flux" }).onsets;
|
||||
assert.equal(o.length, 1); assert.ok(Math.abs(o[0].t - 1.0) < 1e-9);
|
||||
});
|
||||
|
||||
t("readWav reads 16-bit PCM and 32-bit float, mixes stereo to mono, and rejects non-WAV", () => {
|
||||
const f = wavFloat32(Float32Array.from([0, 0.5, -0.5])), w = readWav(f);
|
||||
assert.equal(w.sampleRate, 48000); assert.deepEqual(Array.from(w.samples), [0, 0.5, -0.5]);
|
||||
const b = Buffer.alloc(44 + 8); b.write("RIFF", 0); b.writeUInt32LE(44, 4); b.write("WAVEfmt ", 8); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(2, 22);
|
||||
b.writeUInt32LE(44100, 24); b.writeUInt32LE(176400, 28); b.writeUInt16LE(4, 32); b.writeUInt16LE(16, 34); b.write("data", 36); b.writeUInt32LE(8, 40);
|
||||
b.writeInt16LE(16384, 44); b.writeInt16LE(-16384, 46); b.writeInt16LE(8192, 48); b.writeInt16LE(8192, 50);
|
||||
const s = readWav(b); assert.equal(s.sampleRate, 44100); assert.deepEqual(Array.from(s.samples), [0, 0.25]);
|
||||
assert.throws(() => readWav(Buffer.from("not a wav file at all")));
|
||||
});
|
||||
|
||||
t("readTrack takes header + t,value rows or a single column with fps; readEvents takes lines or JSON", () => {
|
||||
const a = readTrack("t,luma\n0,0.1\n0.1,0.2\n0.2,0.3\n"); assert.deepEqual(Array.from(a.t), [0, 0.1, 0.2]);
|
||||
const b = readTrack("0.1\n0.2\n0.3\n", 10); assert.ok(Math.abs(b.t[2] - 0.2) < 1e-12);
|
||||
assert.throws(() => readTrack("0.1\n0.2\n0.3\n"), /fps/);
|
||||
assert.deepEqual(readEvents("# hits\n0.5,kick\n1.25\n").map((e) => e.t), [0.5, 1.25]);
|
||||
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.`);
|
||||
Loading…
Reference in a new issue