// 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("a stream that drifts 0.06 % (v6w89mk, 6 Nov) is ONE segment from its sparse first anchors", () => { // Measured: 0 s at 150 s, +4.69 s at 7827 s; the first pass anchors every 300 s. const rate = 6.128e-4; const anchors = [150, 450, 750, 1050, 1350, 1650, 1950, 4350, 7827].map((at) => ({ at, offset: Math.round((rate * (at - 150) + (at % 2 ? 0.02 : -0.02)) * 1e4) / 1e4, ok: true, })); const fit = fitClock(anchors); assert.equal(fit.segments.length, 1, JSON.stringify(fit.segments)); assert.equal(fit.ok, true, fit.why); assert.ok(Math.abs(fit.segments[0].rate - rate) < 2e-5, String(fit.segments[0].rate)); const clock = clockOf(fit); // c22's span (cue 4324.6): +2.56 s on the saved video. assert.ok(Math.abs(clockOffsetAt(clock, 4324.6).offset - 2.56) < 0.05, String(clockOffsetAt(clock, 4324.6).offset)); // A real step still splits: 13.1 s is no drift. const stepped = fitClock([...anchors.slice(0, 4), ...[2250, 2550, 2850].map((at) => ({ at, offset: 13.1 + rate * at, ok: true }))]); assert.equal(stepped.segments.length, 2); }); 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, extra: Partial = {}): 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/); });