// 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); } // WHERE THE ENCODER PUT THE START (seconds the decoded file lags its input). // Not always zero: lame 4.0's gapless tag says an encoder delay of 47 samples // where the stream has 576, so ffmpeg (9.1) decodes its mp3 529 samples — // 33 ms at 16 kHz — late. The clock maps the files AS DECODED (what the // transcriber hears), so the offsets it must find are the spliced ones plus // the toolchain's lags: found here to the sample, independently of the code // under test, by matching a decoded second against the input. async function decodedLag(file: string, input: Float32Array): Promise { const r = await execa(FFMPEG, ["-v", "error", "-i", file, "-t", "3", "-ac", "1", "-ar", String(SR), "-f", "f32le", "pipe:1"], { encoding: "buffer", }); const buf = Buffer.from(r.stdout as Uint8Array); const dec = new Float32Array(Math.floor(buf.length / 4)); for (let i = 0; i < dec.length; i += 1) dec[i] = buf.readFloatLE(i * 4); const MAX = Math.round(0.2 * SR); let best = 0; let bestScore = -Infinity; for (let lag = -MAX; lag <= MAX; lag += 1) { let dot = 0; for (let k = MAX; k < MAX + SR; k += 1) dot += input[k] * (dec[k + lag] ?? 0); if (dot > bestScore) [bestScore, best] = [dot, lag]; } return best / SR; } 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 }), ); // A span's offset is its splice offset plus (target lag - source lag). const lag = (await decodedLag(path.join(store, "source-media.mp4"), tgt)) - (await decodedLag(path.join(videoDir, "audio.mp3"), src)); return { videoDir, container: path.join(store, "source-media.mp4"), lag }; } 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, lag } = await fixture(); const before = 2.5 + lag; const afterSplice = 13.1 + lag; 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). // The toolchain's lag is part of what the clock must find (decodedLag). assert.ok(Math.abs(clock.segments[0].offset - before) < 0.002, `before ${clock.segments[0].offset} (expected ${before})`); assert.ok(Math.abs(clock.segments[1].offset - afterSplice) < 0.002, `after ${clock.segments[1].offset} (expected ${afterSplice})`); 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 (each plus the // toolchain's lag), across it uncertain. assert.ok(Math.abs(clockOffsetAt(clock, 100).offset - before) < 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"); });