// The snapshot and the clock of a recording IN PROGRESS, on real files: an // MPEG-TS (the muxed recorders) and a separate fMP4 video + audio pair // (YouTube's), each written in increments at arbitrary byte boundaries the way // a recorder appends, with a 1 kHz burst at a known second of the stream. // Tiny (160x90, 90 s), and skipped where ffmpeg has no libx264. import { test } from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; import { tmpdir } from "node:os"; import { appendFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { execa } from "execa"; import { windowWavArgs } from "./transcribeFile"; import type { LiveRecordingRecord } from "../lib/liveCapture"; import { cutLiveWindow, findLiveSource, liveWindowCutArgs, probeWith, readEnvelope } from "../lib/livePreclip-server"; import { compareEnvelopes, envelopeOf, judgeClock, planTick } from "../lib/livePreclip"; const ROOT = await mkdtemp(path.join(tmpdir(), "live-preclip-")); const FF = process.env.FFMPEG_BIN ?? "ffmpeg"; const FP = process.env.FFPROBE_BIN ?? "ffprobe"; const probe = probeWith(FP); const BURST_AT = 47; const AUDIO = `aevalsrc='if(between(t,${BURST_AT},${BURST_AT}.5),0.8*sin(2*PI*1000*t),0.05*sin(2*PI*220*t)*(1+sin(2*PI*0.7*t)))':s=16000:d=90`; let haveX264 = true; const ts = path.join(ROOT, "src.ts"); const fv = path.join(ROOT, "src-video.mp4"); const fa = path.join(ROOT, "src-audio.m4a"); try { // A stream whose clock does not start at 0 (a TS's first PTS is wherever // the broadcast's was): -output_ts_offset. await execa(FF, [ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=90", "-f", "lavfi", "-i", AUDIO, "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-c:a", "aac", "-b:a", "48k", "-output_ts_offset", "1000", "-f", "mpegts", ts, ]); await execa(FF, ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=90", "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", fv]); await execa(FF, ["-v", "error", "-y", "-f", "lavfi", "-i", AUDIO, "-c:a", "aac", "-b:a", "48k", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-frag_duration", "2000000", "-f", "mp4", fa]); } catch { haveX264 = false; } /** A recorder, appending `src` to `dst` in pieces cut at arbitrary bytes. */ async function grower(src: string, dst: string) { const bytes = await readFile(src); let at = 0; await writeFile(dst, Buffer.alloc(0)); return async (share: number) => { const to = Math.min(bytes.length, Math.floor(bytes.length * share) + 37); if (to > at) await appendFile(dst, bytes.subarray(at, to)); at = to; }; } const peakAt = (env: number[], hop = 0.1) => env.indexOf(Math.max(...env)) * hop; function recording(stem: string): LiveRecordingRecord { return { status: "recording", url: "https://example.com/live", platform: "youtube", fromStart: true, startedAt: "2026-10-27T12:00:00Z", parts: [{ method: "ytdlp", url: "https://example.com/live", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }], }; } test("a growing MPEG-TS: its length grows, a span is read by time on the landed clock", async (t) => { if (!haveX264) return t.skip("no ffmpeg with libx264 here"); const store = path.join(ROOT, "ts-store"); await mkdir(store, { recursive: true }); const stem = ".vid1.live-2026-10-27T12-00-00-000Z.ytdlp"; const part = path.join(store, `${stem}.ts`); const grow = await grower(ts, part); await grow(0.4); const src = await findLiveSource({ slugStore: store, id: "vid1", record: recording(stem), probe }); assert.ok(!("wait" in src), JSON.stringify(src)); if ("wait" in src) return; assert.equal(src.kind, "muxed"); assert.equal(src.audioPath, part); const early = (await probe(part))!.seconds!; assert.ok(early > 25 && early < 45, `40% of 90 s reads as ${early}`); await grow(1); const full = (await probe(part))!.seconds!; assert.ok(full > 88, `the whole stream reads as ${full}`); // The tick after the first: from 15 s before what was transcribed. const plan = planTick({ transcribedTo: 40, recordedSeconds: full, opts: { maxChunkMinutes: 20, overlapSeconds: 15 } }); assert.equal(plan.action, "transcribe"); if (plan.action !== "transcribe") return; assert.equal(plan.from, 25); const wav = path.join(ROOT, "ts-span.wav"); await execa(FF, windowWavArgs(part, wav, { start: plan.from, end: plan.to })); const env = envelopeOf(await decodeWav(wav), 16000); // The burst at 47 s of the stream is 22 s into a span from 25 s — so second // S of the growing file is second S of the stream, whatever its first PTS. assert.ok(Math.abs(peakAt(env) + plan.from - BURST_AT) < 0.25, `burst at ${peakAt(env) + plan.from}`); // The landing remuxes `-c copy` to mp4 (no -copyts): the burst is at 47 s there too. const landed = path.join(ROOT, "landed.mp4"); await execa(FF, ["-v", "error", "-y", "-i", part, "-map", "0:v?", "-map", "0:a?", "-c", "copy", "-movflags", "+faststart", "-f", "mp4", landed]); const landedEnv = (await readEnvelope(landed, 40, 15, FF))!; assert.ok(Math.abs(peakAt(landedEnv) + 40 - BURST_AT) < 0.25, `landed burst at ${peakAt(landedEnv) + 40}`); // And the clock check says so: the same span, fingerprinted on the growing // file and on the landed one. const ref = (await readEnvelope(part, 40, 15, FF))!; const probed = (await readEnvelope(landed, 38, 19, FF))!; assert.equal(judgeClock(compareEnvelopes(ref, probed, 20), 0.1, new Date()).verdict, "same"); // A window cut now from the growing file: picture and sound, the burst 2 s in. const videoDir = path.join(ROOT, "ts-video-dir"); const win = await cutLiveWindow({ ffmpegBin: FF, videoDir, source: src, from: 45, to: 52, requestedBy: "test" }); assert.equal(win.file, "45.00-52.00.mp4"); const p = await probe(win.path); assert.ok(p?.hasVideo && p.hasAudio); assert.ok(Math.abs(p!.seconds! - 7) < 0.3, `window of ${p!.seconds} s`); const wenv = (await readEnvelope(win.path, 0, 7, FF))!; assert.ok(Math.abs(peakAt(wenv) - 2) < 0.25, `window burst at ${peakAt(wenv)}`); // The picture from the window's first second (a TS seeks by timestamp, not // to a keyframe: the cut's run-up is what keeps the first GOP). const starts = await execa(FP, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", win.path]); assert.ok(Number(String(starts.stdout).trim()) < 0.2, `picture starts at ${starts.stdout}`); const side =JSON.parse(await readFile(path.join(videoDir, "clips", "45.00-52.00.json"), "utf8")); assert.equal(side.source, "live-recording"); }); test("a growing separate pair: the audio stream is read, the window takes both", async (t) => { if (!haveX264) return t.skip("no ffmpeg with libx264 here"); const store = path.join(ROOT, "pair-store"); await mkdir(store, { recursive: true }); const stem = ".vid2.live-2026-10-27T12-00-00-000Z.ytdlp"; const video = path.join(store, `${stem}.f270.mp4`); const audio = path.join(store, `${stem}.f234.mp4`); const gv = await grower(fv, video); const ga = await grower(fa, audio); for (const share of [0.2, 0.55, 1]) { await gv(share); await ga(share); const src = await findLiveSource({ slugStore: store, id: "vid2", record: recording(stem), probe }); assert.ok(!("wait" in src), JSON.stringify(src)); if ("wait" in src) return; assert.equal(src.kind, "separate"); assert.equal(src.audioPath, audio); assert.equal(src.videoPath, video); } const seconds = (await probe(audio))!.seconds!; assert.ok(seconds > 85, `audio reads ${seconds}`); const wav = path.join(ROOT, "pair-span.wav"); await execa(FF, windowWavArgs(audio, wav, { start: 40, end: 60 })); const env = envelopeOf(await decodeWav(wav), 16000); assert.ok(Math.abs(peakAt(env) + 40 - BURST_AT) < 0.25, `burst at ${peakAt(env) + 40}`); const args = liveWindowCutArgs(video, audio, 45, 52, "out.mp4"); assert.deepEqual(args.filter((a) => a === "-i").length, 2); assert.ok(args.includes("1:a:0")); const videoDir = path.join(ROOT, "pair-video-dir"); const src = await findLiveSource({ slugStore: store, id: "vid2", record: recording(stem), probe }); if ("wait" in src) return; const win = await cutLiveWindow({ ffmpegBin: FF, videoDir, source: src, from: 45, to: 52, requestedBy: "test" }); const p = await probe(win.path); assert.ok(p?.hasVideo && p.hasAudio, JSON.stringify(p)); const wenv = (await readEnvelope(win.path, 0, 7, FF))!; assert.ok(Math.abs(peakAt(wenv) - 2) < 0.25, `window burst at ${peakAt(wenv)}`); }); test("findLiveSource: an ended part is not followed; nothing written yet is a wait", async () => { const store = path.join(ROOT, "wait-store"); await mkdir(store, { recursive: true }); const stem = ".vid3.live-2026-10-27T12-00-00-000Z.ytdlp"; const rec = recording(stem); assert.deepEqual(await findLiveSource({ slugStore: store, id: "vid3", record: rec, probe }), { wait: "the recorder has written nothing yet" }); await writeFile(path.join(store, `${stem}.ts`), "not media"); const unreadable = await findLiveSource({ slugStore: store, id: "vid3", record: rec, probe }); assert.ok("wait" in unreadable && /no audio ffprobe can read/.test(unreadable.wait)); const ended = { ...rec, parts: [{ ...rec.parts[0]!, endedAt: "2026-10-27T13:00:00Z" }] }; assert.deepEqual(await findLiveSource({ slugStore: store, id: "vid3", record: ended, probe }), { wait: "no part is being recorded" }); }); /** A 16 kHz mono s16le WAV's samples. */ async function decodeWav(file: string): Promise { const buf = await readFile(file); // The data chunk: after the 44-byte header ffmpeg writes (plus a LIST chunk, sometimes). const data = buf.indexOf(Buffer.from("data")); const start = data + 8; const n = Math.floor((buf.length - start) / 2); const out = new Float32Array(n); for (let i = 0; i < n; i += 1) out[i] = buf.readInt16LE(start + i * 2) / 32768; return out; } test.after(async () => { await rm(ROOT, { recursive: true, force: true }); void stat; });