Archilyzer · Source

archilyzer

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

commit 17bb576466b199032cd5a50f168dd2bc39921c30
parent 833bfa33179f08466a8a57c7168f63758aae5ce7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 20:53:59 -0500

common: one clock per recording -- the time map (clock.json) from the transcription source to the saved video

A recording's cues are timed on the file that was transcribed (a Rumble
channel's audio.mp3) and its windows are cut from another (the saved whole
video): two downloads of one live stream, two clocks. rev9-a3 measured c43
+13.1 s, c45 +13.6 s, c20 +5.2 s -- and v7eqa6e had c44 at 0 s and c45 at
+13.6 s, a step inside one stream.

lib/recordingClock.mjs (pure, plain JS for umtool): the FFT cross-correlation
of a source probe against a target search excerpt, the anchors (every 300 s
plus the cited spans), the piecewise-linear fit (segments, outliers, the gaps
a step lies in, widened by half a probe), the refinement times, the lookups
(clockOffsetAt, mapSpan -- certain only on one segment of an ok map) and the
file's shape. lib/recordingClock-server.ts measures it: the source decoded
from its first sample (an mp3 cannot be seeked to the sample), the mp4 target
seeked with a 3 s pre-roll (an input seek alone lands an AAC excerpt 10-55 ms
off), refined inside every step, written as the declared sidecar clock.json
(ok or not, with its residual and why). lib/recordingClock-read.mjs is the
plain-JS read and clockForContainer (stale when the container changed).

Tests: a synthetic 6 Nov shape (+2.5 s, then +13.1 s after a 10.6 s splice)
recovered to the sample from an mp3 against an AAC mp4; drift; outliers; an
unmatched stream not ok; the step's gap; the sidecar list (eighteen).

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

Diffstat:
Acommon/lib/recordingClock-read.mjs | 44++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/recordingClock-server.test.ts | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/recordingClock-server.ts | 340+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/recordingClock.mjs | 539+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/recordingClock.test.ts | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/sidecar-server.test.ts | 4+++-
6 files changed, 1301 insertions(+), 1 deletion(-)

diff --git a/common/lib/recordingClock-read.mjs b/common/lib/recordingClock-read.mjs @@ -0,0 +1,44 @@ +// recordingClock-read — the time map's READ, in plain JS (lane one-clock). +// +// evidenceClip.mjs's saved-video tier reads `data/<id>/clock.json` under bare +// node (umtool's report-to-video scripts), so the read cannot be the TS +// sidecar's (recordingClock-server.ts declares the file and writes it). The +// shape check is the same one, coerceRecordingClock; like every sidecar read, +// anything wrong reads as null. + +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { CLOCK_FILE, clockMatches, coerceRecordingClock } from "./recordingClock.mjs"; + +/** + * A video dir's clock, or null (absent, unreadable, malformed). + * @param {string} videoDir + * @returns {Promise<import("./recordingClock.mjs").RecordingClock | null>} + */ +export async function readRecordingClock(videoDir) { + try { + return coerceRecordingClock(JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ videoDir, CLOCK_FILE), "utf8"))); + } catch { + return null; + } +} + +/** + * The clock that applies to cutting `container` — the map about THIS container + * (same size as when it was measured) — or null: none, or a stale one (the + * video saved again: its map is another file's). + * @param {string} videoDir + * @param {string} container the saved container's path + * @returns {Promise<import("./recordingClock.mjs").RecordingClock | null>} + */ +export async function clockForContainer(videoDir, container) { + const clock = await readRecordingClock(videoDir); + if (!clock) return null; + if (path.basename(container) !== clock.target.file) return null; + try { + const s = await stat(container); + return clockMatches(clock, { targetBytes: s.size }) ? clock : null; + } catch { + return null; + } +} diff --git a/common/lib/recordingClock-server.test.ts b/common/lib/recordingClock-server.test.ts @@ -0,0 +1,161 @@ +// The time map measured from real files (lane one-clock): a synthetic stream +// encoded as the transcription source (`audio.mp3`) and, shifted, with a +// stretch of something else spliced in, as the saved container (an AAC mp4) — +// the 6 Nov shape: +2.5 s, then +13.1 s after the splice. ffmpeg encodes both; +// the measurement decodes them as it would a real stream. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/recordingClock-server.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, rm, stat, writeFile, readFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { execa } from "execa"; +import { clockOffsetAt, mapSpan } from "./recordingClock.mjs"; +import { + ensureRecordingClock, + planRecordingClock, + recordingClockSidecar, +} from "./recordingClock-server"; +import { clockForContainer, readRecordingClock } from "./recordingClock-read.mjs"; + +const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; +const SR = 16000; + +function speech(seconds: number, seed: number): Float32Array { + let s = seed >>> 0 || 1; + const rnd = () => { + s ^= s << 13; + s >>>= 0; + s ^= s >>> 17; + s ^= s << 5; + s >>>= 0; + return s / 4294967296; + }; + const out = new Float32Array(Math.round(seconds * SR)); + let i = 0; + while (i < out.length) { + const burst = Math.round((0.08 + rnd() * 0.3) * SR); + const amp = rnd() < 0.2 ? 0 : 0.05 + rnd() * 0.3; + // A voiced-ish burst: a pitch around 120–220 Hz plus noise. + const f0 = 120 + rnd() * 100; + for (let k = 0; k < burst && i < out.length; k += 1, i += 1) { + out[i] = amp * (0.6 * Math.sin((2 * Math.PI * f0 * k) / SR) + 0.4 * (rnd() * 2 - 1)); + } + } + return out; +} + +const dirs: string[] = []; +after(async () => { + for (const d of dirs) await rm(d, { recursive: true, force: true }); +}); + +async function encode(samples: Float32Array, out: string, codec: string[]) { + const raw = `${out}.f32`; + await writeFile(raw, Buffer.from(samples.buffer, samples.byteOffset, samples.byteLength)); + await execa(FFMPEG, ["-v", "error", "-y", "-f", "f32le", "-ar", String(SR), "-ac", "1", "-i", raw, ...codec, out]); + await rm(raw); +} + +async function fixture() { + const root = await mkdtemp(path.join(os.tmpdir(), "clock-")); + dirs.push(root); + const videoDir = path.join(root, "channels", "c", "data", "v1slug"); + const store = path.join(root, "saved-videos", "c", "v1slug"); + await mkdir(videoDir, { recursive: true }); + await mkdir(store, { recursive: true }); + const src = speech(420, 11); + const cut = Math.round(200 * SR); + const tgt = new Float32Array(Math.round((420 + 2.5 + 10.6) * SR)); + tgt.set(speech(2.5, 5), 0); + tgt.set(src.subarray(0, cut), Math.round(2.5 * SR)); + tgt.set(speech(10.6, 77), Math.round(2.5 * SR) + cut); + tgt.set(src.subarray(cut), Math.round(2.5 * SR) + cut + Math.round(10.6 * SR)); + await encode(src, path.join(videoDir, "audio.mp3"), ["-c:a", "libmp3lame", "-q:a", "5"]); + await encode(tgt, path.join(store, "source-media.mp4"), ["-c:a", "aac", "-b:a", "96k"]); + const bytes = (await stat(path.join(store, "source-media.mp4"))).size; + await writeFile( + path.join(videoDir, "saved-video.json"), + JSON.stringify({ storedAt: "2026-11-06T00:00:00.000Z", dir: store, file: "source-media.mp4", bytes }), + ); + return { videoDir, container: path.join(store, "source-media.mp4") }; +} + +const OPTS = { sampleRate: 4000, probeSeconds: 10, searchSeconds: 20, everySeconds: 60, minGapSeconds: 10 }; + +test("a step and an offset, measured from an mp3 against an AAC mp4, written as clock.json", async () => { + const { videoDir, container } = await fixture(); + assert.equal((await planRecordingClock(videoDir)).kind, "measure"); + const logs: string[] = []; + const r = await ensureRecordingClock({ + ffmpegBin: FFMPEG, + ffprobeBin: FFPROBE, + videoDir, + extra: [150], + options: OPTS, + onLog: (l) => logs.push(l), + }); + assert.equal(r.measured, true); + const clock = r.clock!; + assert.equal(clock.ok, true, clock.why); + assert.equal(clock.segments.length, 2, JSON.stringify(clock.segments)); + // Exact to the sample: the source decoded from its start, the target seeked + // with a pre-roll (an input seek alone lands an AAC excerpt 10–55 ms off). + assert.ok(Math.abs(clock.segments[0].offset - 2.5) < 0.002, `before ${clock.segments[0].offset}`); + assert.ok(Math.abs(clock.segments[1].offset - 13.1) < 0.002, `after ${clock.segments[1].offset}`); + assert.ok(Math.abs(clock.segments[1].offset - clock.segments[0].offset - 10.6) < 0.002); + assert.ok(clock.gaps[0].from < 200 && clock.gaps[0].to > 200, JSON.stringify(clock.gaps)); + assert.ok((clock.residual.rms ?? 1) < 0.005); + assert.ok(logs.some((l) => /clock → clock\.json: ok/.test(l)), logs.join("")); + // On disk, read back by both readers; current now, not measured again. + assert.deepEqual(await recordingClockSidecar.load(videoDir), clock); + assert.deepEqual(await readRecordingClock(videoDir), clock); + assert.deepEqual(await clockForContainer(videoDir, container), clock); + const again = await ensureRecordingClock({ ffmpegBin: FFMPEG, ffprobeBin: FFPROBE, videoDir, options: OPTS }); + assert.equal(again.measured, false); + assert.equal(again.plan, "current"); + // The map: a span before the splice +2.5, after it +13.1, across it uncertain. + assert.ok(Math.abs(clockOffsetAt(clock, 100).offset - 2.5) < 0.002); + assert.equal(mapSpan(clock, 300, 310).certain, true); + assert.equal(mapSpan(clock, 190, 210).certain, false); +}); + +test("a container saved again makes the map stale; a source extracted from the container needs none", async () => { + const { videoDir, container } = await fixture(); + await ensureRecordingClock({ ffmpegBin: FFMPEG, ffprobeBin: FFPROBE, videoDir, options: { ...OPTS, everySeconds: 200 } }); + const pointer = JSON.parse(await readFile(path.join(videoDir, "saved-video.json"), "utf8")); + await writeFile(container, Buffer.alloc(1000)); + assert.equal(await clockForContainer(videoDir, container), null); + assert.equal((await planRecordingClock(videoDir)).kind, "measure"); + await writeFile( + path.join(videoDir, "media-import.json"), + JSON.stringify({ + entries: [ + { + at: "2026-10-26T19:36:46.301Z", + via: "record-live", + source: { path: "/x.ts", name: "x.ts", bytes: 1, moved: true }, + finalized: "remuxed", + container: { file: pointer.file, seconds: 1, bytes: 1000 }, + kept: "new", + audio: "extracted", + }, + ], + }), + ); + assert.equal((await planRecordingClock(videoDir)).kind, "same-clock"); +}); + +test("no saved container, or no separate source: nothing to measure", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "clock-none-")); + dirs.push(root); + assert.equal((await planRecordingClock(root)).kind, "no-container"); + const store = path.join(root, "store"); + await mkdir(store); + await writeFile(path.join(store, "source-media.mp4"), "x"); + await writeFile(path.join(root, "saved-video.json"), JSON.stringify({ dir: store, file: "source-media.mp4", bytes: 1 })); + assert.equal((await planRecordingClock(root)).kind, "no-source"); +}); diff --git a/common/lib/recordingClock-server.ts b/common/lib/recordingClock-server.ts @@ -0,0 +1,340 @@ +// recordingClock-server — MEASURE a recording's time map and write it +// (lane one-clock; the map itself, its fit and its lookups: ./recordingClock.mjs). +// +// The SOURCE is the file the cues were transcribed from — the video dir's +// `audio.<fmt>` (the one the transcribe path reads first, AUDIO_PREFERENCE) — +// and the TARGET is the saved whole container. The source is decoded FROM ITS +// START, as the transcriber decoded it: an mp3 cannot be seeked to the sample +// (a VBR file's byte seek lands where its bitrate estimate says, not where the +// samples are), and a cue's second is a count of samples from the first. Only +// the probes are kept (≈ 20 s each), so a four-hour stream costs a streamed +// decode, not its PCM in memory. The target is an mp4, whose index seeks +// exactly, so each anchor decodes only its own search excerpt there, with the +// same input seek the cutters use (evidenceClip.mjs cutArgs). +// +// No map is measured when the source shares the container's clock: a landed +// container whose `audio.<fmt>` was EXTRACTED from it (media-import.json, the +// live recorder and import-media). Its cues are the container's own seconds. +// +// `data/<id>/clock.json` is a declared sidecar (sidecar-server.ts). A map that +// is not ok is written too, with its reason: the next fetch knows the stream +// was measured and why the map cannot be trusted, and says so instead of +// measuring again. + +import { spawn } from "node:child_process"; +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { execa } from "execa"; +import { sidecar, sidecarField } from "./sidecar-server"; +import { + CLOCK_DEFAULTS, + CLOCK_FILE, + CLOCK_VERSION, + anchorTimes, + clockMatches, + coerceRecordingClock, + describeClock, + fitClock, + measureAnchor, + refineTimes, + type RecordingClock, +} from "./recordingClock.mjs"; +import { audioFilesOf, present } from "./evidenceClip.mjs"; +import { probeMedia } from "./evidenceClip-server"; +import { loadSavedVideo } from "./savedVideo-server"; +import { savedVideoPath, type SavedVideoPointer } from "./savedVideo"; +import { coerceMediaImport, MEDIA_IMPORT_FILENAME } from "./mediaImport"; +import { readJsonFile } from "./jsonFile-server"; + +export const recordingClockSidecar = sidecar(CLOCK_FILE, sidecarField(coerceRecordingClock), { indent: 2 }); + +export type ClockOptions = Partial<typeof CLOCK_DEFAULTS>; + +// ---- decoding --------------------------------------------------------------- + +/** + * Decode `file` from its first sample, mono at `sampleRate`, keeping only the + * spans asked for (seconds, the decoder's own clock). Stops reading at the + * last span's end. + */ +export async function decodeSpansFromStart(opts: { + ffmpegBin: string; + file: string; + spans: { from: number; to: number }[]; + sampleRate: number; + signal?: AbortSignal; +}): Promise<Float32Array[]> { + const { sampleRate: sr } = opts; + const spans = opts.spans.map((s) => ({ + a: Math.max(0, Math.round(s.from * sr)), + b: Math.max(0, Math.round(s.to * sr)), + })); + const out = spans.map((s) => new Float32Array(Math.max(0, s.b - s.a))); + const end = spans.reduce((m, s) => Math.max(m, s.b), 0); + if (end === 0) return out; + const args = [ + "-v", "error", "-nostdin", + "-i", opts.file, + "-vn", "-ac", "1", "-ar", String(sr), + "-t", ((end + sr) / sr).toFixed(3), + "-f", "f32le", "pipe:1", + ]; + await new Promise<void>((resolve, reject) => { + const child = spawn(opts.ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"] }); + let err = ""; + let pos = 0; // samples seen + let carry: Buffer | null = null; + const onAbort = () => child.kill("SIGKILL"); + opts.signal?.addEventListener("abort", onAbort, { once: true }); + child.stderr.on("data", (d: Buffer) => { + err = (err + d.toString()).slice(-2000); + }); + child.stdout.on("data", (chunk: Buffer) => { + let buf = carry ? Buffer.concat([carry, chunk]) : chunk; + const whole = buf.length - (buf.length % 4); + carry = whole < buf.length ? Buffer.from(buf.subarray(whole)) : null; + buf = buf.subarray(0, whole); + const n = whole / 4; + const chunkStart = pos; + const chunkEnd = pos + n; + for (let i = 0; i < spans.length; i += 1) { + const s = spans[i]; + const lo = Math.max(s.a, chunkStart); + const hi = Math.min(s.b, chunkEnd); + for (let k = lo; k < hi; k += 1) out[i][k - s.a] = buf.readFloatLE((k - chunkStart) * 4); + } + pos = chunkEnd; + }); + child.on("error", reject); + child.on("close", (code) => { + opts.signal?.removeEventListener("abort", onAbort); + if (opts.signal?.aborted) reject(new Error("cancelled")); + else if (code !== 0) reject(new Error(`ffmpeg could not decode ${path.basename(opts.file)}: ${err.trim().split("\n").slice(-2).join(" | ")}`)); + else resolve(); + }); + }); + return out; +} + +// The seconds an input seek lands short of, decoded and dropped by an output +// seek. An input seek alone into an AAC track lands 10–55 ms off, varying with +// the second (measured on an audio-only mp4: 48, 38, 54, 12 ms at four +// seconds); seeking PRE_ROLL_S earlier and dropping the rest after the decoder +// is exact at every one. +const PRE_ROLL_S = 3; + +/** Decode [from, from + seconds) of `file`: an input seek PRE_ROLL_S early, then exact. */ +export async function decodeExcerpt(opts: { + ffmpegBin: string; + file: string; + from: number; + seconds: number; + sampleRate: number; + signal?: AbortSignal; +}): Promise<Float32Array> { + const from = Math.max(0, opts.from); + const seek = Math.max(0, from - PRE_ROLL_S); + const r = await execa( + opts.ffmpegBin, + [ + "-v", "error", "-nostdin", + "-ss", seek.toFixed(3), + "-i", opts.file, + "-ss", (from - seek).toFixed(3), + "-t", opts.seconds.toFixed(3), + "-vn", "-ac", "1", "-ar", String(opts.sampleRate), + "-f", "f32le", "pipe:1", + ], + { + encoding: "buffer", + reject: false, + timeout: 120_000, + maxBuffer: 64 * 1024 * 1024, + ...(opts.signal ? { cancelSignal: opts.signal } : {}), + }, + ); + if (r.exitCode !== 0) { + const err = Buffer.from(r.stderr ?? "").toString().trim().split("\n").slice(-2).join(" | "); + throw new Error(`ffmpeg could not decode ${path.basename(opts.file)} at ${opts.from.toFixed(1)}s: ${err}`); + } + const buf = Buffer.from(r.stdout as Uint8Array); + const n = Math.floor(buf.length / 4); + const out = new Float32Array(n); + for (let i = 0; i < n; i += 1) out[i] = buf.readFloatLE(i * 4); + return out; +} + +// ---- which files --------------------------------------------------------------- + +/** The file the cues were transcribed from: the best `audio.<fmt>` there is. */ +export async function transcriptionSourceOf(videoDir: string): Promise<{ name: string; path: string } | null> { + for (const f of await audioFilesOf(videoDir)) if (await present(f.path)) return f; + return null; +} + +/** + * Was the transcription source EXTRACTED from this container (a landed live + * recording, an import)? Then the cues are already on its clock. + */ +export async function sourceSharesContainerClock(videoDir: string, pointer: SavedVideoPointer): Promise<boolean> { + const read = await readJsonFile(path.join(videoDir, MEDIA_IMPORT_FILENAME)); + if (!read.ok) return false; + const rec = coerceMediaImport(read.value); + const last = rec?.entries?.[rec.entries.length - 1]; + return !!last && last.audio === "extracted" && last.container?.file === pointer.file; +} + +export type ClockPlan = + | { kind: "no-container" } + | { kind: "no-source" } + | { kind: "same-clock"; source: string; container: string } + | { kind: "current"; clock: RecordingClock; source: string; container: string } + | { kind: "measure"; source: string; container: string; sourceBytes: number; targetBytes: number; stale: RecordingClock | null }; + +/** What a video dir needs: nothing, its map as it is, or a measurement. */ +export async function planRecordingClock(videoDir: string): Promise<ClockPlan> { + const pointer = await loadSavedVideo(videoDir); + if (!pointer) return { kind: "no-container" }; + const container = savedVideoPath(pointer); + const src = await transcriptionSourceOf(videoDir); + if (!src) return { kind: "no-source" }; + if (await sourceSharesContainerClock(videoDir, pointer)) { + return { kind: "same-clock", source: src.path, container }; + } + const [s, t] = await Promise.all([stat(src.path), stat(container)]); + const have = await recordingClockSidecar.load(videoDir); + if (have && have.target.file === path.basename(container) && have.source.file === src.name && clockMatches(have, { sourceBytes: s.size, targetBytes: t.size })) { + return { kind: "current", clock: have, source: src.path, container }; + } + return { kind: "measure", source: src.path, container, sourceBytes: s.size, targetBytes: t.size, stale: have }; +} + +// ---- measuring ------------------------------------------------------------------ + +/** + * Measure the map of `videoDir`'s transcription source onto its saved + * container: anchors every `everySeconds` and at `extra` (cue seconds — the + * cited spans), refined inside every step until narrow; fitted; WRITTEN (ok or + * not) unless `write: false`. + */ +export async function measureRecordingClock(opts: { + ffmpegBin: string; + ffprobeBin: string; + videoDir: string; + source: string; + container: string; + sourceBytes: number; + targetBytes: number; + extra?: number[]; + options?: ClockOptions; + write?: boolean; + onLog?: (line: string) => void; + signal?: AbortSignal; + now?: () => Date; +}): Promise<RecordingClock> { + const o = { ...CLOCK_DEFAULTS, ...(opts.options ?? {}) }; + const sr = o.sampleRate; + const log = (l: string) => opts.onLog?.(l.endsWith("\n") ? l : `${l}\n`); + const [sp, tp] = await Promise.all([ + probeMedia(opts.source, opts.ffprobeBin), + probeMedia(opts.container, opts.ffprobeBin), + ]); + const sourceSec = sp?.durationSec ?? null; + const targetSec = tp?.durationSec ?? null; + if (!sourceSec || !targetSec) { + throw new Error(`ffprobe could not read ${!sourceSec ? opts.source : opts.container}`); + } + const half = o.probeSeconds / 2; + const measure = async (times: number[]) => { + const probes = await decodeSpansFromStart({ + ffmpegBin: opts.ffmpegBin, + file: opts.source, + spans: times.map((t) => ({ from: t - half, to: t + half })), + sampleRate: sr, + signal: opts.signal, + }); + const out = []; + for (let i = 0; i < times.length; i += 1) { + const at = times[i]; + const searchStart = Math.max(0, at - half - o.searchSeconds); + const searchEnd = Math.min(targetSec, at + half + o.searchSeconds); + if (searchEnd - searchStart < o.probeSeconds) { + out.push({ at, offset: null, score: 0, ratio: 0, ok: false, why: "past the container's end" }); + continue; + } + const search = await decodeExcerpt({ + ffmpegBin: opts.ffmpegBin, + file: opts.container, + from: searchStart, + seconds: searchEnd - searchStart, + sampleRate: sr, + signal: opts.signal, + }); + out.push(measureAnchor({ at, probe: probes[i], search, searchStart, sampleRate: sr }, o)); + } + return out; + }; + + const first = anchorTimes(sourceSec, { ...o, extra: opts.extra ?? [] }); + log( + ` ⏱ clock: ${path.basename(opts.source)} (${Math.round(sourceSec)} s, the cues' clock) against ` + + `${path.basename(opts.container)} (${Math.round(targetSec)} s): ${first.length} anchor(s)`, + ); + let anchors = await measure(first); + let fit = fitClock(anchors, o); + for (let pass = 0; pass < o.maxRefinePasses; pass += 1) { + const more = refineTimes(fit, o).filter((t) => t >= half && t <= sourceSec - half); + if (!more.length) break; + log(` ⏱ clock: a step between segments — ${more.length} more anchor(s) to narrow it`); + anchors = [...anchors, ...(await measure(more))].sort((a, b) => a.at - b.at); + fit = fitClock(anchors, o); + } + const createdAt = (opts.now?.() ?? new Date()).toISOString(); + const clock: RecordingClock = { + version: CLOCK_VERSION, + id: `${createdAt}:${opts.targetBytes}`, + createdAt, + source: { file: path.basename(opts.source), bytes: opts.sourceBytes }, + target: { file: path.basename(opts.container), bytes: opts.targetBytes }, + method: "xcorr", + params: { + sampleRate: sr, + probeSeconds: o.probeSeconds, + searchSeconds: o.searchSeconds, + everySeconds: o.everySeconds, + tolerance: o.tolerance, + sourceSeconds: sourceSec, + targetSeconds: targetSec, + }, + anchors, + segments: fit.segments, + gaps: fit.gaps, + residual: fit.residual, + ok: fit.ok, + ...(fit.why ? { why: fit.why } : {}), + }; + if (opts.write !== false) await recordingClockSidecar.write(opts.videoDir, clock); + log(` ⏱ clock ${opts.write !== false ? `→ ${CLOCK_FILE}` : "(not written)"}: ${describeClock(clock)}`); + return clock; +} + +/** + * The map a cut from this video's saved container goes through: the current + * one, else measured now (and written). Null when no map applies (no + * container, no separate source, a source extracted from the container). + */ +export async function ensureRecordingClock(opts: { + ffmpegBin: string; + ffprobeBin: string; + videoDir: string; + extra?: number[]; + options?: ClockOptions; + onLog?: (line: string) => void; + signal?: AbortSignal; +}): Promise<{ clock: RecordingClock | null; measured: boolean; plan: ClockPlan["kind"] }> { + const plan = await planRecordingClock(opts.videoDir); + if (plan.kind === "current") return { clock: plan.clock, measured: false, plan: plan.kind }; + if (plan.kind !== "measure") return { clock: null, measured: false, plan: plan.kind }; + const clock = await measureRecordingClock({ ...opts, ...plan }); + return { clock, measured: true, plan: plan.kind }; +} diff --git a/common/lib/recordingClock.mjs b/common/lib/recordingClock.mjs @@ -0,0 +1,539 @@ +// recordingClock — ONE CLOCK PER RECORDING (lane one-clock, 6 Nov 2026). +// +// A recording's cues are timed on the file that was TRANSCRIBED (a Rumble +// channel's `audio.mp3`, a separate audio-only download of the stream), and its +// clip windows are cut from ANOTHER file — the saved whole video, or a remote +// seek. Two downloads of one live stream are not one clock: measured on the +// rev9-a3 pass of quartering-diet with parakeet word timings on every fetched +// window, seven Rumble clips played the wrong words (c43 +13.1 s, c45 +13.6 s, +// c20 +5.2 s, k41 +2.6 s, c18 +1.6 s, k46 −0.7 s, c19 ≈ −1 s), and not one +// constant per recording: v7eqa6e had c44 at 0 s and c45 at +13.6 s, a step +// inside one stream (a dropped stretch in one of the two downloads). +// +// So a recording whose windows are cut from its saved video gets a TIME MAP, +// `data/<id>/clock.json`: the transcription source's audio (the cue clock) is +// cross-correlated against the saved container's audio at anchors across the +// stream — every few minutes, and around each cited span — and a +// piecewise-linear map is fitted, offset(t) = target − source, with its residual. +// A window asked for in cue seconds is cut from the container at the MAPPED +// seconds and keeps its cue-clock name, so every reader (the render, the bench, +// the moment page) stays on the one clock the cues and the manifests use. +// +// Between two segments that disagree there is a STEP, somewhere in a gap the +// anchors could not narrow further; a span that touches a gap is not mapped +// with confidence (`certain: false`) and falls to the per-clip quote check. A +// map whose residual is bad (music, silence, a different edit) is written with +// `ok: false` and the reason, and nothing cuts through it. +// +// This file is PURE and plain JS (umtool's report-to-video scripts run under +// bare node and read the map through evidenceClip.mjs): the correlation, the +// fit, the lookups and the file's shape. Decoding and the sidecar's writer are +// ./recordingClock-server.ts. + +export const CLOCK_FILE = "clock.json"; +export const CLOCK_VERSION = 1; + +/** + * @typedef {{ sampleRate: number, probeSeconds: number, searchSeconds: number, everySeconds: number, + * minScore: number, minPeakRatio: number, tolerance: number, minGapSeconds: number, refinePerGap: number, + * maxRefinePasses: number, maxRms: number, minAnchors: number, minUsableShare: number }} ClockParams + */ + +/** + * The knobs, with the values the 6 Nov streams were measured with. Seconds + * unless named otherwise. + * @type {Readonly<ClockParams>} + */ +export const CLOCK_DEFAULTS = Object.freeze({ + // Decode rate for both sides: speech correlates sharply at 8 kHz, and a lag + // is resolved to an eighth of a millisecond. + sampleRate: 8000, + // The source excerpt at each anchor (centred on it). + probeSeconds: 20, + // How far either side the target is searched. The largest offset measured + // on 6 Nov was 13.6 s. + searchSeconds: 45, + // The regular anchors' spacing across the stream. + everySeconds: 300, + // Normalised cross-correlation a match must reach, and how far above the + // best peak elsewhere (≥ 0.25 s away) it must stand. + minScore: 0.35, + minPeakRatio: 1.15, + // Two anchors on one segment agree to within this (after its drift). + tolerance: 0.08, + // A gap between two segments is narrowed until it is at most this wide. + minGapSeconds: 10, + // Anchors measured per gap per refinement pass. + refinePerGap: 7, + // Passes of refinement. + maxRefinePasses: 4, + // The fitted map is `ok` only under this RMS residual. + maxRms: 0.05, + // ...with at least this many usable anchors, this share of those measured. + minAnchors: 3, + minUsableShare: 0.4, +}); + +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +// ---- FFT ------------------------------------------------------------------- + +/** The smallest power of two ≥ n. */ +export function nextPow2(n) { + let p = 1; + while (p < n) p *= 2; + return p; +} + +/** + * In-place iterative radix-2 complex FFT. `re`/`im` have a power-of-two length. + * @param {Float64Array} re + * @param {Float64Array} im + * @param {boolean} [inverse] + */ +export function fft(re, im, inverse = false) { + const n = re.length; + for (let i = 1, j = 0; i < n; i += 1) { + let bit = n >> 1; + for (; j & bit; bit >>= 1) j ^= bit; + j ^= bit; + if (i < j) { + let t = re[i]; + re[i] = re[j]; + re[j] = t; + t = im[i]; + im[i] = im[j]; + im[j] = t; + } + } + for (let len = 2; len <= n; len <<= 1) { + const ang = ((inverse ? 2 : -2) * Math.PI) / len; + const wr = Math.cos(ang); + const wi = Math.sin(ang); + const half = len >> 1; + for (let i = 0; i < n; i += len) { + let cr = 1; + let ci = 0; + for (let k = 0; k < half; k += 1) { + const a = i + k; + const b = a + half; + const xr = re[b] * cr - im[b] * ci; + const xi = re[b] * ci + im[b] * cr; + re[b] = re[a] - xr; + im[b] = im[a] - xi; + re[a] += xr; + im[a] += xi; + const ncr = cr * wr - ci * wi; + ci = cr * wi + ci * wr; + cr = ncr; + } + } + } + if (inverse) { + for (let i = 0; i < n; i += 1) { + re[i] /= n; + im[i] /= n; + } + } +} + +/** + * Pre-emphasis and mean removal: a first difference sharpens the correlation + * peak (speech's low end is broad and correlates with itself over tens of + * milliseconds) and the mean would otherwise bias every lag alike. + * @param {ArrayLike<number>} x + * @returns {Float64Array} + */ +export function whiten(x) { + const out = new Float64Array(x.length); + let prev = 0; + let sum = 0; + for (let i = 0; i < x.length; i += 1) { + const v = Number(x[i]) || 0; + out[i] = v - 0.97 * prev; + prev = v; + sum += out[i]; + } + const mean = x.length ? sum / x.length : 0; + for (let i = 0; i < out.length; i += 1) out[i] -= mean; + return out; +} + +/** + * Where `probe` sits inside `search`: the lag (samples into `search`) with the + * highest normalised cross-correlation, that score, and the best score at least + * `guard` samples away (how unique the match is). + * + * @param {ArrayLike<number>} probe + * @param {ArrayLike<number>} search at least as long as `probe` + * @param {{ guard?: number }} [opts] + * @returns {{ lag: number, score: number, second: number } | null} null when + * either side is silent or `search` is shorter than `probe` + */ +export function locate(probe, search, { guard = 2000 } = {}) { + const p = whiten(probe); + const s = whiten(search); + const n = p.length; + const m = s.length; + if (n < 16 || m < n) return null; + let ep = 0; + for (let i = 0; i < n; i += 1) ep += p[i] * p[i]; + if (!(ep > 1e-9)) return null; + const N = nextPow2(m); + const ar = new Float64Array(N); + const ai = new Float64Array(N); + const br = new Float64Array(N); + const bi = new Float64Array(N); + ar.set(p); + br.set(s); + fft(ar, ai); + fft(br, bi); + // conj(A) · B: c[k] = Σ p[i] s[i + k] + for (let i = 0; i < N; i += 1) { + const r = ar[i] * br[i] + ai[i] * bi[i]; + const im = ar[i] * bi[i] - ai[i] * br[i]; + ar[i] = r; + ai[i] = im; + } + fft(ar, ai, true); + // The energy of every n-long stretch of `search`, from prefix sums. + const pre = new Float64Array(m + 1); + for (let i = 0; i < m; i += 1) pre[i + 1] = pre[i] + s[i] * s[i]; + const lags = m - n + 1; + const ncc = new Float64Array(lags); + let best = -Infinity; + let at = -1; + const floor = ep * 1e-6; + for (let k = 0; k < lags; k += 1) { + const es = pre[k + n] - pre[k]; + const v = es > floor ? ar[k] / Math.sqrt(ep * es) : 0; + ncc[k] = v; + if (v > best) { + best = v; + at = k; + } + } + if (at < 0) return null; + let second = 0; + for (let k = 0; k < lags; k += 1) { + if (Math.abs(k - at) <= guard) continue; + if (ncc[k] > second) second = ncc[k]; + } + return { lag: at, score: best, second }; +} + +/** + * One anchor: the source excerpt centred on `at` (cue clock) found in the + * target excerpt that starts at `searchStart` (target clock). + * + * @param {{ at: number, probe: ArrayLike<number>, search: ArrayLike<number>, searchStart: number, sampleRate: number }} a + * @param {Partial<typeof CLOCK_DEFAULTS>} [opts] + * @returns {{ at: number, offset: number | null, score: number, ratio: number, ok: boolean, why?: string }} + */ +export function measureAnchor({ at, probe, search, searchStart, sampleRate }, opts = {}) { + const o = { ...CLOCK_DEFAULTS, ...opts }; + const hit = locate(probe, search, { guard: Math.round(0.25 * sampleRate) }); + if (!hit) return { at, offset: null, score: 0, ratio: 0, ok: false, why: "silent" }; + const probeStart = at - probe.length / sampleRate / 2; + const offset = round4(searchStart + hit.lag / sampleRate - probeStart); + const ratio = hit.second > 1e-9 ? hit.score / hit.second : 99; + const score = round4(hit.score); + if (hit.score < o.minScore) return { at, offset, score, ratio: round4(ratio), ok: false, why: "weak" }; + if (ratio < o.minPeakRatio) return { at, offset, score, ratio: round4(ratio), ok: false, why: "ambiguous" }; + return { at, offset, score, ratio: round4(Math.min(ratio, 99)), ok: true }; +} + +const round4 = (x) => Math.round(x * 1e4) / 1e4; + +// ---- the anchors -------------------------------------------------------------- + +/** + * Where to measure: every `everySeconds` across the source (the first half a + * step in), plus the extra seconds (around each cited span), each kept where a + * whole probe fits. Sorted, deduplicated to a tenth of the probe. + * + * @param {number} duration the source's length + * @param {{ extra?: number[] } & Partial<typeof CLOCK_DEFAULTS>} [opts] + * @returns {number[]} + */ +export function anchorTimes(duration, { extra = [], ...rest } = {}) { + const o = { ...CLOCK_DEFAULTS, ...rest }; + const half = o.probeSeconds / 2; + const lo = half; + const hi = duration - half; + if (!(hi >= lo)) return []; + const out = []; + for (let t = Math.min(o.everySeconds / 2, hi); t <= hi + 1e-9; t += o.everySeconds) out.push(t); + if (out.length && hi - out[out.length - 1] > o.everySeconds / 3) out.push(hi); + for (const x of extra) if (fin(x)) out.push(Math.min(hi, Math.max(lo, x))); + out.sort((a, b) => a - b); + const dedup = []; + for (const t of out) { + if (!dedup.length || t - dedup[dedup.length - 1] > o.probeSeconds / 10) dedup.push(round4(t)); + } + return dedup; +} + +// ---- the fit ----------------------------------------------------------------- + +/** Least squares offset = a + b·(t − t0) over the points; rate 0 for a short run. */ +function fitLine(points) { + const n = points.length; + const t0 = points[0].at; + const span = points[n - 1].at - t0; + if (n < 3 || span < 120) { + const sorted = points.map((p) => p.offset).sort((a, b) => a - b); + const med = sorted[Math.floor((n - 1) / 2)]; + return { t0, offset: med, rate: 0 }; + } + let sx = 0; + let sy = 0; + let sxx = 0; + let sxy = 0; + for (const p of points) { + const x = p.at - t0; + sx += x; + sy += p.offset; + sxx += x * x; + sxy += x * p.offset; + } + const den = n * sxx - sx * sx; + const rate = den > 1e-12 ? (n * sxy - sx * sy) / den : 0; + return { t0, offset: (sy - rate * sx) / n, rate }; +} + +const lineAt = (l, t) => l.offset + l.rate * (t - l.t0); + +/** + * The piecewise-linear map from the measured anchors. Consecutive usable anchors + * that agree (to `tolerance`, after the run's drift) are one SEGMENT; one that + * disagrees while the next agrees again is an OUTLIER; otherwise a new segment + * starts and the stretch between the two is a GAP (a step somewhere in it). + * + * @param {{ at: number, offset: number | null, ok: boolean }[]} anchors + * @param {Partial<typeof CLOCK_DEFAULTS>} [opts] + */ +export function fitClock(anchors, opts = {}) { + const o = { ...CLOCK_DEFAULTS, ...opts }; + const good = anchors + .filter((a) => a.ok && fin(a.offset) && fin(a.at)) + .sort((a, b) => a.at - b.at); + /** @type {{ at: number, offset: number }[][]} */ + const runs = []; + /** @type {number[]} */ + const outliers = []; + let run = null; + for (let i = 0; i < good.length; i += 1) { + const p = good[i]; + if (!run) { + run = [p]; + runs.push(run); + continue; + } + const line = fitLine(run); + if (Math.abs(p.offset - lineAt(line, p.at)) <= o.tolerance) { + run.push(p); + continue; + } + const q = good[i + 1]; + if (q && Math.abs(q.offset - lineAt(line, q.at)) <= o.tolerance) { + outliers.push(p.at); + continue; + } + run = [p]; + runs.push(run); + } + const segments = runs.map((r) => { + const l = fitLine(r); + let ss = 0; + for (const p of r) ss += (p.offset - lineAt(l, p.at)) ** 2; + return { + from: r[0].at, + to: r[r.length - 1].at, + offset: round4(lineAt(l, r[0].at)), + rate: Number(l.rate.toExponential(6)), + n: r.length, + rms: round4(Math.sqrt(ss / r.length)), + }; + }); + // A GAP is wider than the stretch between the two anchors: each anchor's probe + // reached half a probe beyond its centre, and a probe that straddles the step + // still matches the side holding most of it — so the step may sit up to half + // a probe inside either neighbour's centre. + const margin = o.probeSeconds / 2; + const gaps = []; + for (let i = 1; i < segments.length; i += 1) { + gaps.push({ from: round4(segments[i - 1].to - margin), to: round4(segments[i].from + margin) }); + } + let ss = 0; + let max = 0; + let n = 0; + for (const r of runs) { + const l = fitLine(r); + for (const p of r) { + const d = Math.abs(p.offset - lineAt(l, p.at)); + ss += d * d; + max = Math.max(max, d); + n += 1; + } + } + const residual = { rms: n ? round4(Math.sqrt(ss / n)) : null, max: n ? round4(max) : null, n }; + const measured = anchors.length; + const why = []; + if (n < Math.min(o.minAnchors, measured)) why.push(`${n} usable anchor(s) of ${measured}`); + else if (measured && n / measured < o.minUsableShare) why.push(`only ${n} of ${measured} anchors matched (music, silence or a different edit?)`); + if (residual.rms !== null && residual.rms > o.maxRms) why.push(`residual ${residual.rms}s over ${o.maxRms}s`); + if (outliers.length > Math.max(1, n / 4)) why.push(`${outliers.length} anchors disagree with their neighbours`); + if (!segments.length) why.push("no anchor matched"); + return { + segments, + gaps, + outliers, + residual, + ok: why.length === 0, + ...(why.length ? { why: why.join("; ") } : {}), + }; +} + +/** + * Seconds to measure next: inside every gap still wider than `minGapSeconds`, + * `refinePerGap` evenly spaced anchors. + * @param {{ gaps: { from: number, to: number }[] }} fit + * @param {Partial<typeof CLOCK_DEFAULTS>} [opts] + * @returns {number[]} + */ +export function refineTimes(fit, opts = {}) { + const o = { ...CLOCK_DEFAULTS, ...opts }; + const out = []; + const margin = o.probeSeconds / 2; + for (const g of fit.gaps ?? []) { + // Between the two anchors' centres (fitClock widened the gap by a margin). + const from = g.from + margin; + const w = g.to - margin - from; + if (!(w > o.minGapSeconds)) continue; + const k = Math.max(1, Math.min(o.refinePerGap, Math.ceil(w / o.minGapSeconds) - 1)); + for (let i = 1; i <= k; i += 1) out.push(round4(from + (w * i) / (k + 1))); + } + return out; +} + +// ---- the lookups --------------------------------------------------------------- + +/** + * The offset (target − source) at cue second `t`: the segment holding it, else + * the nearest segment's edge value. `certain` is false inside a gap (a step lies + * somewhere in it) and for a map that is not `ok`. + * + * @param {RecordingClock} clock + * @param {number} t + * @returns {{ offset: number, certain: boolean, segment: number }} + */ +export function clockOffsetAt(clock, t) { + const segs = clock?.segments ?? []; + if (!segs.length) return { offset: 0, certain: false, segment: -1 }; + const at = (s, x) => s.offset + s.rate * (Math.min(s.to, Math.max(s.from, x)) - s.from); + const ok = clock.ok === true; + // The segment whose centre-span holds t, else the nearer neighbour. + let i = 0; + while (i < segs.length - 1 && t > segs[i].to) { + const next = segs[i + 1]; + if (t < next.from) { + if (next.from - t < t - segs[i].to) i += 1; + break; + } + i += 1; + } + // Inside a gap (a step lies somewhere in it): not certain. + const inGap = (clock.gaps ?? []).some((g) => t > g.from && t < g.to); + return { offset: round4(at(segs[i], t)), certain: ok && !inGap, segment: i }; +} + +/** + * A cue-clock span on the target's clock. `certain` only when both ends sit on + * ONE segment of an `ok` map (a span across a step has no single offset). + * + * @param {RecordingClock} clock + * @param {number} from + * @param {number} to + * @returns {{ from: number, to: number, offsetFrom: number, offsetTo: number, certain: boolean }} + */ +export function mapSpan(clock, from, to) { + const a = clockOffsetAt(clock, from); + const b = clockOffsetAt(clock, to); + return { + from: round4(Math.max(0, from + a.offset)), + to: round4(to + b.offset), + offsetFrom: a.offset, + offsetTo: b.offset, + certain: a.certain && b.certain && a.segment === b.segment, + }; +} + +// ---- the file ---------------------------------------------------------------- + +/** + * @typedef {{ file: string, bytes: number }} ClockFileRef + * @typedef {{ + * version: number, + * id: string, + * createdAt: string, + * source: ClockFileRef, + * target: ClockFileRef, + * method: "xcorr", + * params: Record<string, number>, + * anchors: { at: number, offset: number | null, score: number, ratio: number, ok: boolean, why?: string }[], + * segments: { from: number, to: number, offset: number, rate: number, n: number, rms: number }[], + * gaps: { from: number, to: number }[], + * residual: { rms: number | null, max: number | null, n: number }, + * ok: boolean, + * why?: string, + * }} RecordingClock + */ + +/** + * The file's shape, checked: the clock or null (a sidecar's read never throws). + * @param {unknown} v + * @returns {RecordingClock | null} + */ +export function coerceRecordingClock(v) { + if (!v || typeof v !== "object" || Array.isArray(v)) return null; + const c = /** @type {Record<string, any>} */ (v); + if (c.version !== CLOCK_VERSION || typeof c.id !== "string" || !c.id) return null; + const ref = (r) => r && typeof r === "object" && typeof r.file === "string" && fin(r.bytes); + if (!ref(c.source) || !ref(c.target)) return null; + if (!Array.isArray(c.segments) || !Array.isArray(c.gaps) || !Array.isArray(c.anchors)) return null; + const segOk = (s) => s && fin(s.from) && fin(s.to) && fin(s.offset) && fin(s.rate) && s.to >= s.from; + if (!c.segments.every(segOk)) return null; + if (!c.gaps.every((g) => g && fin(g.from) && fin(g.to))) return null; + if (typeof c.ok !== "boolean") return null; + return /** @type {RecordingClock} */ (c); +} + +/** + * Is this clock about THESE two files? A container saved again, or a source + * downloaded again, is another clock: the map is stale and nothing cuts + * through it. + * @param {RecordingClock} clock + * @param {{ sourceBytes?: number | null, targetBytes?: number | null }} now + */ +export function clockMatches(clock, { sourceBytes = null, targetBytes = null } = {}) { + if (sourceBytes !== null && clock.source.bytes !== sourceBytes) return false; + if (targetBytes !== null && clock.target.bytes !== targetBytes) return false; + return true; +} + +/** One line for a log: the segments' offsets, the gaps, the residual. */ +export function describeClock(clock) { + const segs = (clock.segments ?? []).map( + (s) => `${s.offset >= 0 ? "+" : ""}${s.offset.toFixed(2)}s @${Math.round(s.from)}–${Math.round(s.to)}s`, + ); + const gaps = (clock.gaps ?? []).map((g) => `${Math.round(g.from)}–${Math.round(g.to)}s`); + const res = clock.residual?.rms === null || clock.residual?.rms === undefined ? "?" : `${(clock.residual.rms * 1000).toFixed(1)} ms`; + const used = (clock.anchors ?? []).filter((a) => a.ok).length; + return ( + `${clock.ok ? "ok" : "NOT ok"}: ${segs.join(", ") || "no segment"}` + + (gaps.length ? `; step(s) inside ${gaps.join(", ")}` : "") + + `; residual ${res} over ${used}/${(clock.anchors ?? []).length} anchors` + + (clock.why ? ` — ${clock.why}` : "") + ); +} diff --git a/common/lib/recordingClock.test.ts b/common/lib/recordingClock.test.ts @@ -0,0 +1,214 @@ +// One clock per recording (lane one-clock): the correlation finds a synthetic +// offset, a step inside the stream is found and narrowed, a drift is fitted, a +// silent or unmatched stream is not ok, and the lookups map a cue span onto the +// target's clock — or say they cannot. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/recordingClock.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + CLOCK_DEFAULTS, + anchorTimes, + clockMatches, + clockOffsetAt, + coerceRecordingClock, + describeClock, + fitClock, + locate, + mapSpan, + measureAnchor, + refineTimes, + type RecordingClock, +} from "./recordingClock.mjs"; + +const SR = 4000; + +// Speech-like: noise in syllable-length bursts with pauses, from a seeded PRNG. +function speech(seconds: number, seed: number): Float32Array { + let s = seed >>> 0 || 1; + const rnd = () => { + s ^= s << 13; + s >>>= 0; + s ^= s >>> 17; + s ^= s << 5; + s >>>= 0; + return s / 4294967296; + }; + const out = new Float32Array(Math.round(seconds * SR)); + let i = 0; + while (i < out.length) { + const burst = Math.round((0.08 + rnd() * 0.3) * SR); + const amp = rnd() < 0.2 ? 0 : 0.2 + rnd(); + for (let k = 0; k < burst && i < out.length; k += 1, i += 1) out[i] = amp * (rnd() * 2 - 1); + } + return out; +} + +function concat(...parts: Float32Array[]): Float32Array { + const out = new Float32Array(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + for (const p of parts) { + out.set(p, o); + o += p.length; + } + return out; +} + +const slice = (x: Float32Array, from: number, to: number) => + x.subarray(Math.max(0, Math.round(from * SR)), Math.min(x.length, Math.round(to * SR))); + +// Measure every anchor the way the server does: the source probe centred on +// `at`, the target searched ±search around it. +function measureAll(source: Float32Array, target: Float32Array, times: number[], opts = {}) { + const o = { ...CLOCK_DEFAULTS, sampleRate: SR, probeSeconds: 10, searchSeconds: 20, ...opts }; + return times.map((at) => { + const probe = slice(source, at - o.probeSeconds / 2, at + o.probeSeconds / 2); + const searchStart = Math.max(0, at - o.probeSeconds / 2 - o.searchSeconds); + const search = slice(target, searchStart, at + o.probeSeconds / 2 + o.searchSeconds); + return measureAnchor({ at, probe, search, searchStart, sampleRate: SR }, o); + }); +} + +// The 6 Nov shape: the target starts 2.5 s later, and 10.6 s of something +// else sits in it at source second 400 — so c44-like spans before it are +2.5, +// c45-like spans after it +13.1. +const SOURCE = speech(900, 7); +const TARGET = concat(speech(2.5, 99), slice(SOURCE, 0, 400), speech(10.6, 123), slice(SOURCE, 400, 900)); + +test("locate finds an excerpt inside a longer signal to the sample", () => { + const probe = slice(SOURCE, 100, 110); + const search = slice(TARGET, 80, 140); + const hit = locate(probe, search, { guard: SR / 4 }); + assert.ok(hit); + // SOURCE 100 is TARGET 102.5; the search starts at 80. + assert.equal(hit.lag, Math.round(22.5 * SR)); + assert.ok(hit.score > 0.99, `score ${hit.score}`); + assert.ok(hit.second < 0.2, `second ${hit.second}`); +}); + +test("locate gives up on silence", () => { + assert.equal(locate(new Float32Array(SR * 2), slice(TARGET, 0, 10)), null); +}); + +test("anchors every step, plus the extra seconds, inside the probe's reach", () => { + const t = anchorTimes(1000, { everySeconds: 300, probeSeconds: 20, extra: [5, 512, 513] }); + assert.deepEqual(t, [10, 150, 450, 512, 750, 990]); +}); + +test("a step inside the stream: two segments, a gap, refined until narrow", () => { + const o = { probeSeconds: 10, searchSeconds: 20, everySeconds: 120, minGapSeconds: 10 }; + let anchors = measureAll(SOURCE, TARGET, anchorTimes(900, { ...o }), o); + let fit = fitClock(anchors, o); + assert.equal(fit.segments.length, 2); + assert.equal(fit.gaps.length, 1); + for (let pass = 0; pass < 4; pass += 1) { + const more = refineTimes(fit, o); + if (!more.length) break; + anchors = [...anchors, ...measureAll(SOURCE, TARGET, more, o)]; + fit = fitClock(anchors, o); + } + assert.equal(fit.ok, true, fit.why); + assert.equal(fit.segments.length, 2); + assert.ok(Math.abs(fit.segments[0].offset - 2.5) < 0.001, `first ${fit.segments[0].offset}`); + assert.ok(Math.abs(fit.segments[1].offset - 13.1) < 0.001, `second ${fit.segments[1].offset}`); + const g = fit.gaps[0]; + // The step is at source 400: the gap holds it, and is at most minGap plus a + // probe (half a probe beyond either anchor) wide. + assert.ok(g.from < 400 && g.to > 400, JSON.stringify(g)); + assert.ok(g.to - g.from <= 10 + 10, JSON.stringify(g)); + assert.ok((fit.residual.rms ?? 1) < 0.001); +}); + +test("a drift is one segment with a rate, and the map follows it", () => { + // 40 ms per hour of drift on top of +1.6 s, as two sound cards would. + const rate = 0.04 / 3600; + const anchors = [30, 330, 630, 930, 1230, 1530].map((at) => ({ at, offset: 1.6 + rate * at, ok: true })); + const fit = fitClock(anchors); + assert.equal(fit.segments.length, 1); + assert.ok(Math.abs(fit.segments[0].rate - rate) < 1e-9); + const clock = clockOf(fit); + assert.ok(Math.abs(clockOffsetAt(clock, 1000).offset - (1.6 + rate * 1000)) < 1e-4); +}); + +test("one anchor that disagrees between two that agree is an outlier, not a step", () => { + const anchors = [ + { at: 100, offset: 2, ok: true }, + { at: 400, offset: 2, ok: true }, + { at: 700, offset: 9.7, ok: true }, + { at: 1000, offset: 2, ok: true }, + { at: 1300, offset: 2.01, ok: true }, + ]; + const fit = fitClock(anchors); + assert.equal(fit.segments.length, 1); + assert.deepEqual(fit.outliers, [700]); + assert.equal(fit.ok, true); +}); + +test("a stream that does not match is not ok, and says why", () => { + const other = speech(900, 4242); + const o = { probeSeconds: 10, searchSeconds: 20, everySeconds: 120 }; + const anchors = measureAll(SOURCE, other, anchorTimes(900, o), o); + assert.ok(anchors.every((a) => !a.ok)); + const fit = fitClock(anchors, o); + assert.equal(fit.ok, false); + assert.match(fit.why ?? "", /usable anchor|no anchor/); +}); + +function clockOf(fit: ReturnType<typeof fitClock>, extra: Partial<RecordingClock> = {}): RecordingClock { + return { + version: 1, + id: "t", + createdAt: "2026-11-06T00:00:00.000Z", + source: { file: "audio.mp3", bytes: 10 }, + target: { file: "source-media.mp4", bytes: 20 }, + method: "xcorr", + params: {}, + anchors: [], + segments: fit.segments, + gaps: fit.gaps, + residual: fit.residual, + ok: fit.ok, + ...extra, + }; +} + +test("mapSpan: a span on one segment maps with its offset; across the step it is uncertain", () => { + const clock = clockOf({ + segments: [ + { from: 60, to: 395, offset: 2.5, rate: 0, n: 4, rms: 0 }, + { from: 405, to: 840, offset: 13.1, rate: 0, n: 4, rms: 0 }, + ], + gaps: [{ from: 395, to: 405 }], + outliers: [], + residual: { rms: 0, max: 0, n: 8 }, + ok: true, + }); + assert.deepEqual(mapSpan(clock, 100, 110), { from: 102.5, to: 112.5, offsetFrom: 2.5, offsetTo: 2.5, certain: true }); + assert.deepEqual(mapSpan(clock, 600, 610), { from: 613.1, to: 623.1, offsetFrom: 13.1, offsetTo: 13.1, certain: true }); + // Before the first anchor and after the last: the edge segment's value. + assert.equal(mapSpan(clock, 0, 5).certain, true); + assert.equal(clockOffsetAt(clock, 890).offset, 13.1); + // Inside the gap, or across it: not certain. + assert.equal(mapSpan(clock, 398, 402).certain, false); + assert.equal(mapSpan(clock, 390, 420).certain, false); + // A map that is not ok maps nothing with confidence. + assert.equal(mapSpan({ ...clock, ok: false }, 100, 110).certain, false); +}); + +test("the file's shape: coerce, matches, describe", () => { + const clock = clockOf({ + segments: [{ from: 60, to: 840, offset: 13.1, rate: 0, n: 4, rms: 0.0004 }], + gaps: [], + outliers: [], + residual: { rms: 0.0004, max: 0.0009, n: 4 }, + ok: true, + }); + assert.deepEqual(coerceRecordingClock(JSON.parse(JSON.stringify(clock))), clock); + assert.equal(coerceRecordingClock({ ...clock, version: 2 }), null); + assert.equal(coerceRecordingClock({ ...clock, segments: [{ from: 1 }] }), null); + assert.equal(coerceRecordingClock(null), null); + assert.equal(clockMatches(clock, { sourceBytes: 10, targetBytes: 20 }), true); + assert.equal(clockMatches(clock, { targetBytes: 21 }), false); + assert.match(describeClock(clock), /^ok: \+13\.10s @60–840s; residual 0\.4 ms/); +}); diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts @@ -40,6 +40,7 @@ import { loadExcludeTruncatedCheck, setExcludedFromTruncatedCheck, } from "./excludeTruncatedCheck-server"; +import "./recordingClock-server"; import type { AvailabilityRecord } from "./availability"; import type { DownloadOutcomeRecord } from "./downloadOutcome"; import type { TranscribeOutcomeRecord } from "./transcribeOutcome"; @@ -48,7 +49,7 @@ async function scratch(): Promise<string> { return mkdtemp(path.join(os.tmpdir(), "sidecar-")); } -test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are declared", () => { +test("every declared sidecar filename escapes SUB_FILE_RE, and all eighteen are declared", () => { assert.deepEqual([...SIDECAR_FILENAMES].sort(), [ "ai-digest.json", "ai-digest.overrides.json", @@ -56,6 +57,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are "attribution.json", "audio-integrity.json", "availability.json", + "clock.json", "diarization.json", "do-not-clean.json", "download-outcome.json",