Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit c63260c093e0f5a894dc167c37f6574ef5d7e3ca
parent 455896ed3c8a59a9a51963dbfc1b2c962ce60585
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 26 Oct 2026 12:17:46 -0400

umtool: a clip segment is reused when its key matches; take --from links another take's segments, chrome frames and batches; take --keep-frames

A full build encoded every clip segment again, so every crossfade batch
over them missed too. Each clip segment now records a key in its cut
record (segKey/segSeconds, segment-cache.mjs): the exact ffmpeg argv with
every input file it names (small files by content, big ones by real path,
size and mtime), the cut record and the ffmpeg binary. A matching segment
that still probes to its length is left as it is; a rebuild goes through
a rename and keeps the old file when the bytes come out the same. The
segment texts and records are written through renames, so a hard link
from another take is replaced, never written through.

umtool take --from <take> hard-links that take's segments, keyed chrome
frame sequences (or ones kept aside in out/.keep-frames) and finished
crossfade batches in before the render. --keep-frames passes
--keep-frames to the build so a twin can reuse the chrome.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/bin/umtool.mjs | 5+++--
Mumtool/docs/report-video.md | 32++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeCli.mjs | 13+++++++++++--
Aumtool/lib/report/takeFrom.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeFrom.test.mjs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 20+++++++++++++++++++-
Mumtool/lib/report/takeRender.mjs | 5+++--
Mumtool/report-to-video/build-video.mjs | 74+++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Aumtool/report-to-video/segment-cache.mjs | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/segment-cache.test.mjs | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 846 insertions(+), 32 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A twin of a finished report-video take renders in a fraction of the time.** A full build of the Huck cut took about 1 h 45 m, and its uncensored twin — the same cut with `render.blur` off — took as long again, because every build encoded all 66 clips again (about 8 minutes), which in turn redid every crossfade batch, and captured the on-screen chrome again (about 47 minutes) once the first build had pruned its frames. Now a clip's segment is encoded again only when something that makes its picture or sound changed (its cut, snap, room, blur, framing, captions, loudness, encode settings or source file); otherwise the one on disk is reused untouched, and so are the crossfade batches over it. `umtool take <project> --id <id> --from <other take> …` starts a take from another take's render: it hard-links that take's clip segments, chrome frames and crossfade batches in (no copies, and the other take's files never change) and renders, rebuilding only what differs — for the uncensored twin, the blurred clip and the batch it sits in, then the final overlay. Make the first take with `--keep-frames` so its chrome frames are still there for the twin (they are 1–3 GB a layer; without it they are pruned after the render as before). `--from` refuses a take that does not exist, the take itself, or a take never rendered. Needs a restart of umtool for the Takes page's jobs; the CLI has it at once. - **A report video's fact-check counter can stay off screen until it first counts.** The deck's tally drew every verdict's cell from the first frame, so in the Huck cut the "Huck's Blend pitches" cell read 0 for about 23 of its 29 minutes. With `render.chrome.factcheck.tally.showAt: "first"` a cell is hidden until the stamp that gives it its first count lands; then it pops in already reading that count, flashes, and stays to the end. `{ "PARTLY": "first" }` sets it for one verdict's cell only. The default, `"always"`, is the tally as before. A hidden cell keeps its place in the row, and the finale's totals still show every verdict. Set it in the On-screen tab's fact-check labels (**pop in**, per verdict), with `umtool look <project> factcheck.tally.showAt=first` (or `factcheck.tally.showAt.PARTLY=first`; `factcheck.tally.showAt=` clears it), or in a take (`--set render.chrome.factcheck.tally.showAt=first`). An unknown value is refused by name. The clip editor's live preview and the Play view show the same deck page as the render, so the cell pops in at the same moment there. Needs a restart of umtool and a rebuild of the video. - **A report video's finale timeline no longer prints words over words.** In the Huck cut's finale the claim checks' words all stood on one line over the rail (`“less than ten” a year`, `19 seizures on camera`, `12 in a day · 4 in a week`, both pill-test goalposts), the `12 IN A DAY`/`4 IN A WEEK` labels ran into the markers' flags, and the turned dates under the rail overlapped. Now the claim checks take turns (`deck.finale.claims`: `rotate`, the default — one claim at a time for an even share of the finale's time, at least 6 s each, with a short crossfade; `all` stacks them), every claim's words, span label and marker label is laid in its own place in rows over the rail, with its stick kept inside its bracket and clear of the words under it, and a crowded rail says each date once and fans the turned labels out on thin leaders so no two meet. The timeline takes the height its rows need (`deck.finale.timelineShare`: `auto`, up to just over half the frame, its words set larger when there is room; or a share 0.38–0.6), and the clip, the totals and the stats shrink to fit under it. A finale without claim checks and with room for its labels renders as before. Re-render a take to see it. - **An assistant can finish a report video from umtool's command line without hand fixes.** `umtool variants <project> --take <take>` now makes the delivery ladder (master, 1080p, 720p, fit24) of a finished take, and so does the Deliver tab's **Make variants** with a take picked. A take used to be refused with "has no build to make variants of" because its render was moved to `takes/<take>/preview.mp4`; the take maker now also leaves it in the take's `out/` under the build's name (a hard link, so no extra disk), and a take made before this is encoded from its `preview.mp4`. `umtool timeline <project> insert` writes a clip the way the rest of the cut is written: in a cut with the on-screen deck, `--title` sets the deck's title (`onscreen.title`; `--stream-title` sets the stream's), a cut whose deck titles are dates gets `--date` as one in the same format (`9 Dec 2024`), the clip takes the section of the clip it goes after unless `--section N` says otherwise, and `--lock` and `--lock-end` lock its edges. `umtool check` now says how to fix a clip with no cue file: `pnpm ops build-cues --json '{"slug":"<channel>","ids":["<video>"]}' --wait` when the video is in the archive, and the Rumble two-ids check when it is not. A take of part of a cut says in its log what timed the window: the last build's schedule, or the clips' own lengths when there is no schedule or it does not time clips inserted since the build. diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -55,7 +55,7 @@ // umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id> // the operator's notes, and the agent's answers // umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] -// [--at S --dur S | --full] [--force] | --id <id> --rebuild make one take +// [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] // the clip deck's montage rulings (release 34) @@ -765,7 +765,8 @@ function usage() { " umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)", " umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>", " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]", - " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force)", + " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force;", + " --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>", " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -884,6 +884,38 @@ renders them blurred; a take with `--set render.blur=off` (the New take form's p `{"render": {"blur": "off"}}`) renders the same cut with every picture as recorded and no caption. Keep the project's own cut (and its `timeline` take) blurred for sharing and the `uncensored` take beside it. +**Start a take from another take's render (`--from`).** A full build used to encode every clip +segment again, and so every crossfade batch over them, even when nothing about a clip changed. +Now each clip segment records a key in its `<id>.cut.json` (`segKey`, `segSeconds`; +`report-to-video/segment-cache.mjs`): the exact ffmpeg argv, every file it names (a small one — +the header text, a blur caption, a caption file — by its contents, a source by its real path, +size and mtime), the cut record (snapped seconds, room, loudness, blur, framing, captions, +montage) and the ffmpeg binary. A segment on disk whose key is the cut's, and which still probes +to its length, is reused and not rewritten, so its mtime holds and the crossfade batches over it +hit too; anything else is encoded again (through a rename), and when the new bytes are the old +bytes the old file is kept. `build-video --no-segment-cache` always encodes. Cards, stills, +charts and ledgers are made again on every build as before (only the brand intro, a teaser and a +narrated card have caches of their own). + +``` +umtool take <project> --id final-uncensored --label "Final, uncensored" --set render.blur=off --full \ + --from final-blurred +``` + +hard-links `takes/final-blurred/out/sourced/`'s clip segments (the files `SEGMENT_FILE_SUFFIXES` +names), each keyed chrome render (`chrome/<layer>-frames/` with its `.key`; a layer kept aside in +`takes/<other>/out/.keep-frames/<layer>-frames` is linked in as `chrome/<layer>-frames`) and its +finished crossfade batches into this take's `out/sourced/`, then renders as usual: whatever still +matches is reused, the rest is rebuilt. Links, never copies or symlinks, and every one of these +files the build replaces rather than writes, so the other take's files never change. `--from` +refuses a take that does not exist, this take itself, or a take with no `out/sourced/`, before +anything is written. A chrome layer reuses its frames only when they are on disk: a build prunes +`chrome/<layer>-frames` after its mux (1–3 GB a layer for a full cut), so make the take you will +start a twin from with **`--keep-frames`** (passed to the build), or its twin captures the chrome +again. The blur is in the segments' pictures only — no chrome layer draws it — so an uncensored +twin rebuilds the blurred clips, their crossfade batches and the final overlay pass, and reuses +the rest. + `--quick` (a recipe's or a take's `quick: true`) is that quick render. A take that exists is skipped unless forced (**make it again if it exists**, `--force`). **Rebuild** on a card (`--rebuild`) makes it again from its own take.json against the project's manifest as it is now. A recipe is `{ group, window, quick?, takes: [{ id, label, style?, patch?, diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -5,6 +5,7 @@ // umtool take <project> --id <id> --label "<l>" [--group G] [--kind K] [--summary S] // [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …] // [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson] +// [--from TAKE] [--keep-frames] // umtool take <project> --id <id> --rebuild made again from its own take.json // umtool takes effects <project> [--json] the effect presets this cut offers (report-to-video/fx.mjs) // umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson] @@ -36,13 +37,19 @@ export const TAKE_USAGE = [ "usage: umtool take <project> --id <id> --label \"<label>\" [--group G] [--kind similar|different]", " [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]", " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]", - " umtool take <project> --id <id> --rebuild made again from its own take.json", + " [--from TAKE] [--keep-frames]", + " umtool take <project> --id <id> --rebuild [--from TAKE] [--keep-frames] made again from its own take.json", "", "A take is the project's manifest with a style's patch, then the take's own, applied (JSON merge", "patches), rendered into takes/<id>/. The window renders the entries it covers; --full the whole", `cut. Default window: --at ${DEFAULT_WINDOW.at} --dur ${DEFAULT_WINDOW.dur}. Nothing is fetched. --quick encodes`, "the render with x264 veryfast (the render only: the take's manifest, what a pick uses, keeps its own).", "--effect NAME is one of `umtool takes effects <project>` (an overlay effect's patch, before --patch's).", + "--from TAKE hard-links that take's built clip segments, chrome frames and crossfade batches into this", + "take's out/ first; the render then reuses each one whose key still matches this cut and rebuilds the rest", + "(an uncensored twin of a blurred take rebuilds only the blurred clip). The other take's files are never", + "changed. --keep-frames keeps this take's chrome frames after the mux (1-3 GB a layer for a full cut), so", + "a later --from can reuse them; without it they are pruned, and a --from twin captures the chrome again.", ].join("\n"); export const TAKES_USAGE = [ @@ -62,7 +69,7 @@ class CliError extends Error {} function parse(args) { const valued = new Set([ "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect", - "--at", "--dur", "--recipe", "--only", "--progress", + "--at", "--dur", "--recipe", "--only", "--progress", "--from", ]); /** @type {Record<string, string[]>} */ const flags = {}; @@ -218,6 +225,8 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons } const r = await makeTake(project.dir, spec, { force: p.has("--force") || p.has("--rebuild"), + from: p.one("--from") ?? null, + keepFrames: p.has("--keep-frames"), emit: out.emit, log: out.log, ...(deps ?? (await realDeps())), diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -0,0 +1,117 @@ +// `umtool take … --from <other take>`: before the render, the other take's +// built files are HARD-LINKED into this take's out/sourced/, so the build +// reuses whatever of them still matches this take's cut: +// +// segments/<id>{.mp4,.cut.json,…} each clip segment, reused when its key +// (segment-cache.mjs) is this cut's +// chrome/<layer>-frames/ each keyed chrome render (the deck, the +// feed, the stamps, the finale, a posts +// window, a teaser), reused when its +// `.key` is this cut's (compose-chrome) +// xfade-batches/batch-<key>.mov each crossfade batch, reused when its +// key (the segments' size and mtime) is +// out/.keep-frames/<layer>-frames a layer kept aside from a prune (the +// other take's chrome/ lost it after its +// mux), linked in as chrome/<layer>-frames +// +// Links, never copies, and never a symlink: every one of these the build +// REPLACES rather than writes -- a segment through a rename +// (encodeSegmentCached), its records and texts through a rename (replaceFile), +// a chrome sequence by removing the directory and rendering a new one, a batch +// through a rename after the stale ones are removed -- so a rebuild here never +// changes a byte of the other take's. Nothing else is linked: the chrome +// compositions (chrome/deck/index.html …) are written in place each run. +// +// Plain node; the CLI runs it with bare node. + +import { link, lstat, mkdir, readdir, rename, rm } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_VARIANT, SEGMENT_FILE_SUFFIXES } from "umtool-report-to-video/build-video"; +import { takesDirOf } from "./takes.mjs"; + +/** Where `--from` keeps a layer aside: the other take's `out/.keep-frames/<layer>-frames`. */ +export const KEEP_FRAMES_DIR = ".keep-frames"; + +const isFile = async (p) => (await lstat(p).catch(() => null))?.isFile() === true; +const isDir = async (p) => (await lstat(p).catch(() => null))?.isDirectory() === true; +const names = (dir) => readdir(dir).catch(() => []); + +/** Link `src` at `dst`, replacing whatever file is there (through a rename); the same inode is left. */ +async function linkFile(src, dst) { + const [a, b] = await Promise.all([lstat(src), lstat(dst).catch(() => null)]); + if (b && b.ino === a.ino && b.dev === a.dev) return false; + const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.link`); + await rm(tmp, { force: true }); + await link(src, tmp); + await rename(tmp, dst); + return true; +} + +/** A frame sequence directory, linked file by file into a fresh `dst` (what was there removed). */ +async function linkFrames(src, dst) { + await rm(dst, { recursive: true, force: true }); + await mkdir(dst, { recursive: true }); + let n = 0; + for (const f of await names(src)) { + const p = path.join(src, f); + if (!(await isFile(p))) continue; + await link(p, path.join(dst, f)); + n += 1; + } + return n; +} + +/** + * Check `--from`: the other take exists, is not this one, and has a built out/sourced/. + * @returns {Promise<string>} the other take's out/sourced + */ +export async function fromTakeSourced(projectDir, id, from) { + if (!from) throw new Error("--from <take>: the take whose built files to start from"); + if (from === id) throw new Error(`--from ${from}: that is this take — name another take`); + const other = path.join(takesDirOf(projectDir), from); + if (!(await isDir(other))) throw new Error(`--from ${from}: no such take in ${path.basename(projectDir)}`); + const sourced = path.join(other, "out", DEFAULT_VARIANT); + if (!(await isDir(sourced))) throw new Error(`--from ${from}: the take has no out/${DEFAULT_VARIANT} (it was never rendered)`); + return sourced; +} + +/** + * Hard-link take `from`'s built files into `takeOut/sourced` (see the top of the file). + * @returns {Promise<{ segments: number, frames: string[], batches: number }>} + */ +export async function linkFromTake(projectDir, id, from, takeOut) { + const src = await fromTakeSourced(projectDir, id, from); + const dst = path.join(takeOut, DEFAULT_VARIANT); + if (path.resolve(src) === path.resolve(dst)) throw new Error(`--from ${from}: that is this take's own out/`); + const out = { segments: 0, frames: [], batches: 0 }; + + const segs = path.join(src, "segments"); + const segOut = path.join(dst, "segments"); + await mkdir(segOut, { recursive: true }); + for (const f of await names(segs)) { + if (f.startsWith(".") || !SEGMENT_FILE_SUFFIXES.some((s) => f.endsWith(s))) continue; + if (!(await isFile(path.join(segs, f)))) continue; + if (await linkFile(path.join(segs, f), path.join(segOut, f))) out.segments += 1; + } + + // The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside. + const chrome = path.join(src, "chrome"); + const kept = path.join(path.dirname(src), KEEP_FRAMES_DIR); + const layers = new Map(); + for (const f of await names(kept)) if (f.endsWith("-frames") && (await isFile(path.join(kept, f, ".key")))) layers.set(f, path.join(kept, f)); + for (const f of await names(chrome)) if (f.endsWith("-frames") && (await isFile(path.join(chrome, f, ".key")))) layers.set(f, path.join(chrome, f)); + if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true }); + for (const [name, dir] of [...layers].sort()) { + await linkFrames(dir, path.join(dst, "chrome", name)); + out.frames.push(name); + } + + const batches = path.join(src, "xfade-batches"); + const batchOut = path.join(dst, "xfade-batches"); + for (const f of await names(batches)) { + if (!/^batch-[0-9a-f]+\.mov$/.test(f) || !(await isFile(path.join(batches, f)))) continue; + await mkdir(batchOut, { recursive: true }); + if (await linkFile(path.join(batches, f), path.join(batchOut, f))) out.batches += 1; + } + return out; +} diff --git a/umtool/lib/report/takeFrom.test.mjs b/umtool/lib/report/takeFrom.test.mjs @@ -0,0 +1,154 @@ +// `umtool take … --from <take>` (takeFrom.mjs): the other take's segments, +// chrome frames (or the ones kept aside) and crossfade batches are hard-linked +// into this take's out/sourced/ before the render; a bad --from is refused +// before anything is written. A stub renderer; no media. +// +// Run with: node --test umtool/lib/report/takeFrom.test.mjs +import assert from "node:assert/strict"; +import { existsSync, statSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { makeTake } from "./takeMaker.mjs"; +import { linkFromTake } from "./takeFrom.mjs"; +import { renderArgv } from "./takeRender.mjs"; +import { takeCommand } from "./takeCli.mjs"; +import { PROJECT_KINDS } from "../projects/kinds.mjs"; + +const TAKES_KIND = PROJECT_KINDS.find((k) => k.makesTakes).id; +const clip = (id, start, end) => ({ type: "clip", id, video: `v-${id}`, start, end, cite: start, section: 0 }); +const MANIFEST = { + schemaVersion: 1, slug: "fixture", title: "Fixture", + render: { width: 640, height: 360, fps: 15, transition: 0.5 }, + timeline: [clip("s01", 0, 10), clip("s02", 20, 25)], +}; + +async function project() { + const root = await mkdtemp(path.join(tmpdir(), "takefrom-")); + const dir = path.join(root, "reports", "proj"); + await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n"); + await writeFile(path.join(dir, "project.json"), JSON.stringify({ kind: TAKES_KIND, title: "Proj" }) + "\n"); + // The other take, built: its segments, a pruned layer kept aside, a live one, a batch. + const src = path.join(dir, "takes", "blurred", "out", "sourced"); + for (const d of ["segments", "chrome/deck-frames", "chrome/deck", "chrome/feed-frames-nokey", "xfade-batches"]) await mkdir(path.join(src, d), { recursive: true }); + for (const f of ["s01.mp4", "s01.cut.json", "s01.attrib.txt", "s01.blur-0.txt", "s02.mp4", "s02.cut.json"]) await writeFile(path.join(src, "segments", f), `blurred ${f}`); + await writeFile(path.join(src, "chrome", "deck-frames", "frame_000001.png"), "png"); + await writeFile(path.join(src, "chrome", "deck-frames", ".key"), "k1\n"); + await writeFile(path.join(src, "chrome", "deck", "index.html"), "<html>"); + await writeFile(path.join(src, "chrome", "feed-frames-nokey", "frame_000001.png"), "png"); + await writeFile(path.join(src, "xfade-batches", "batch-0123abcd.mov"), "batch"); + await writeFile(path.join(src, "xfade-batches", "batch-0123abcd.partial.mov"), "half"); + const kept = path.join(dir, "takes", "blurred", "out", ".keep-frames", "stamp-frames"); + await mkdir(kept, { recursive: true }); + await writeFile(path.join(kept, "frame_000001.png"), "stamp"); + await writeFile(path.join(kept, ".key"), "k2\n"); + await writeFile(path.join(dir, "takes", "blurred", "take.json"), JSON.stringify({ id: "blurred" })); + return { root, dir, src, reportsRoot: path.join(root, "reports") }; +} + +const sameFile = (a, b) => { + const x = statSync(a); + const y = statSync(b); + return x.ino === y.ino && x.dev === y.dev; +}; + +test("linkFromTake: segments, keyed chrome frames (kept-aside ones too) and finished batches, as hard links", async () => { + const p = await project(); + try { + const out = path.join(p.dir, "takes", "twin", "out"); + await mkdir(path.join(out, "sourced", "segments"), { recursive: true }); + // A file of the twin's own is replaced by the link (through a rename). + await writeFile(path.join(out, "sourced", "segments", "s02.mp4"), "the twin's own"); + const got = await linkFromTake(p.dir, "twin", "blurred", out); + const d = path.join(out, "sourced"); + for (const f of ["s01.mp4", "s01.cut.json", "s01.attrib.txt", "s02.mp4", "s02.cut.json"]) { + assert.ok(sameFile(path.join(p.src, "segments", f), path.join(d, "segments", f)), f); + } + assert.equal(got.segments, 5); + assert.ok(!existsSync(path.join(d, "segments", "s01.blur-0.txt")), "a file the build writes in place is not linked"); + assert.deepEqual(got.frames, ["deck-frames", "stamp-frames"]); + assert.ok(sameFile(path.join(p.src, "chrome", "deck-frames", "frame_000001.png"), path.join(d, "chrome", "deck-frames", "frame_000001.png"))); + assert.ok(sameFile(path.join(p.src, "chrome", "deck-frames", ".key"), path.join(d, "chrome", "deck-frames", ".key"))); + assert.equal(await readFile(path.join(d, "chrome", "stamp-frames", ".key"), "utf8"), "k2\n"); + assert.ok(!existsSync(path.join(d, "chrome", "deck")), "a composition is not linked"); + assert.ok(!existsSync(path.join(d, "chrome", "feed-frames-nokey")), "a sequence with no key is not linked"); + assert.equal(got.batches, 1); + assert.ok(sameFile(path.join(p.src, "xfade-batches", "batch-0123abcd.mov"), path.join(d, "xfade-batches", "batch-0123abcd.mov"))); + assert.ok(!existsSync(path.join(d, "xfade-batches", "batch-0123abcd.partial.mov"))); + assert.equal(await readFile(path.join(p.src, "segments", "s02.mp4"), "utf8"), "blurred s02.mp4", "the other take's file is as it was"); + // Again: nothing new to link, nothing broken. + const again = await linkFromTake(p.dir, "twin", "blurred", out); + assert.equal(again.segments, 0); + assert.equal(again.batches, 0); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("makeTake --from: linked before the render; --keep-frames reaches the build; a bad --from is refused before anything is written", async () => { + const p = await project(); + try { + const seen = []; + const render = async (job) => { + seen.push({ keepFrames: job.keepFrames, linked: existsSync(path.join(job.outDir, "sourced", "segments", "s01.mp4")) }); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "render"); + return { file }; + }; + const opts = { render, probe: async () => 1, styles: {} }; + await makeTake(p.dir, { id: "twin", label: "Twin", patch: { render: { blur: "off" } }, window: "full" }, { ...opts, from: "blurred", keepFrames: true }); + assert.deepEqual(seen, [{ keepFrames: true, linked: true }]); + + for (const [from, re] of [["twin", /that is this take/], ["nope", /no such take/]]) { + await assert.rejects(makeTake(p.dir, { id: "twin", label: "Twin", window: "full" }, { ...opts, force: true, from }), re); + } + // A take that was never rendered. + await mkdir(path.join(p.dir, "takes", "empty"), { recursive: true }); + await assert.rejects(makeTake(p.dir, { id: "fresh", label: "Fresh", window: "full" }, { ...opts, from: "empty" }), /never rendered/); + assert.ok(!existsSync(path.join(p.dir, "takes", "fresh")), "nothing written for a refused --from"); + assert.equal(seen.length, 1); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("the CLI: --from and --keep-frames; a bad --from exits non-zero with the reason", async () => { + const p = await project(); + try { + const errs = []; + const deps = { + render: async (job) => { + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "render"); + return { file }; + }, + probe: async () => 1, + }; + const code = await takeCommand(["proj", "--id", "twin", "--label", "Twin", "--set", "render.blur=off", "--full", "--from", "blurred", "--keep-frames"], { + reportsRoot: p.reportsRoot, log: () => {}, err: (s) => errs.push(s), deps, + }); + assert.equal(code, 0, errs.join("\n")); + assert.ok(existsSync(path.join(p.dir, "takes", "twin", "out", "sourced", "segments", "s01.mp4"))); + const bad = await takeCommand(["proj", "--id", "other", "--label", "O", "--full", "--from", "missing"], { + reportsRoot: p.reportsRoot, log: () => {}, err: (s) => errs.push(s), deps, + }); + assert.equal(bad, 1); + assert.match(errs.at(-1), /--from missing: no such take/); + // The help names both. + const help = []; + await takeCommand(["--help"], { log: (s) => help.push(s) }); + assert.match(help.join("\n"), /--from TAKE/); + assert.match(help.join("\n"), /--keep-frames/); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + +test("renderArgv: --keep-frames only when asked", () => { + const base = { manifestPath: "/m.json", outDir: "/o", full: true, xfade: true, queueLock: null }; + assert.ok(!renderArgv(base).includes("--keep-frames")); + assert.ok(renderArgv({ ...base, keepFrames: true }).includes("--keep-frames")); +}); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -404,6 +404,7 @@ export function normalizeWindow(w) { * * @typedef {{ * manifestPath: string, outDir: string, slug: string, full: boolean, xfade: boolean, + * keepFrames?: boolean, * emit: (ev: Record<string, unknown>) => void, log: (line: string) => void, * }} RenderJob * @typedef {(job: RenderJob) => Promise<{ file: string }>} RenderFn @@ -474,7 +475,12 @@ export async function linkSharedOut(projectDir, takeOut) { * @param {{ force?: boolean, render?: RenderFn, probe?: (file: string) => Promise<number | null>, * styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, * emit?: (ev: Record<string, unknown>) => void, log?: (line: string) => void, - * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date }} [opts] + * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date, + * from?: string | null, keepFrames?: boolean }} [opts] + * `from`: another take whose built segments, chrome renders and crossfade + * batches are hard-linked in before the render (takeFrom.mjs), so the build + * reuses whatever still matches. `keepFrames`: the build keeps its chrome + * frames after the mux (build-video --keep-frames), for a later `from`. */ export async function makeTake(projectDir, rawSpec, opts = {}) { const spec = checkSpec(rawSpec); @@ -489,6 +495,10 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { return { id: spec.id, skipped: true }; } + // --from is checked before anything is written: a bad name leaves no work dir. + const fromTake = opts.from ? await import("./takeFrom.mjs") : null; + if (fromTake) await fromTake.fromTakeSourced(projectDir, spec.id, opts.from); + const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8"); const base = JSON.parse(baseText); const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); @@ -537,6 +547,13 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { await (opts.ensureOut ?? ((d) => mkdir(d, { recursive: true })))(takeOut); const linked = await linkSharedOut(projectDir, takeOut); if (linked.length) log(`${spec.id}: reusing the project's ${linked.join(" and ")}`); + if (fromTake) { + const got = await fromTake.linkFromTake(projectDir, spec.id, /** @type {string} */ (opts.from), takeOut); + log( + `${spec.id}: linked from ${opts.from}: ${got.segments} segment file(s), ` + + `${got.frames.length ? got.frames.join(", ") : "no chrome frames"}, ${got.batches} crossfade batch(es) — reused where they still match`, + ); + } // The take's manifest is written under a work name until the render is // done: a failed REBUILD must not leave the old preview beside a new manifest. @@ -563,6 +580,7 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { slug: String(manifest.slug ?? ""), full: spec.window === "full", xfade, + keepFrames: opts.keepFrames === true, emit, log, })); diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs @@ -35,9 +35,9 @@ export function queueLockScript() { /** * The argv of a take's render, pure. - * @param {{ manifestPath: string, outDir: string, full: boolean, xfade: boolean, queueLock?: string | null }} job + * @param {{ manifestPath: string, outDir: string, full: boolean, xfade: boolean, keepFrames?: boolean, queueLock?: string | null }} job */ -export function renderArgv({ manifestPath, outDir, full, xfade, queueLock = queueLockScript() }) { +export function renderArgv({ manifestPath, outDir, full, xfade, keepFrames = false, queueLock = queueLockScript() }) { const build = [ process.execPath, path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"), @@ -50,6 +50,7 @@ export function renderArgv({ manifestPath, outDir, full, xfade, queueLock = queu "--continue-on-error", ...(xfade ? [] : ["--no-xfade"]), ...(full ? [] : ["--no-chapters"]), + ...(keepFrames ? ["--keep-frames"] : []), ]; return queueLock ? [process.execPath, queueLock, "--heavy", "--", ...build] : build; } diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -75,6 +75,11 @@ // --no-xfade Hard cuts instead of crossfades (much faster; concat copy) // --progress ndjson One JSON event per line instead of prose (for umtool) // --continue-on-error Record a failed entry and carry on, instead of aborting +// --no-segment-cache Encode every clip segment again. Without it a clip whose +// segment on disk carries this build's key (the ffmpeg argv, +// its input files, its cut record; segment-cache.mjs) is +// reused as it is -- not rewritten, so the crossfade batches +// over it are reused too. // --fetch-only <id> Fetch one clip's window into clips-raw and stop // --pad <s> Override render.fetchPad (the clip bench fetches wide) // --pad-before <s> / --pad-after <s> One side only; each defaults to --pad @@ -201,6 +206,7 @@ export { snap }; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; +import { encodeSegmentCached } from "./segment-cache.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. import { @@ -1220,10 +1226,12 @@ const encodeArgsVideoOnly = (render) => [ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, provenance, framing = null) { const outDir = dirs.dir; const { path: raw, fetchStart, scan } = await fetchClipAligned(entry, meta, render, dirs.local, opts); - // Its source in hand, and only then: a link to another take's files is - // unlinked before anything is written (detachSegmentFiles), so a clip whose - // source cannot be had leaves this take's segment as it was. - await detachSegmentFiles(path.join(outDir, "segments"), entry.id); + // Every file this writes in segments/ is written through a rename (the + // segment by encodeSegmentCached, the records and texts by replaceFile), so + // a link to another take's file -- `umtool take --from` links them in -- is + // replaced, never written through, and a segment whose key still matches is + // left as it is (segment-cache.mjs). A clip whose source cannot be had + // leaves this take's segment as it was. const seg = path.join(outDir, "segments", `${entry.id}.mp4`); const { width, height } = render; @@ -1354,7 +1362,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const quotePath = path.join(outDir, "segments", `${entry.id}.quote.txt`); const attribPath = path.join(outDir, "segments", `${entry.id}.attrib.txt`); // Written for reference/diffing only — the quote is no longer drawn on screen. - await writeFile(quotePath, wrap(`“${entry.quote}”`, 92), "utf8"); + await replaceFile(quotePath, wrap(`“${entry.quote}”`, 92)); // WHO, what, when, where in it. The channel heads the line because a // compilation routinely spans a streamer's own channel and two VOD mirrors, @@ -1364,11 +1372,11 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // a VOD mirror is often years after the stream. A clip may carry // `channelTitle`, `date` (the stream's own YYYY-MM-DD) and `title` (a display // title) to override the record's. - await writeFile(attribPath, attributionLine(entry, meta, provenance), "utf8"); + await replaceFile(attribPath, attributionLine(entry, meta, provenance)); // A brand draws the line's head -- the channel -- in the foreground colour. const who = render.brand ? channelName(entry, meta, provenance) : ""; const channelPath = who ? path.join(outDir, "segments", `${entry.id}.channel.txt`) : null; - if (channelPath) await writeFile(channelPath, who, "utf8"); + if (channelPath) await replaceFile(channelPath, who); // THE DECK. The citation header, the corner QR and the section footer are // all things the deck says instead -- the source and date in its subtitle, @@ -1404,7 +1412,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const lineFiles = []; for (const [k, line] of layout.lines.entries()) { const file = path.join(outDir, "segments", `${entry.id}.blur-${k}.txt`); - await writeFile(file, line, "utf8"); + await replaceFile(file, line); lineFiles.push(file); } return blurPictureFilters({ blur, span, h, layout, lineFiles, render }); @@ -1414,9 +1422,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, const fr = framing ?? segmentFraming(render); const pst = await poster(fr.box, 1); const picture = await blurPicture(fr.box.width, fr.box.height); - await execFileP( - FFMPEG, - [ + // The box it was framed into, so --chrome-only can refuse another layout's. + await encodeClipSegment({ + seg, outDir, render, opts, id: entry.id, record: { ...cutRecord, framing: fr }, + argv: [ "-nostdin", "-v", "error", "-y", ...cutArgs(raw, segA, segB), ...(pst ? pst.input : []), @@ -1429,10 +1438,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...encodeArgs(render), seg, ], - { maxBuffer: 1 << 24 }, - ); - // The box it was framed into, so --chrome-only can refuse another layout's. - await writeCutRecord(seg, { ...cutRecord, framing: fr }); + }); return seg; } @@ -1593,9 +1599,10 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, } if (dirs.short) cutRecord.short = { crop: entry.vertical?.crop ?? null, width, height }; - await execFileP( - FFMPEG, - [ + await encodeClipSegment({ + seg, outDir, render, opts, id: entry.id, + record: mont ? { ...cutRecord, montage: level ? { ...mg.record, loudness: level } : mg.record } : cutRecord, + argv: [ "-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", parts.join(";"), @@ -1603,9 +1610,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, ...encodeArgs(render), seg, ], - { maxBuffer: 1 << 24 }, - ); - await writeCutRecord(seg, mont ? { ...cutRecord, montage: level ? { ...mg.record, loudness: level } : mg.record } : cutRecord); + }); if (mont) { dirs.montage.cuts.set(entry.id, { raw, cutA, cutB, phrase: mont.phrase, via: mont.via, year: mont.ctx.year, hasVideo: media.hasVideo, @@ -1615,6 +1620,22 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, return seg; } +/** + * One clip segment's encode, through the segment cache (segment-cache.mjs): + * reused when the key of this argv, its inputs and its record is the one + * recorded beside the segment on disk; else encoded through a rename and the + * record (with the key) written. `--no-segment-cache` always encodes. + */ +async function encodeClipSegment({ seg, argv, record, outDir, render, opts, id }) { + return encodeSegmentCached({ + seg, argv, record, outDir, id, fps: render.fps, ffmpeg: FFMPEG, + noCache: !!opts?.noSegmentCache, + exec: (bin, a) => execFileP(bin, a, { maxBuffer: 1 << 24 }), + probe: (f) => probeDuration(f, render.fps), + emit: (ev, f) => EMIT(ev, f), + }); +} + // ---- the look (render.captions, a short; release 36 lane C) --------------- // The build's side of look.mjs: what needs the project's files, the corpus // and ffmpeg. Reached only when render.captions is set, or for a short. @@ -1663,7 +1684,7 @@ async function segmentCaptions({ entry, provenance, look, render, outDir, from, seconds, maxChars: geo.maxChars, }); const file = path.join(outDir, "segments", `${entry.id}.captions.ass`); - await writeFile(file, assDocument(lines, { width: render.width, height: render.height, size, bottom }), "utf8"); + await replaceFile(file, assDocument(lines, { width: render.width, height: render.height, size, bottom })); return { filter: assFilter(file, FONTS_DIR), lines: lines.length, wordsFrom: src.wordsFrom }; } @@ -2161,7 +2182,7 @@ async function replaceFile(file, text) { export const cutRecordPath = (seg) => seg.replace(/\.mp4$/, ".cut.json"); async function writeCutRecord(seg, record) { - await writeFile(cutRecordPath(seg), JSON.stringify(record) + "\n", "utf8"); + await replaceFile(cutRecordPath(seg), JSON.stringify(record) + "\n"); } /** A segment's cut record, or null when there is none (a segment built before records existed). */ @@ -5381,7 +5402,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly prefer: opts.cueSource ?? "auto", log: (m) => EMIT("log", { message: m }), }); - const outRoot = out ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); + // Absolute: the segment cache keys a segment's argv with this take's out + // dir written as <out> (segment-cache.mjs), which needs one spelling of it. + const outRoot = path.resolve(out ?? path.join(path.dirname(path.resolve(manifestPath)), "out")); const dirs = variantPaths(outRoot, manifest.slug, variant); // A short's work is its own: the cut's segments are never overwritten by one. if (opts.short) dirs.dir = path.join(outRoot, "shorts-work"); @@ -6242,7 +6265,7 @@ async function main() { " [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" + " [--join-preview [--join-from <id>]] (the first few joins, a few seconds each side: out/join-preview.mp4)\n" + " [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" + - " [--progress ndjson] [--continue-on-error] [--no-reuse]\n" + + " [--progress ndjson] [--continue-on-error] [--no-reuse] [--no-segment-cache]\n" + " [--no-rail] [--rail-only] [--preview <start> <dur>]\n" + " [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" + " [--clip-preview <id>] (one clip's segment with its deck: out/<variant>/clip-preview/<id>.mp4)\n" + @@ -6284,6 +6307,7 @@ async function main() { cueSource: flag("--cue-source"), thumbnailOnly: argv.includes("--thumbnail"), keepFrames: argv.includes("--keep-frames"), + noSegmentCache: argv.includes("--no-segment-cache"), noLint: argv.includes("--no-lint"), noRulings: argv.includes("--no-rulings"), narrationUnreviewed: argv.includes("--narration-unreviewed"), diff --git a/umtool/report-to-video/segment-cache.mjs b/umtool/report-to-video/segment-cache.mjs @@ -0,0 +1,203 @@ +// THE CLIP SEGMENT CACHE: a full build re-encodes a clip's segment only when +// something that makes its bytes changed. +// +// A segment is one ffmpeg run. Its KEY is that run -- the exact argv, every +// input file named in it (a big file by its real path, size and mtime; a +// small one, like the header's text or a caption file the build has just +// written, by its contents), the cut record written beside it (the snapped +// seconds, room, loudness, blur, framing, captions, montage) and the ffmpeg +// binary -- hashed. Every input that changes a picture or a sound reaches +// the argv: the cut seconds through `-ss`/`-to`, the snap, pads, room, mute +// and audio knobs through the filter graph, the blur through its filters and +// line files, the framing through the scale/pad, the captions through their +// ASS file, the loudness through its gain, the encode settings through +// encodeArgs, the source through its file. The record says it a second time. +// +// The key is written in `<id>.cut.json` (`segKey`, with `segSeconds`, the +// segment's probed length). A segment on disk whose record carries this key, +// and which still probes to that length, is reused as it is: not rewritten, +// so its mtime holds and the crossfade batches keyed on it hit too. A record +// with no key (built before this) or another key is rebuilt. +// +// A rebuild encodes to a temporary file and renames it over the segment, so a +// segment that is a hard link of another take's is REPLACED, never written +// through. When the new bytes are the old bytes (a segment with no key yet, +// re-encoded the same) the old file is kept, mtime and all. +// +// Plain node; no Next. Every path here is a parameter, never cwd-derived. + +import { createHash } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; + +/** Bumped when what the key covers changes: every segment is rebuilt once. */ +export const SEGMENT_KEY_VERSION = 1; +/** A file at or under this many bytes is keyed by its contents; above, by real path, size and mtime. */ +export const HASH_CONTENT_BELOW = 8 << 20; +/** An absolute path inside an argv element (a filter's textfile=, an -i, a fontfile=). */ +const ABS_PATH = /\/(?:[\w.@+~%-]+\/)*[\w.@+~%-]+/g; + +const sha256 = (s) => createHash("sha256").update(s).digest("hex"); + +function fileSha(file) { + return new Promise((resolve, reject) => { + const h = createHash("sha256"); + createReadStream(file) + .on("error", reject) + .on("data", (b) => h.update(b)) + .on("end", () => resolve(h.digest("hex"))); + }); +} + +/** What a file contributes to a key, or null when it is not a regular file. */ +async function fileIdentity(file) { + const st = await stat(file).catch(() => null); + if (!st?.isFile()) return null; + if (st.size <= HASH_CONTENT_BELOW) return `sha:${await fileSha(file)}`; + const real = await realpath(file).catch(() => file); + return `file:${real}|${st.size}|${st.mtimeMs}`; +} + +/** + * The argv with every input file it names replaced by what identifies it, and + * the build's own out dir by `<out>`, so the same segment of two takes (each + * with its own out/) keys alike. Pure but for the files' stats. + * + * @param {string[]} argv the ffmpeg argv WITHOUT its output path + * @param {{ outDir: string }} o + */ +export async function canonicalArgv(argv, { outDir }) { + const ids = new Map(); + const idOf = async (p) => { + if (!ids.has(p)) ids.set(p, await fileIdentity(p)); + return ids.get(p); + }; + const out = path.resolve(outDir); + const result = []; + for (const a of argv) { + let s = String(a); + // A whole element that is a (relative) file. + if (!s.startsWith("/") && !s.startsWith("-") && s.includes("/")) { + const id = await idOf(path.resolve(s)); + if (id) { + result.push(`<${id}>`); + continue; + } + } + const found = [...new Set(s.match(ABS_PATH) ?? [])].sort((x, y) => y.length - x.length); + for (const p of found) { + const id = await idOf(p); + if (id) s = s.split(p).join(`<${id}>`); + } + result.push(s.split(out).join("<out>")); + } + return result; +} + +let ffmpegIdCache = new Map(); + +/** The ffmpeg binary's identity (its real path, size and mtime), found on PATH when bare. */ +export async function ffmpegIdentity(bin, env = process.env) { + if (ffmpegIdCache.has(bin)) return ffmpegIdCache.get(bin); + let file = null; + if (bin.includes("/")) file = path.resolve(bin); + else { + for (const dir of String(env.PATH ?? "").split(":").filter(Boolean)) { + const f = path.join(dir, bin); + if ((await stat(f).catch(() => null))?.isFile()) { + file = f; + break; + } + } + } + const st = file ? await stat(file).catch(() => null) : null; + const real = file ? await realpath(file).catch(() => file) : null; + const id = st ? `${real}|${st.size}|${st.mtimeMs}` : `bin:${bin}`; + ffmpegIdCache.set(bin, id); + return id; +} + +/** The record as the key sees it: the cache's own fields left out. */ +export function recordForKey(record) { + const { segKey: _k, segSeconds: _s, ...rest } = record ?? {}; + return rest; +} + +/** + * A segment's key (see the top of the file). + * @param {{ argv: string[], record: object, outDir: string, ffmpeg: string }} o argv WITHOUT the output path + */ +export async function segmentKey({ argv, record, outDir, ffmpeg }) { + return sha256(JSON.stringify({ + v: SEGMENT_KEY_VERSION, + ffmpeg: await ffmpegIdentity(ffmpeg), + argv: await canonicalArgv(argv, { outDir }), + record: recordForKey(record), + })).slice(0, 32); +} + +const cutRecordOf = (seg) => seg.replace(/\.mp4$/, ".cut.json"); + +async function replaceText(file, text) { + const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`); + await writeFile(tmp, text, "utf8"); + await rename(tmp, file); +} + +async function sameBytes(a, b) { + const [x, y] = await Promise.all([stat(a).catch(() => null), stat(b).catch(() => null)]); + if (!x?.isFile() || !y?.isFile() || x.size !== y.size) return false; + return (await fileSha(a)) === (await fileSha(b)); +} + +/** + * Encode one segment, or reuse the one on disk when its key matches. + * + * @param {{ seg: string, argv: string[], record: object, outDir: string, fps: number, ffmpeg: string, + * exec: (bin: string, argv: string[]) => Promise<unknown>, + * probe: (file: string) => Promise<number>, + * emit?: (ev: string, fields: object) => void, noCache?: boolean, id?: string }} o + * `argv` ENDS with the output path (`seg`), as the build always ran it + * @returns {Promise<{ reused: false | "key" | "bytes", key: string, seconds: number }>} + */ +export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmpeg, exec, probe, emit = () => {}, noCache = false, id = path.basename(seg, ".mp4") }) { + if (argv[argv.length - 1] !== seg) throw new Error(`encodeSegmentCached: the argv must end with ${seg}`); + const head = argv.slice(0, -1); + const key = await segmentKey({ argv: head, record, outDir, ffmpeg }); + const tol = 1.5 / (fps || 30); + if (!noCache) { + const prev = await readFile(cutRecordOf(seg), "utf8").then(JSON.parse, () => null); + if (prev?.segKey === key && Number.isFinite(prev.segSeconds) && (await stat(seg).catch(() => null))?.isFile()) { + const got = await probe(seg).catch(() => null); + if (got != null && Math.abs(got - prev.segSeconds) <= tol) { + emit("note", { message: `${id}: segment unchanged (key ${key.slice(0, 12)}) — reused` }); + return { reused: "key", key, seconds: prev.segSeconds }; + } + emit("note", { message: `${id}: segment key matches but the file probes ${got ?? "unreadable"}s, not ${prev.segSeconds}s — rebuilt` }); + } + } + const tmp = path.join(path.dirname(seg), `.${path.basename(seg, ".mp4")}.${process.pid}.partial.mp4`); + await rm(tmp, { force: true }); + try { + await exec(ffmpeg, [...head, tmp]); + const seconds = await probe(tmp); + let reused = false; + if (await sameBytes(tmp, seg)) { + await rm(tmp, { force: true }); + reused = "bytes"; + emit("note", { message: `${id}: segment re-encoded to the same bytes — the one on disk kept` }); + } else { + await rename(tmp, seg); + } + await replaceText(cutRecordOf(seg), JSON.stringify({ ...recordForKey(record), segKey: key, segSeconds: seconds }) + "\n"); + return { reused, key, seconds }; + } finally { + await rm(tmp, { force: true }); + } +} + +/** For tests: forget the ffmpeg identities found. */ +export function resetSegmentCacheForTests() { + ffmpegIdCache = new Map(); +} diff --git a/umtool/report-to-video/segment-cache.test.mjs b/umtool/report-to-video/segment-cache.test.mjs @@ -0,0 +1,254 @@ +// 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 <out>, 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], /^<file:.*big\.mp4\|\d+\|/); + await utimes(big, new Date(), new Date(Date.now() + 5000)); + assert.notDeepEqual(await canonicalArgv(["-i", big], { outDir: a }), k1, "a source's mtime is in the key"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("segmentKey: the record is in it (framing, blur, loudness), the cache's own fields are not", async () => { + 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 }); + } +});