// 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//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, maxRate: 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} */ 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 steepest drift (seconds per second) one segment may have: two sound // cards' clocks, or a stream resampled a hair off. Measured 6.13e-4 on // v6w89mk (0 s at 2:30, +4.69 s at 2:10:27). A second anchor joins a // one-anchor run within tolerance + this × the time between them. maxRate: 1e-3, // 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} 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} probe * @param {ArrayLike} 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, search: ArrayLike, searchStart: number, sampleRate: number }} a * @param {Partial} [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} [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 run too short to say. */ function fitLine(points) { const n = points.length; const t0 = points[0].at; const span = points[n - 1].at - t0; if (n < 2 || span < 60) { 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} [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); // One anchor so far says nothing of drift: the next joins it within the // drift a segment may have; after that, the run's own line decides. const allowed = run.length === 1 ? o.tolerance + o.maxRate * Math.abs(p.at - run[0].at) : o.tolerance; if (Math.abs(p.offset - lineAt(line, p.at)) <= allowed) { 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} [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, * cues?: { transcribedAt: string }, * method: "xcorr", * params: Record, * 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} */ (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}` : "") ); }