// The clip segment cache (segment-cache.mjs): a segment whose key matches is // reused as it is -- not rewritten, mtime held -- and any one input that // changes its picture or its sound rebuilds it. Unit tests over a stub // encoder, then tiny real builds of a `src` clip (skipped without ffmpeg). // // Run with: node --test umtool/report-to-video/segment-cache.test.mjs import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { linkSync, readFileSync, statSync } from "node:fs"; import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { HASH_CONTENT_BELOW, canonicalArgv, encodeSegmentCached, recordForKey, segmentKey, } from "./segment-cache.mjs"; import { buildVideo, setProgressMode } from "./build-video.mjs"; import { MONO_FONT_FILE } from "./brand.mjs"; const tmp = (p) => mkdtemp(path.join(os.tmpdir(), p)); // ---- the key --------------------------------------------------------------- test("canonicalArgv: the out dir is , a small file is its contents, a big one its path, size and mtime", async () => { const root = await tmp("segkey-"); try { const a = path.join(root, "a", "out"); const b = path.join(root, "b", "out"); for (const d of [a, b]) { await mkdir(path.join(d, "segments"), { recursive: true }); await writeFile(path.join(d, "segments", "x.attrib.txt"), "Channel · 1 Jan", "utf8"); } const argv = (o) => ["-i", "/nonexistent/raw.mp4", "-filter_complex", `drawtext=textfile='${o}/segments/x.attrib.txt':x=1[v]`]; const ca = await canonicalArgv(argv(a), { outDir: a }); const cb = await canonicalArgv(argv(b), { outDir: b }); assert.deepEqual(ca, cb, "two takes' out dirs key alike"); assert.ok(!ca.join(" ").includes(root)); assert.equal(ca[1], "/nonexistent/raw.mp4", "a path that is no file stays as written"); await writeFile(path.join(b, "segments", "x.attrib.txt"), "Channel · 2 Jan", "utf8"); assert.notDeepEqual(await canonicalArgv(argv(b), { outDir: b }), ca, "a text file's words are in the key"); // A source above the content limit: its path, size and mtime. const big = path.join(root, "big.mp4"); await writeFile(big, Buffer.alloc(HASH_CONTENT_BELOW + 1)); const k1 = await canonicalArgv(["-i", big], { outDir: a }); assert.match(k1[1], /^ { const base = { argv: ["-ss", "1", "-to", "2"], outDir: "/o", ffmpeg: "ffmpeg-not-on-path" }; const rec = { id: "c", start: 1, end: 2, framing: { layout: "deck", box: { width: 100 } } }; const k = await segmentKey({ ...base, record: rec }); assert.equal(await segmentKey({ ...base, record: { ...rec, segKey: "x", segSeconds: 9 } }), k); assert.notEqual(await segmentKey({ ...base, record: { ...rec, framing: { layout: "feed", box: { width: 80 } } } }), k); assert.notEqual(await segmentKey({ ...base, record: { ...rec, blur: { from: 0, to: 1 } } }), k); assert.notEqual(await segmentKey({ ...base, record: { ...rec, loudness: { gain: 2 } } }), k); assert.notEqual(await segmentKey({ ...base, argv: ["-ss", "1", "-to", "2.1"], record: rec }), k); assert.deepEqual(recordForKey({ a: 1, segKey: "k", segSeconds: 2 }), { a: 1 }); }); // ---- encodeSegmentCached over a stub encoder ----------------------------- function stubEncoder(bytes = () => "frames") { const calls = []; return { calls, exec: async (_bin, argv) => { calls.push(argv); await writeFile(argv[argv.length - 1], bytes(calls.length), "utf8"); }, probe: async () => 2, }; } test("encodeSegmentCached: no key → built; same key → reused, mtime unchanged; a changed input → rebuilt", async () => { const root = await tmp("segcache-"); try { const segs = path.join(root, "out", "segments"); await mkdir(segs, { recursive: true }); const seg = path.join(segs, "c.mp4"); // A segment from before keys: a file and a record with no segKey. await writeFile(seg, "old frames", "utf8"); await writeFile(path.join(segs, "c.cut.json"), JSON.stringify({ id: "c", start: 1, end: 3 }), "utf8"); let n = 0; const enc = stubEncoder(() => `frames ${++n}`); const notes = []; const run = (record, argv = ["-ss", "1", "-to", "3"]) => encodeSegmentCached({ seg, argv: [...argv, seg], record, outDir: path.join(root, "out"), fps: 30, ffmpeg: "ffmpeg-stub", exec: enc.exec, probe: enc.probe, emit: (_ev, f) => notes.push(f.message), }); const rec = { id: "c", start: 1, end: 3 }; const first = await run(rec); assert.equal(first.reused, false); assert.equal(enc.calls.length, 1, "a record with no key is rebuilt"); assert.equal(readFileSync(seg, "utf8"), "frames 1"); const written = JSON.parse(await readFile(path.join(segs, "c.cut.json"), "utf8")); assert.equal(written.segKey, first.key); assert.equal(written.segSeconds, 2); const before = statSync(seg); const again = await run(rec); assert.equal(again.reused, "key"); assert.equal(enc.calls.length, 1, "no encode"); assert.equal(statSync(seg).mtimeMs, before.mtimeMs); assert.equal(statSync(seg).ino, before.ino); assert.match(notes.at(-1), /c: segment unchanged \(key [0-9a-f]{12}\)/); await run({ ...rec, end: 3.2 }, ["-ss", "1", "-to", "3.2"]); assert.equal(enc.calls.length, 2, "the cut's end rebuilds it"); await run({ ...rec, end: 3.2, blur: { from: 0, to: 1 } }, ["-ss", "1", "-to", "3.2"]); assert.equal(enc.calls.length, 3, "the blur rebuilds it"); // A file that no longer probes to its recorded length is rebuilt. enc.probe = async (f) => (f === seg ? 0.4 : 2); await run({ ...rec, end: 3.2, blur: { from: 0, to: 1 } }, ["-ss", "1", "-to", "3.2"]); assert.equal(enc.calls.length, 4); } finally { await rm(root, { recursive: true, force: true }); } }); test("encodeSegmentCached: the same bytes again keep the file on disk; a rebuild replaces a hard link, never writes through it", async () => { const root = await tmp("segcache-link-"); try { const other = path.join(root, "other", "segments"); const mine = path.join(root, "mine", "segments"); await mkdir(other, { recursive: true }); await mkdir(mine, { recursive: true }); await writeFile(path.join(other, "c.mp4"), "same frames", "utf8"); await writeFile(path.join(other, "c.cut.json"), JSON.stringify({ id: "c" }) + "\n", "utf8"); const seg = path.join(mine, "c.mp4"); linkSync(path.join(other, "c.mp4"), seg); linkSync(path.join(other, "c.cut.json"), path.join(mine, "c.cut.json")); const before = statSync(seg); // No key on record: encoded again, to the same bytes -- the linked file stays. const same = stubEncoder(() => "same frames"); const r = await encodeSegmentCached({ seg, argv: ["-x", seg], record: { id: "c" }, outDir: path.join(root, "mine"), fps: 30, ffmpeg: "ffmpeg-stub", exec: same.exec, probe: same.probe, }); assert.equal(r.reused, "bytes"); assert.equal(statSync(seg).ino, before.ino); assert.equal(statSync(seg).mtimeMs, before.mtimeMs); // Its record was replaced through a rename: the other take's is as it was. assert.deepEqual(JSON.parse(readFileSync(path.join(other, "c.cut.json"), "utf8")), { id: "c" }); assert.ok(JSON.parse(readFileSync(path.join(mine, "c.cut.json"), "utf8")).segKey); // Other bytes: a new file of this take's own; the other take's untouched. const diff = stubEncoder(() => "new frames"); await encodeSegmentCached({ seg, argv: ["-y", seg], record: { id: "c" }, outDir: path.join(root, "mine"), fps: 30, ffmpeg: "ffmpeg-stub", exec: diff.exec, probe: diff.probe, }); assert.equal(readFileSync(seg, "utf8"), "new frames"); assert.equal(readFileSync(path.join(other, "c.mp4"), "utf8"), "same frames"); assert.notEqual(statSync(seg).ino, before.ino); } finally { await rm(root, { recursive: true, force: true }); } }); // ---- real builds ----------------------------------------------------------- const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" }; const RENDER = { width: 320, height: 180, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0, headerHeight: 24, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_FONT_FILE, }; async function srcProject() { const root = await tmp("segcache-build-"); await mkdir(path.join(root, "media"), { recursive: true }); const mp4 = path.join(root, "media", "talk.mp4"); const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=320x180:rate=30:d=4", "-f", "lavfi", "-i", "sine=f=330:r=48000:d=4", "-shortest", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", mp4, ]); assert.equal(r.status, 0, String(r.stderr)); const manifestPath = path.join(root, "video.manifest.json"); const write = (clip = {}, render = {}) => writeFile(manifestPath, JSON.stringify({ slug: "demo", title: "Demo", render: { ...RENDER, ...render }, timeline: [{ id: "c1", type: "clip", src: "media/talk.mp4", start: 0.5, end: 3, title: "Talk", channelTitle: "Demo", date: "2026-01-02", ...clip }], })); await write(); return { root, manifestPath, write, mp4, seg: path.join(root, "out", "sourced", "segments", "c1.mp4") }; } test("a real build: an unchanged clip's segment is reused; its end, blur, render.blur, framing and source each rebuild it", { skip: !have && "needs ffmpeg and ffprobe" }, async () => { const notes = []; setProgressMode((e) => { if (e.ev === "note") notes.push(e.message); }); const p = await srcProject(); try { const build = async () => { const r = await buildVideo({ manifestPath: p.manifestPath, only: "c1", opts: { noNetwork: true } }); assert.equal(r.failures.length, 0); return statSync(p.seg); }; const reusedLast = () => /c1: segment unchanged/.test(notes.at(-1) ?? ""); const s0 = await build(); const s1 = await build(); assert.ok(reusedLast(), notes.slice(-3).join(" | ")); assert.equal(s1.mtimeMs, s0.mtimeMs, "not rewritten"); assert.equal(s1.ino, s0.ino); const changed = async (what, clip, render) => { await p.write(clip, render); notes.length = 0; const before = statSync(p.seg); const after = await build(); assert.ok(!notes.some((m) => /c1: segment unchanged/.test(m)), `${what}: reused (${notes.join(" | ")})`); assert.notEqual(after.mtimeMs, before.mtimeMs, `${what}: rewritten`); // And again, unchanged: reused. notes.length = 0; const third = await build(); assert.ok(notes.some((m) => /c1: segment unchanged/.test(m)), `${what}, again: reused`); assert.equal(third.mtimeMs, after.mtimeMs); }; await changed("the cut's end", { end: 2.6 }); await changed("a blur", { end: 2.6, blur: { on: true } }); await changed("render.blur off", { end: 2.6, blur: { on: true } }, { blur: "off" }); await changed("the framing (a taller header)", { end: 2.6 }, { headerHeight: 40 }); await changed("the deck's framing", { end: 2.6 }, { headerHeight: undefined, width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }); // The source itself, other bytes under the same name. const r = spawnSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30:d=4", "-f", "lavfi", "-i", "sine=f=440:r=48000:d=4", "-shortest", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", p.mp4, ]); assert.equal(r.status, 0, String(r.stderr)); notes.length = 0; const before = statSync(p.seg); const after = await build(); assert.ok(!notes.some((m) => /c1: segment unchanged/.test(m)), "a new source: reused"); assert.notEqual(after.mtimeMs, before.mtimeMs); // --no-segment-cache always encodes. notes.length = 0; await buildVideo({ manifestPath: p.manifestPath, only: "c1", opts: { noNetwork: true, noSegmentCache: true } }); assert.ok(!notes.some((m) => /c1: segment unchanged/.test(m))); // ...and the encoder is deterministic: the same run makes the same bytes, so the file on disk is kept. assert.ok(notes.some((m) => /c1: segment re-encoded to the same bytes/.test(m)), notes.join(" | ")); } finally { setProgressMode("human"); await rm(p.root, { recursive: true, force: true }); } });