import { test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; import { mkdtempSync, openAsBlob, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CLIP_ENGINE_MARK, ClipCancelled, ClipTooBig, HELD_PAST_OUT_MAX, clipVideoPackets, outputSupport, probeClip, saveClip, } from "./localClipEngine"; import { EncodedPacket, MkvOutputFormat, MovOutputFormat, Mp4OutputFormat, WebMOutputFormat } from "mediabunny"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test lib/localClipEngine.test.ts // // The stream copy itself, in Node over a Blob of a file ffmpeg makes here // (keyframes every 2.0 s, B-frames in the H.264 one), checked with ffprobe: // the codecs are the source's (nothing re-encoded), the clip starts on a key // frame at the keyframe the probe named, lasts out − keyframe, and its audio // and video start within one audio frame of each other. Skipped, with the // reason, on a machine with no ffmpeg. function has(cmd: string): boolean { try { execFileSync(cmd, ["-version"], { stdio: "ignore" }); return true; } catch { return false; } } const FFMPEG = has("ffmpeg") && has("ffprobe"); const skip = FFMPEG ? false : "ffmpeg/ffprobe not on PATH"; const dir = mkdtempSync(join(tmpdir(), "local-clip-engine-")); process.on("exit", () => rmSync(dir, { recursive: true, force: true })); const SOURCES = { mp4: [ "-c:v", "libx264", "-profile:v", "main", "-bf", "2", "-g", "50", "-keyint_min", "50", "-sc_threshold", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "64k", ], webm: [ "-c:v", "libvpx-vp9", "-g", "50", "-keyint_min", "50", "-deadline", "realtime", "-cpu-used", "8", "-b:v", "200k", "-c:a", "libopus", "-b:a", "48k", ], } as const; const TESTSRC = ["-f", "lavfi", "-i", "testsrc2=size=160x90:rate=25:duration=12"]; const TONE = ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=12"]; function make(kind: keyof typeof SOURCES, extra: string[] = [], name = `source.${kind}`): string { const out = join(dir, name); execFileSync("ffmpeg", ["-v", "error", "-y", ...TESTSRC, ...TONE, ...SOURCES[kind], ...extra, "-shortest", out]); return out; } // Black video with ONE white frame at 6.00 s, silence with ONE 1 kHz beep // from 6.00 s: a clip that shifted its audio against its video is caught by // where the flash and the beep land. function makeFlashBeep(kind: keyof typeof SOURCES): string { const out = join(dir, `flash-beep.${kind}`); execFileSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=160x90:r=25:d=12,drawbox=x=0:y=0:w=iw:h=ih:color=white:t=fill:enable='between(t,5.99,6.01)'", "-f", "lavfi", "-i", "aevalsrc='0.8*sin(2*PI*1000*t)*between(t,6,6.2)':s=48000:d=12", ...SOURCES[kind], "-shortest", out, ]); return out; } // Where, on the clip's own clock, the first bright frame is and the beep starts. function flashAndBeep(path: string): { flash: number; beep: number } { const v = execFileSync("ffmpeg", ["-v", "error", "-i", path, "-an", "-vf", "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"], { encoding: "utf8", }); let flash = NaN; let pts = NaN; for (const line of v.split("\n")) { const t = /pts_time:([\d.]+)/.exec(line); if (t) pts = Number(t[1]); const y = /YAVG=([\d.]+)/.exec(line); if (y && Number(y[1]) > 128 && Number.isNaN(flash)) flash = pts; } // silencedetect reports on stderr. const err = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", path, "-vn", "-af", "silencedetect=n=-30dB:d=0.05", "-f", "null", "-"], { encoding: "utf8", }).stderr; const end = /silence_end: ([\d.]+)/.exec(err); return { flash, beep: end ? Number(end[1]) : NaN }; } async function saveToFile(src: Blob, plan: Parameters[1], name: string): Promise { const saved = await saveClip(src, plan, { kind: "memory" }, () => {}, new AbortController().signal); const out = join(dir, name); writeFileSync(out, Buffer.from(await saved.blob!.arrayBuffer())); return out; } type Probe = { streams: { codec_type: string; codec_name: string; start_time: string; duration?: string }[]; format: { duration: string } }; function ffprobe(path: string): Probe { return JSON.parse( execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,start_time,duration:format=duration", "-of", "json", path], { encoding: "utf8", }), ); } function firstFrameIsKey(path: string): boolean { const out = execFileSync( "ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "frame=key_frame", "-read_intervals", "%+#1", "-of", "csv=p=0", path], { encoding: "utf8" }, ); return out.trim().split("\n")[0]?.trim() === "1"; } test("the output support handed to the pure module is the library's own", () => { const s = outputSupport(); assert.deepEqual(s.mp4, new Mp4OutputFormat().getSupportedCodecs()); assert.deepEqual(s.mov, new MovOutputFormat().getSupportedCodecs()); assert.deepEqual(s.mkv, new MkvOutputFormat().getSupportedCodecs()); assert.deepEqual(s.webm, new WebMOutputFormat().getSupportedCodecs()); }); for (const kind of ["mp4", "webm"] as const) { test(`${kind}: a stream copy from the keyframe before the in mark`, { skip }, async () => { const src = await openAsBlob(make(kind)); // Marks 5.0 → 9.0 on the cue clock, no offset: the keyframe is 4.0. const probe = await probeClip(src, 5, 9, 0); assert.ok(probe.ok, JSON.stringify(probe)); if (!probe.ok) return; const { plan } = probe; assert.equal(plan.format, kind); assert.equal(plan.ext, `.${kind}`); assert.ok(Math.abs(plan.startTs - 4) < 0.05, `keyframe at ${plan.startTs}`); assert.equal(plan.fileIn, 5); assert.equal(plan.fileOut, 9); assert.equal(plan.endTs, 9); assert.ok(Math.abs(plan.fileStart) < 0.05, `the copy begins at ${plan.fileStart}`); assert.ok(plan.duration !== null && Math.abs(plan.duration - 12) < 0.1); assert.equal(plan.hasVideo, true); assert.equal(plan.hasAudio, true); assert.equal(plan.extraTracks, false); const progress: number[] = []; const saved = await saveClip(src, plan, { kind: "memory" }, (p) => progress.push(p.fraction), new AbortController().signal); assert.ok(saved.blob); assert.ok(saved.bytes > 0); assert.equal(saved.blob!.size, saved.bytes); assert.ok(progress.length > 0 && progress.at(-1)! >= 0.95, `progress ${progress.at(-1)}`); const out = join(dir, `clip.${kind}`); writeFileSync(out, Buffer.from(await saved.blob!.arrayBuffer())); const info = ffprobe(out); const v = info.streams.find((s) => s.codec_type === "video")!; const a = info.streams.find((s) => s.codec_type === "audio")!; // Copied, not re-encoded. assert.equal(v.codec_name, kind === "mp4" ? "h264" : "vp9"); assert.equal(a.codec_name, kind === "mp4" ? "aac" : "opus"); assert.ok(firstFrameIsKey(out), "the first frame is a key frame"); // out − keyframe = 5.0 s, give or take a frame. const duration = Number(info.format.duration); assert.ok(Math.abs(duration - 5) < 0.12, `duration ${duration}`); // A/V in step at the cut: the two start within one audio frame (AAC 1024 // samples at 48 kHz ≈ 21.3 ms; Opus 20 ms). const gap = Math.abs(Number(v.start_time) - Number(a.start_time)); assert.ok(gap <= 0.0215, `video starts at ${v.start_time}, audio at ${a.start_time}`); }); } test("an offset moves the in mark onto a keyframe: the clip starts at the mark", { skip }, async () => { const src = await openAsBlob(make("webm")); // Cue 5.0 + offset 1 = file 6.0, a keyframe. const probe = await probeClip(src, 5, 9, 1); assert.ok(probe.ok); if (!probe.ok) return; assert.equal(probe.plan.fileIn, 6); assert.equal(probe.plan.fileOut, 10); assert.ok(Math.abs(probe.plan.startTs - 6) < 0.05, `keyframe at ${probe.plan.startTs}`); }); test("marks outside the file, and a file that is not a container it reads, are refused", { skip }, async () => { const src = await openAsBlob(make("mp4")); const outside = await probeClip(src, 20, 25, 0); assert.deepEqual(outside.ok ? null : outside.refusal.kind, "outside"); const wav = join(dir, "tone.wav"); execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=2", wav]); const notOurs = await probeClip(await openAsBlob(wav), 0.5, 1.5, 0); assert.deepEqual(notOurs.ok ? null : notOurs.refusal, { kind: "container" }); }); test("cancel stops the copy, aborts the disk writer and never closes (commits) it", { skip }, async () => { const src = await openAsBlob(make("mp4")); const probe = await probeClip(src, 1, 11, 0); assert.ok(probe.ok); if (!probe.ok) return; const calls: string[] = []; const writable = new WritableStream({ async write() { calls.push("write"); await new Promise((r) => setTimeout(r, 20)); }, close() { calls.push("close"); }, abort() { calls.push("abort"); }, }); const ac = new AbortController(); const run = saveClip(src, probe.plan, { kind: "disk", writable }, (p) => { if (p.fraction > 0.2) ac.abort(); }, ac.signal); await assert.rejects(run, ClipCancelled); assert.ok(calls.includes("abort"), calls.join(",")); assert.ok(!calls.includes("close"), calls.join(",")); }); test("cancel while a read is in flight answers at once, and hands back no clip", { skip }, async () => { const path = join(dir, "heavy.webm"); execFileSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=25:duration=20", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=20", "-vf", "noise=alls=80:allf=t", ...SOURCES.webm, "-b:v", "4M", "-minrate", "4M", "-maxrate", "4M", "-shortest", path, ]); const src = await openAsBlob(path); // The file reads slowly (100 ms per 64 KiB), as from a slow disk. const orig = Blob.prototype.stream; Blob.prototype.stream = function (this: Blob) { const reader = orig.call(this).getReader(); return new ReadableStream({ async pull(c) { const { done, value } = await reader.read(); if (done) return c.close(); await new Promise((r) => setTimeout(r, Math.ceil(value.byteLength / 65536) * 100)); c.enqueue(value); }, cancel: (r) => reader.cancel(r), }); } as typeof Blob.prototype.stream; try { const probe = await probeClip(src, 2, 19, 0); assert.ok(probe.ok); if (!probe.ok) return; const ac = new AbortController(); const run = saveClip(src, probe.plan, { kind: "memory" }, () => {}, ac.signal); await new Promise((r) => setTimeout(r, 400)); const at = Date.now(); ac.abort(); await assert.rejects(run, ClipCancelled); assert.ok(Date.now() - at < 300, `cancel took ${Date.now() - at} ms`); } finally { Blob.prototype.stream = orig; } }); for (const kind of ["mp4", "webm"] as const) { test(`${kind}: a flash and a beep at 6.0 s land together at 2.0 s in a clip from the 4.0 s keyframe`, { skip }, async () => { const src = await openAsBlob(makeFlashBeep(kind)); const probe = await probeClip(src, 5, 9, 0); assert.ok(probe.ok, JSON.stringify(probe)); if (!probe.ok) return; assert.ok(Math.abs(probe.plan.startTs - 4) < 0.05); const { flash, beep } = flashAndBeep(await saveToFile(src, probe.plan, `flash-beep-clip.${kind}`)); // One video frame is 40 ms; the beep's onset is within an audio frame. assert.ok(Math.abs(flash - 2) <= 0.045, `the flash is at ${flash}`); assert.ok(Math.abs(beep - 2) <= 0.03, `the beep is at ${beep}`); assert.ok(Math.abs(flash - beep) <= 0.045, `flash ${flash}, beep ${beep}`); }); } test("video only (H.264, no audio): a clip from the keyframe", { skip }, async () => { const src = await openAsBlob(make("mp4", ["-an"], "video-only.mp4")); const probe = await probeClip(src, 5, 9, 0); assert.ok(probe.ok, JSON.stringify(probe)); if (!probe.ok) return; assert.equal(probe.plan.hasAudio, false); assert.equal(probe.plan.ext, ".mp4"); const info = ffprobe(await saveToFile(src, probe.plan, "video-only-clip.mp4")); assert.deepEqual(info.streams.map((s) => s.codec_name), ["h264"]); assert.ok(Math.abs(Number(info.format.duration) - 5) < 0.12, info.format.duration); }); for (const [name, args, ext, codec] of [ ["audio-only.m4a", ["-vn", "-c:a", "aac", "-b:a", "64k"], ".m4a", "aac"], ["audio-only.webm", ["-vn", "-c:a", "libopus", "-b:a", "48k"], ".webm", "opus"], ] as const) { test(`audio only (${codec}): a clip from the in mark, within one audio frame`, { skip }, async () => { const path = join(dir, name); execFileSync("ffmpeg", ["-v", "error", "-y", ...TONE, ...args, path]); const src = await openAsBlob(path); const probe = await probeClip(src, 5, 9, 0); assert.ok(probe.ok, JSON.stringify(probe)); if (!probe.ok) return; assert.equal(probe.plan.hasVideo, false); assert.equal(probe.plan.ext, ext); assert.ok(probe.plan.startTs <= 5 && 5 - probe.plan.startTs < 0.025, `starts at ${probe.plan.startTs}`); const info = ffprobe(await saveToFile(src, probe.plan, `clip-${name}`)); assert.deepEqual(info.streams.map((s) => s.codec_name), [codec]); assert.ok(Math.abs(Number(info.format.duration) - 4) < 0.06, info.format.duration); }); } for (const kind of ["mp4", "webm"] as const) { test(`${kind}: a copy whose first timestamp is 3 s is clipped on its own (the