commit 15594467bcc2306cb389c22cde614112f8ee2607
parent 44a923bce7665ce175560540709f61d2eb5fdaed
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 17:00:33 -0500
umtool: the render pool -- every post, clip, chunk, sound and chrome frame a build makes, filed once by its key and hard-linked into any take of any project that needs it again
Operator, 4 Nov: "every clip that could be inserted into a video is put into
a shared cached clip pool by all input params by default".
- render-pool.mjs: content-addressed objects under <media root>/.render-pool
(UMTOOL_RENDER_POOL; =0 off; only for an out/ under the media root, so a
test or a scratch copy never writes the operator's pool), each kind with a
renderer salt; a hit hard-linked in through a rename, a miss linked into a
tmp dir renamed into place; never a copy (another filesystem is no pool).
The cap (UMTOOL_RENDER_POOL_MAX_GB, default 30) is on the bytes no take
links; least recently used first; a linked object is never evicted.
Hits and misses appended to events.ndjson.
- Wired: segment-cache (clip segments and their cut record), post-render
(a post item's segment and .post.json, after its own record misses),
planChunks (each chunk, before the deck's lazy plan, so a pooled chunk
needs no frames), the cut's sound (hard-cut and crossfade), compose-chrome
reuseFrames (each frame by its key, captured ones put in) and a whole
render's distinct frames. The pool is pruned at the end of a build, hourly.
- umtool pool [stats|prune|verify] [--json] (lib/report/poolCli.mjs).
- render-pool.test.mjs: put/fetch by link, events, LRU prune that keeps
linked objects, verify; and the keys -- every field of a fixture post
(entry, box, place, encode, stamps, plan, palette, fonts, fps, narration
knobs), chunk, sound and clip mutated in turn changes its key.
- hardcut-deck.test.mjs: another project's build of the same cut takes
every chunk and the sound from the pool and draws no frame; a chunk lost
mid-render comes back from the pool; --chrome-only re-encodes nothing.
- report-video.md "The render pool"; umtool help.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 896 insertions(+), 7 deletions(-)
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -78,6 +78,7 @@
// | delete <project> <take> [--dry-run] [--force] take housekeeping
// umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render gets the machine
// umtool render-mode on [--for 90m] [--print-token] -- <cmd …> held while <cmd> runs (its env carries the token)
+// umtool pool [stats|prune|verify] [--json] the render pool: every built unit by its key, shared by every take
// umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3]
// [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master
// | --reel <name> [--take <t>] a beat reel (promo/<name>-beats.json) -> <slug>.<name>.mp4
@@ -969,6 +970,9 @@ function usage() {
" on [--for D] [--print-token] -- <cmd …>: held while <cmd> runs (its env carries the token,",
" the hold is its pid), released when it exits -- the form for a script; --print-token prints",
" the token alone on stdout",
+ " umtool pool [stats] [--since 7d] | prune [--max-gb N] [--dry-run] | verify [--sample N | --all] [--json]",
+ " the render pool: every post, clip, chunk, sound and chrome frame a build made, by its key,",
+ " hard-linked into any take that needs it again (UMTOOL_RENDER_POOL=0 off; _MAX_GB its cap)",
" umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]",
" a trailer cut from the take's finished master: the master's own frames, so the deck shows the",
" whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)",
@@ -1102,6 +1106,8 @@ const COMMANDS = {
takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))),
// Render mode (2026-10-30): lib/report/renderMode.mjs.
"render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))),
+ // The render pool (report-to-video render-pool.mjs): lib/report/poolCli.mjs.
+ pool: async () => process.exit(await (await import("../lib/report/poolCli.mjs")).poolCommand(argv.slice(argv.indexOf("pool") + 1))),
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
// Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs.
links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))),
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1951,6 +1951,48 @@ auto-picked over it (`--unpin`, or picking another, lets go). The gate this remo
takes and none picked, Re-render the take had no target and the only way on was to pick one.
+### The render pool
+
+Every unit a build makes is filed in ONE pool shared by every take of every project, under the hash
+of its full input key, and every build looks there when its own `out/` misses (report-to-video
+`render-pool.mjs`; operator, 4 Nov: "every clip that could be inserted into a video is put into a
+shared cached clip pool by all input params by default"):
+
+| kind | the unit | its key |
+| --- | --- | --- |
+| `post` | a post item's segment and its `.post.json` | `postSegmentKeyOf` (post-render.mjs): the entry, its plan, the box, the encode, its files' stamps, the narration |
+| `clip` | a clip segment and its `.cut.json` | `segmentKey` (segment-cache.mjs): the ffmpeg argv, every input by its identity, the cut record |
+| `chunk` | a chunk of the final encode | `chunkKey` (chunked-encode.mjs): its inputs' contents, its graph in its own clock -- position-free |
+| `sound` | the cut's sound | the pins' and the encode's argv, each segment's sound |
+| `frame` | one chrome frame | its frame key (frame-keys.mjs): what it draws |
+
+A hit is HARD-LINKED into the take; a miss, once built, is linked into the pool through a tmp
+directory renamed into place. A link, never a copy: while a take holds an object the pool costs no
+disk, and since a build replaces its files rather than writing through them, neither side can change
+the other's bytes. Each kind carries a renderer salt (`POOL_KINDS`), bumped when code changes what a
+unit is for the same inputs; the build's own key versions are in the keys too.
+`render-pool.test.mjs` mutates every field of a fixture post, chunk, sound and clip and fails if one
+leaves its key as it was.
+
+So `--from` keeps working but is no longer needed: a take finds any unit any take built. A take
+stopped mid-render and run again finds every chunk it finished, in its own `out/` or in the pool.
+
+- **Where:** `UMTOOL_RENDER_POOL` (a directory), else `<media root>/.render-pool` (`UMTOOL_MEDIA_DIR`'s,
+ else the reports root's) -- for an `out/` under that root only, so a test's or a scratch copy's
+ build never writes the operator's pool; another filesystem (no hard link) is no pool.
+ `UMTOOL_RENDER_POOL=0` turns it off.
+- **Disk:** `UMTOOL_RENDER_POOL_MAX_GB` (default 30) caps the bytes only the pool holds -- objects no
+ take links. Over it, the least recently used go first, at the end of a build (at most hourly) or by
+ `umtool pool prune`; an object a take links -- a pinned or picked take's, a running build's -- is
+ never evicted.
+- **`umtool pool [stats|prune|verify] [--json]`:** what it holds by kind, its hits and misses
+ (`--since 7d`), the biggest objects; an eviction down to the cap (`--max-gb`, `--dry-run`); a check
+ of a sample (`--sample N`, `--all`) against the sha256 each file was put in with.
+- **Not yet pooled:** image, card, narrated card, teaser and intro segments (each cheap, or cached by
+ a key of its own in the take), the combo badge's pass. A post item's key names its files by path
+ (its stamps, the avatars), so it is shared by every take of a project but not across two projects
+ that hold the same files at different paths.
+
### Render mode: giving a render the machine
A render you are waiting for is slowed by what else the machine does — the transcription
diff --git a/umtool/lib/report/poolCli.mjs b/umtool/lib/report/poolCli.mjs
@@ -0,0 +1,74 @@
+// `umtool pool [stats|prune|verify] [--json]` -- the render pool
+// (report-to-video render-pool.mjs): what it holds, its hits and misses per
+// kind, the biggest objects; an eviction down to its cap; a check of a sample.
+//
+// umtool pool [stats] [--since 7d] [--json]
+// umtool pool prune [--max-gb N] [--dry-run] [--json]
+// umtool pool verify [--sample N | --all] [--json]
+//
+// `--pool <dir>` (or UMTOOL_RENDER_POOL) names another pool.
+import { MEDIA_ROOT } from "../paths.mjs";
+import { POOL_KINDS, poolFor, poolMaxBytes, poolPrune, poolStats, poolVerify } from "umtool-report-to-video/render-pool";
+
+const USAGE = "usage: umtool pool [stats|prune|verify] [--pool DIR] [--since 7d] [--max-gb N] [--dry-run] [--sample N | --all] [--json]";
+const mib = (b) => `${(b / (1 << 20)).toFixed(0)} MiB`;
+
+/** `7d`, `12h`, `30m` -> ms; null when absent. */
+function sinceMs(v) {
+ const m = /^(\d+(?:\.\d+)?)([dhm])$/.exec(String(v ?? ""));
+ if (!m) return null;
+ return Number(m[1]) * { d: 86_400_000, h: 3_600_000, m: 60_000 }[m[2]];
+}
+
+/** @param {string[]} args @returns {Promise<number>} the exit code */
+export async function poolCommand(args, { log = console.log, env = process.env } = {}) {
+ const flag = (n) => {
+ const i = args.indexOf(n);
+ return i >= 0 ? args[i + 1] : undefined;
+ };
+ const json = args.includes("--json");
+ const sub = args[0] && !args[0].startsWith("--") ? args[0] : "stats";
+ const pool = flag("--pool") ?? (await poolFor(MEDIA_ROOT, env));
+ if (!pool) {
+ log("the render pool is off (UMTOOL_RENDER_POOL=0)");
+ return 0;
+ }
+ if (sub === "stats") {
+ const since = sinceMs(flag("--since"));
+ const s = await poolStats(pool, { since: since ? Date.now() - since : 0 });
+ if (json) log(JSON.stringify(s, null, 2));
+ else {
+ log(`render pool ${pool}: ${s.objects} object(s), ${mib(s.bytes)}; ${mib(s.onlyPool)} held by the pool alone (cap ${mib(s.maxOnlyPool)})`);
+ for (const [k, v] of Object.entries(s.kinds)) {
+ const all = v.hits + v.misses;
+ log(` ${k.padEnd(6)} ${String(v.objects).padStart(7)} ${POOL_KINDS[k].noun.padEnd(20)} ${mib(v.bytes).padStart(10)} ${v.hits} hit(s), ${v.misses} miss(es)${all ? ` (${Math.round((100 * v.hits) / all)} %)` : ""}`);
+ }
+ if (s.biggest.length) log(" biggest:");
+ for (const b of s.biggest) log(` ${mib(b.bytes).padStart(9)} ${b.kind} ${b.path}${b.linked ? " (a take links it)" : ""}`);
+ }
+ return 0;
+ }
+ if (sub === "prune") {
+ const gb = flag("--max-gb");
+ const maxBytes = gb !== undefined ? Number(gb) * 1024 ** 3 : poolMaxBytes(env);
+ if (!Number.isFinite(maxBytes) || maxBytes < 0) {
+ log(USAGE);
+ return 2;
+ }
+ const r = await poolPrune(pool, { maxBytes, dryRun: args.includes("--dry-run") });
+ if (json) log(JSON.stringify(r, null, 2));
+ else log(`render pool: ${args.includes("--dry-run") ? "would evict" : "evicted"} ${r.evicted} object(s), ${mib(r.bytes)}; held by the pool alone ${mib(r.before)} -> ${mib(r.after)} (cap ${mib(r.maxBytes)}; an object a take links is never evicted)`);
+ return 0;
+ }
+ if (sub === "verify") {
+ const r = await poolVerify(pool, { sample: Number(flag("--sample") ?? 50), all: args.includes("--all") });
+ if (json) log(JSON.stringify(r, null, 2));
+ else {
+ log(`render pool: checked ${r.checked} of ${r.of} object(s): ${r.problems.length ? `${r.problems.length} problem(s)` : "all as put in"}`);
+ for (const p of r.problems) log(` ${p}`);
+ }
+ return r.problems.length ? 1 : 0;
+ }
+ log(USAGE);
+ return 2;
+}
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -237,6 +237,7 @@ export { snap };
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
import { keepFramesAsked, keptFramesDir, pruneChromeFrames } from "./prune-frames.mjs";
import { encodeSegmentCached, ffmpegIdentity } from "./segment-cache.mjs";
+import { poolFetch, poolFor, poolPruneThrottled, poolPut } from "./render-pool.mjs";
import {
CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, SPARSE_FILE, chunkKey, chunkSpans, frameFile, frameKeysIdentity, framesRead, readFrameKeys, sequenceIdentity, spanSegments, whyRebuilt,
} from "./chunked-encode.mjs";
@@ -5112,6 +5113,12 @@ async function makeHardCutSound({ segments, durs, joins = null, render, dir, wor
EMIT("note", { message: "final encode: the cut's sound unchanged — reused" });
return { audio, reused: true };
}
+ await mkdir(dir, { recursive: true });
+ const pool = await poolFor(workDir);
+ if (await poolFetch(pool, "sound", path.basename(audio), { "sound.m4a": audio })) {
+ EMIT("note", { message: "final encode: the cut's sound from the render pool" });
+ return { audio, reused: true };
+ }
const t0 = Date.now();
const a = hardCutSoundArgs({ durs, joins, render });
const pins = path.join(workDir, `work-sound-${process.pid}`);
@@ -5126,6 +5133,7 @@ async function makeHardCutSound({ segments, durs, joins = null, render, dir, wor
const tmp = audio.replace(/\.m4a$/, `.${process.pid}.partial.m4a`);
await execFileP(FFMPEG, a.encode(list, tmp), { maxBuffer: 1 << 26 });
await rename(tmp, audio);
+ await poolPut(pool, "sound", path.basename(audio), { "sound.m4a": audio });
} finally {
await rm(pins, { recursive: true, force: true });
}
@@ -5212,6 +5220,9 @@ export async function logRebuild(workDir, entry) {
* is joined) -- which before this re-encoded the whole cut in one overlay
* pass on every build, ~12 minutes for a 31-minute cut.
*/
+/** Per chunks dir, the chunk keys this process took from the render pool. */
+const POOLED_CHUNKS = new Map();
+
/**
* The chunked encode's plan, without encoding a frame: every chunk's span,
* key, record and argv, and which of them are on disk (`reused`) and which
@@ -5279,14 +5290,24 @@ export async function planChunks({ segments, render, chrome = null, joins = null
}
await memo.save();
- // Reused: on disk with the frames it should have.
+ // Reused: on disk with the frames it should have -- this take's, or the
+ // render pool's (render-pool.mjs: the same chunk encoded by any take).
+ const pool = await poolFor(workDir);
+ // (The chunks this run took from the pool, said by the encode though the deck's plan took them.)
+ if (!POOLED_CHUNKS.has(dir)) POOLED_CHUNKS.set(dir, new Set());
+ const pooled = POOLED_CHUNKS.get(dir);
const todo = [];
for (const p of plan) {
- const got = (await exists(p.file)) ? await videoFrames(p.file) : null;
+ let got = (await exists(p.file)) ? await videoFrames(p.file) : null;
+ if (got !== p.span.b - p.span.a && pool && (await poolFetch(pool, "chunk", p.rec.key, { "chunk.mp4": p.file }))) {
+ got = await videoFrames(p.file);
+ if (got === p.span.b - p.span.a) pooled.add(p.rec.key);
+ }
+ if (pooled.has(p.rec.key)) p.pooled = true;
if (got === p.span.b - p.span.a) p.reused = true;
else todo.push(p);
}
- return { D, fps, durs, starts, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash };
+ return { D, fps, durs, starts, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash, pool };
}
/**
@@ -5326,7 +5347,7 @@ export async function framesNeeded({ framesDir, fk, ...job }) {
export async function chunkedConcat({ segments, render, outPath, chrome = null, joins = null, workDir, hardCut = false }) {
const t0 = Date.now();
- const { D, fps, durs, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash } = await planChunks({ segments, render, chrome, joins, workDir, hardCut });
+ const { D, fps, durs, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash, pool } = await planChunks({ segments, render, chrome, joins, workDir, hardCut });
// A chunk to encode reads every frame it lays: a sparse sequence's absent
// frames are only ever in chunks on disk (framesNeeded), checked here.
const sparse = new Map();
@@ -5347,7 +5368,8 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null,
const reusedFrames = plan.filter((p) => p.reused).reduce((n, p) => n + (p.span.b - p.span.a), 0);
const hms = (f) => `${(f / fps / 60).toFixed(1)} min`;
EMIT("note", {
- message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused), ` +
+ message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused` +
+ `${plan.some((p) => p.pooled) ? `, ${plan.filter((p) => p.pooled).length} from the render pool` : ""}), ` +
`${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs()} at a time)`,
});
// Why, grouped, so a line says what changed rather than listing 80 chunks.
@@ -5369,10 +5391,15 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null,
EMIT("note", { message: "final encode: the cut's sound unchanged — reused" });
return;
}
+ if (await poolFetch(pool, "sound", path.basename(audio), { "sound.m4a": audio })) {
+ EMIT("note", { message: "final encode: the cut's sound from the render pool" });
+ return;
+ }
const ta = Date.now();
const tmp = audio.replace(/\.m4a$/, ".partial.m4a");
await execFileP(FFMPEG, cutAudioArgs({ segments, durs, D, render, joins, outPath: tmp }), { maxBuffer: 1 << 26 });
await rename(tmp, audio);
+ await poolPut(pool, "sound", path.basename(audio), { "sound.m4a": audio });
EMIT("note", { message: `final encode: the cut's sound encoded in ${((Date.now() - ta) / 1000).toFixed(1)}s` });
};
@@ -5391,6 +5418,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null,
throw new Error(`chunk ${p.rec.anchor} (frames ${p.span.a}–${p.span.b}) encoded ${got} frames, expected ${p.span.b - p.span.a}`);
}
await rename(tmp, p.file);
+ await poolPut(pool, "chunk", p.rec.key, { "chunk.mp4": p.file });
done += 1;
EMIT("note", {
message: `final encode: chunk ${done}/${byKey.size} (${(p.span.a / fps).toFixed(1)}–${(p.span.b / fps).toFixed(1)}s) ` +
@@ -5422,6 +5450,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null,
// The memo keeps what this cut is made of: a frame or segment gone is forgotten.
memo.pruneUnseen();
await memo.save();
+ POOLED_CHUNKS.delete(dir);
const keep = new Set([...plan.map((p) => path.basename(p.file)), path.basename(audio), CHUNKS_RECORD, "concat.txt"]);
for (const name of await readdir(dir)) if (!keep.has(name)) await rm(path.join(dir, name), { force: true });
@@ -6733,6 +6762,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// umtool take --keep-frames) has them SET ASIDE in `<out>/.keep-frames/`
// instead, for a later `take --from` (prune-frames.mjs).
const pruneFrames = async () => {
+ // The render pool's cap (render-pool.mjs), at most once an hour: least recently used, never a linked object.
+ const pp = await poolPruneThrottled(await poolFor(outDir));
+ if (pp?.evicted) EMIT("note", { message: `render pool: evicted ${pp.evicted} object(s), ${(pp.bytes / (1 << 20)).toFixed(0)} MiB, least recently used first (over its ${(pp.maxBytes / 1024 ** 3).toFixed(0)} GB cap)` });
if (opts.keepFrames || hyper || (deck && opts.noChrome)) return;
const aside = (await keepFramesAsked(outRoot)) ? keptFramesDir(outRoot, variant) : null;
const p = await pruneChromeFrames(outDir, { setAside: aside });
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -45,6 +45,7 @@ import { GSAP_FILE } from "./chrome-deck.mjs";
import { fxGeometry, threadShotOf } from "./deck.mjs";
import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs";
import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs";
+import { poolFor, poolFrame, poolFrameEvents, poolPutFrames } from "./render-pool.mjs";
import { regionCaching, regionModule } from "./modules/index.mjs";
const run = promisify(execFile);
@@ -1046,7 +1047,16 @@ export async function composeChrome({
if (got !== frames) {
throw new Error(`the ${region} render wrote ${got} frames to ${target}, expected ${frames} (${size.duration}s at ${rate} fps)`);
}
- if (fk) await writeFrameKeys(target, fk);
+ if (fk) {
+ await writeFrameKeys(target, fk);
+ // Each distinct frame into the render pool (render-pool.mjs).
+ const pool = await poolFor(base);
+ if (pool) {
+ const first = new Map();
+ fk.forEach((k, i) => first.has(k) || first.set(k, path.join(target, frameName(i + 1))));
+ await poolPutFrames(pool, [...first]);
+ }
+ }
await writeFile(keyFile, key + "\n", "utf8");
}
return { ...result, frames: target, ...(fk ? { reused: 0, captured: frames } : {}) };
@@ -1177,6 +1187,21 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
});
}
if (!dirs.length && !dedup) return null;
+ // The render pool (render-pool.mjs): a frame of this key drawn by any take of any project.
+ const pool = await poolFor(base);
+ if (pool) {
+ let hits = 0;
+ let misses = 0;
+ for (const k of new Set(fk)) {
+ if (have.has(k)) continue;
+ const f = await poolFrame(pool, k);
+ if (f) {
+ have.set(k, f);
+ hits += 1;
+ } else misses += 1;
+ }
+ await poolFrameEvents(pool, hits, misses);
+ }
const missing = [];
for (let i = 0; i < fk.length; i += 1) if (!have.has(fk[i])) missing.push(i);
// `need` (a Set of 0-based frames): only those are drawn; a frame on no
@@ -1205,6 +1230,7 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
const got = await framesOnDisk(capDir);
if (got !== capture.length) throw new Error(`the ${region} frame capture wrote ${got} frames to ${capDir}, expected ${capture.length}`);
capture.forEach((i, j) => have.set(fk[i], path.join(capDir, frameName(j + 1))));
+ if (pool) await poolPutFrames(pool, capture.map((i, j) => [fk[i], path.join(capDir, frameName(j + 1))]));
}
// Which frame on disk each frame is. One key is often drawn by many frames
diff --git a/umtool/report-to-video/hardcut-deck.test.mjs b/umtool/report-to-video/hardcut-deck.test.mjs
@@ -127,4 +127,83 @@ test("a hard-cut deck build: keyed chunks, and the deck drawn only where a chunk
assert.ok(Number(/read (\d+) of/.exec(read)[1]) <= 32, read);
assert.ok(drawn().slice(before).every((n) => n <= 32), `drawn ${drawn().slice(before)}`);
assert.deepEqual((await verifyBuild(manifestPath, {})).problems, []);
+
+ // --chrome-only over the same segments: the same chunks, nothing drawn or encoded.
+ const runs = drawn().length;
+ notes.length = 0;
+ await buildVideo({ manifestPath, opts: { chromeOnly: true } });
+ assert.ok(notes.some((m) => /^final encode: 3\/3 chunk\(s\) unchanged/.test(m)), notes.join("\n"));
+ assert.equal(drawn().length, runs);
+ assert.deepEqual(record().chunks.map((c) => c.key), rec3.chunks.map((c) => c.key));
+});
+
+test("the render pool: another project's build of the same cut takes every chunk and the sound from it", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => {
+ const root = mkdtempSync(path.join(tmpdir(), "rtv-hcpool-"));
+ const env = { bin: process.env.HYPERFRAMES_BIN, log: process.env.HF_LOG, pool: process.env.UMTOOL_RENDER_POOL };
+ t.after(() => {
+ for (const [k, v] of [["HYPERFRAMES_BIN", env.bin], ["HF_LOG", env.log], ["UMTOOL_RENDER_POOL", env.pool]]) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ setProgressMode("human");
+ rmSync(root, { recursive: true, force: true });
+ });
+ const stub = path.join(root, "hf-stub.mjs");
+ writeFileSync(stub, STUB);
+ chmodSync(stub, 0o755);
+ process.env.HYPERFRAMES_BIN = stub;
+ const log = path.join(root, "renders.log");
+ process.env.HF_LOG = log;
+ const pool = path.join(root, "pool");
+ process.env.UMTOOL_RENDER_POOL = pool;
+ const drawn = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(Number) : []);
+ const project = (name) => {
+ const dir = path.join(root, name);
+ mkdirSync(path.join(dir, "stills"), { recursive: true });
+ for (const [n, c] of [["one", "334455"], ["two", "554433"]]) {
+ const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x${c}:size=320x180`, "-frames:v", "1", path.join(dir, "stills", `${n}.png`)]);
+ assert.equal(r.status, 0, String(r.stderr));
+ }
+ const manifestPath = path.join(dir, "video.manifest.json");
+ writeFileSync(manifestPath, JSON.stringify({
+ slug: "hc", title: "Pooled", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, render: RENDER,
+ timeline: [
+ { id: "i1", type: "image", src: "stills/one.png", seconds: 2 },
+ { id: "i2", type: "image", src: "stills/two.png", seconds: 2 },
+ ],
+ }));
+ return manifestPath;
+ };
+ const notes = [];
+ setProgressMode((e) => {
+ if (e.ev === "note") notes.push(e.message);
+ });
+ await buildVideo({ manifestPath: project("a"), opts: {} });
+ const runs = drawn().length;
+ const { poolStats } = await import("./render-pool.mjs");
+ const s1 = await poolStats(pool);
+ assert.equal(s1.kinds.chunk.objects, 2);
+ assert.equal(s1.kinds.sound.objects, 1);
+ assert.ok(s1.kinds.frame.objects >= 1, "the deck's distinct frames");
+
+ // Project b: the same cut, built anew -- from the pool.
+ notes.length = 0;
+ const mb = project("b");
+ await buildVideo({ manifestPath: mb, opts: {} });
+ assert.ok(notes.some((m) => /^final encode: 2\/2 chunk\(s\) unchanged \(.*2 from the render pool\)/.test(m)), notes.join("\n"));
+ assert.ok(notes.some((m) => /sound from the render pool/.test(m)), notes.join("\n"));
+ assert.equal(drawn().length, runs, "no deck frame drawn");
+ assert.deepEqual((await verifyBuild(mb, {})).problems, []);
+ const s2 = await poolStats(pool);
+ assert.ok(s2.kinds.chunk.hits >= 2 && s2.kinds.sound.hits >= 1);
+ assert.equal(s2.kinds.chunk.objects, 2, "nothing stored twice");
+
+ // A build stopped mid-encode, run again: what it encoded is on disk or in
+ // the pool; only the rest is encoded (here: one chunk lost, taken back).
+ const chunksB = path.join(root, "b", "out", "sourced", CHUNKS_DIR);
+ const rec = JSON.parse(readFileSync(path.join(chunksB, CHUNKS_RECORD), "utf8"));
+ rmSync(path.join(chunksB, rec.chunks[1].file));
+ notes.length = 0;
+ await buildVideo({ manifestPath: mb, opts: {} });
+ assert.ok(notes.some((m) => /^final encode: 2\/2 chunk\(s\) unchanged \(.*1 from the render pool\)/.test(m)), notes.join("\n"));
});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -29,6 +29,7 @@
"./clip-blur": "./clip-blur.mjs",
"./clip-words": "./clip-words.mjs",
"./compose-chrome": "./compose-chrome.mjs",
+ "./render-pool": "./render-pool.mjs",
"./counter": "./counter.mjs",
"./cues": "./cues.mjs",
"./cut-points": "./cut-points.mjs",
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -32,6 +32,7 @@ import { applyJoinState, endMediaOf } from "./post-join.mjs";
import { applyVisitState } from "./post-link-visit.mjs";
import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs";
import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs";
+import { poolFetch, poolFor, poolPut } from "./render-pool.mjs";
const r3 = (v) => Math.round(v * 1000) / 1000;
const num = (v) => String(r3(v));
@@ -1012,6 +1013,12 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
emit("note", { message: `${entry.id}: post item unchanged — its segment kept` });
return seg;
}
+ // The render pool (render-pool.mjs): this item, by this key, built by any take of any project.
+ const pool = await poolFor(outDir);
+ if (pool && (await poolFetch(pool, "post", key, { "seg.mp4": seg, "post.json": record }))) {
+ emit("note", { message: `${entry.id}: post item from the render pool (key ${key.slice(0, 12)})` });
+ return seg;
+ }
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
const zoomPlan = postZoomPlan(entry, render, plan.total, plan.narration);
// Its captions (post-caption.mjs): each waits for a zoom it would be up with, and is gone by the media phase (a stack card).
@@ -1065,6 +1072,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
// Through a rename: a record `--from` linked in (another take's) is replaced, never written through.
await writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8");
await rename(`${record}.tmp`, record);
+ if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record });
emit("note", {
message: narration
? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)`
diff --git a/umtool/report-to-video/render-pool.mjs b/umtool/report-to-video/render-pool.mjs
@@ -0,0 +1,370 @@
+// THE RENDER POOL: a content-addressed cache of built units, shared by every
+// take of every project (operator, 4 Nov: "every clip that could be inserted
+// into a video is put into a shared cached clip pool by all input params by
+// default, kind of like archilyzer videos").
+//
+// Each built unit is stored ONCE, under the hash of its kind, its kind's
+// renderer salt and the full key the build already computes for it:
+//
+// post a post item's segment and its record (post-render.mjs
+// postSegmentKeyOf: the entry, its plan, the box, the encode, its
+// files' stamps, the narration…): `seg.mp4`, `post.json`
+// clip a clip (or still) segment and its cut record (segment-cache.mjs
+// segmentKey: the ffmpeg argv with every input by its identity):
+// `seg.mp4`, `cut.json`
+// chunk a chunk of the final encode (chunked-encode.mjs chunkKey: its
+// inputs' contents, its graph in its own clock -- position-free):
+// `chunk.mp4`
+// sound a cut's sound (the hard-cut pins and encode, or the crossfade's
+// graph): `sound.m4a`
+// frame one chrome frame, by its frame key (frame-keys.mjs: what it
+// draws): `<key>.png`, a file of its own
+//
+// Every build looks in the pool when its own out/ misses, and HARD-LINKS a hit
+// into the take; a unit it builds is linked into the pool (through a tmp
+// directory renamed into place, so a reader never sees half an object). A
+// link, never a copy: the pool costs no disk while a take holds the same
+// inode, and a build REPLACES its files (rename), never writes through them,
+// so neither side can change the other's bytes. Another filesystem than the
+// pool's (EXDEV) is simply no pool.
+//
+// WHERE: `UMTOOL_RENDER_POOL` (a directory), else `<media root>/.render-pool`
+// (UMTOOL_MEDIA_DIR's, else the reports root's) -- for an out/ under that
+// root only, so a test's or a scratch copy's build never writes into the
+// operator's pool. `UMTOOL_RENDER_POOL=0` turns it off.
+//
+// DISK: `UMTOOL_RENDER_POOL_MAX_GB` (default 30) caps the bytes ONLY the pool
+// holds (a file with one link: no take has it). Over the cap, objects go least
+// recently used first (an object's directory -- a frame's shard -- is touched
+// on every hit); an object a take still links is never evicted, so neither is
+// one a pinned or picked take holds, nor one a running build just made or
+// took. `umtool pool stats|prune|verify`.
+//
+// Hits and misses are appended to `<pool>/events.ndjson` (a line each, an
+// atomic append), which `stats` reads.
+//
+// Plain node; every path is a parameter or the environment.
+
+import { createHash, randomBytes } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { appendFile, link, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+import { MEDIA_ROOT } from "../lib/paths.mjs";
+
+/**
+ * The kinds, each with its renderer SALT: bumped when code changes what a
+ * kind's unit is for unchanged inputs (every object of the kind is then a
+ * miss once). A kind's own key may carry a salt of its own as well
+ * (post-render POST_SEGMENT_RV, SEGMENT_KEY_VERSION, CHUNK_KEY_VERSION,
+ * FRAME_KEY_VERSION): those are in the keys this hashes.
+ */
+export const POOL_KINDS = Object.freeze({
+ post: { salt: 1, noun: "post segments" },
+ clip: { salt: 1, noun: "clip segments" },
+ chunk: { salt: 1, noun: "final-encode chunks" },
+ sound: { salt: 1, noun: "cut sounds" },
+ frame: { salt: 1, noun: "chrome frames" },
+});
+
+/** The pool's default cap on the bytes only it holds, in GB. */
+export const POOL_MAX_GB_DEFAULT = 30;
+const META = "meta.json";
+const EVENTS = "events.ndjson";
+const sha256 = (s) => createHash("sha256").update(s).digest("hex");
+
+/**
+ * The pool for a build whose out dir is `outDir`: a directory, or null (off,
+ * or an out/ outside the media root with no pool named).
+ */
+export async function poolFor(outDir, env = process.env) {
+ const named = env.UMTOOL_RENDER_POOL;
+ if (named === "0" || named === "off") return null;
+ if (named) return path.resolve(named);
+ const root = await realpath(MEDIA_ROOT).catch(() => MEDIA_ROOT);
+ const out = await realpath(outDir).catch(() => path.resolve(outDir));
+ if (!(out === root || out.startsWith(root + path.sep))) return null;
+ return path.join(root, ".render-pool");
+}
+
+/** An object's id: its kind, the kind's salt and the build's key, hashed. */
+export function poolId(kind, key) {
+ const k = POOL_KINDS[kind];
+ if (!k) throw new Error(`render pool: no kind ${kind}`);
+ return sha256(JSON.stringify({ kind, salt: k.salt, key: String(key) })).slice(0, 40);
+}
+
+/** Where an object lives: a directory for a unit, a file for a frame. */
+export function objectPath(pool, kind, key) {
+ const id = poolId(kind, key);
+ return kind === "frame" ? path.join(pool, kind, id.slice(0, 2), `${id}.png`) : path.join(pool, kind, id.slice(0, 2), id);
+}
+
+const MADE = new Set();
+async function event(pool, kind, hit) {
+ if (!MADE.has(pool)) {
+ await mkdir(pool, { recursive: true }).catch(() => {});
+ MADE.add(pool);
+ }
+ await appendFile(path.join(pool, EVENTS), JSON.stringify({ at: Date.now(), kind, hit }) + "\n").catch(() => {});
+}
+
+/** Hard-link `src` at `dst` through a rename (whatever was at `dst` replaced); false when it cannot (EXDEV, gone). */
+async function linkInto(src, dst) {
+ const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.${randomBytes(3).toString("hex")}.pool`);
+ try {
+ await link(src, tmp);
+ } catch {
+ return false;
+ }
+ await rename(tmp, dst);
+ return true;
+}
+
+const touch = (p) => utimes(p, new Date(), new Date()).catch(() => {});
+
+/**
+ * A unit from the pool: each of `files` (`{ name: dest }`) hard-linked at its
+ * dest. True on a hit (every file linked), false on a miss.
+ */
+export async function poolFetch(pool, kind, key, files) {
+ if (!pool) return false;
+ const dir = objectPath(pool, kind, key);
+ const meta = await readFile(path.join(dir, META), "utf8").then((t) => JSON.parse(t), () => null);
+ const names = Object.keys(files);
+ if (!meta || names.some((n) => !meta.files?.[n])) {
+ await event(pool, kind, false);
+ return false;
+ }
+ for (const n of names) {
+ if (!(await linkInto(path.join(dir, n), files[n]))) {
+ await event(pool, kind, false);
+ return false;
+ }
+ }
+ await touch(dir);
+ await event(pool, kind, true);
+ return true;
+}
+
+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")));
+ });
+}
+
+/**
+ * A unit into the pool: each of `files` (`{ name: src }`) hard-linked into a
+ * tmp directory with its `meta.json` (each file's bytes and sha256), renamed
+ * into place. An object already there is kept. Never throws: a pool that
+ * cannot take it (another filesystem, a full disk) is no pool.
+ */
+export async function poolPut(pool, kind, key, files, extra = {}) {
+ if (!pool) return false;
+ const dir = objectPath(pool, kind, key);
+ try {
+ if ((await stat(path.join(dir, META)).catch(() => null))?.isFile()) return true;
+ const shard = path.dirname(dir);
+ await mkdir(shard, { recursive: true });
+ const tmp = path.join(path.dirname(shard), `.tmp-${process.pid}-${randomBytes(4).toString("hex")}`);
+ await mkdir(tmp);
+ try {
+ const meta = { kind, key: String(key), salt: POOL_KINDS[kind].salt, at: new Date().toISOString(), files: {}, ...extra };
+ for (const [n, src] of Object.entries(files)) {
+ await link(src, path.join(tmp, n));
+ const st = await stat(src);
+ meta.files[n] = { bytes: st.size, sha256: await fileSha(src) };
+ }
+ await writeFile(path.join(tmp, META), JSON.stringify(meta, null, 1) + "\n", "utf8");
+ await rename(tmp, dir).catch(async (e) => {
+ if (e?.code !== "EEXIST" && e?.code !== "ENOTEMPTY") throw e;
+ });
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** A frame's file in the pool, when it has one (its shard touched), else null. */
+export async function poolFrame(pool, key) {
+ if (!pool) return null;
+ const f = objectPath(pool, "frame", key);
+ if (!(await stat(f).catch(() => null))?.isFile()) return null;
+ await touch(path.dirname(f));
+ return f;
+}
+
+/** Frames into the pool: each `[key, file]` linked in (one already there kept). Returns how many went in. */
+export async function poolPutFrames(pool, pairs) {
+ if (!pool || !pairs.length) return 0;
+ let n = 0;
+ const shards = new Set();
+ for (const [key, src] of pairs) {
+ const f = objectPath(pool, "frame", key);
+ if (!shards.has(path.dirname(f))) {
+ await mkdir(path.dirname(f), { recursive: true }).catch(() => {});
+ shards.add(path.dirname(f));
+ }
+ if ((await lstat(f).catch(() => null))?.isFile()) continue;
+ if (await linkInto(src, f).catch(() => false)) n += 1;
+ }
+ return n;
+}
+
+/** Record a batch of frame lookups (one line, not one per frame). */
+export async function poolFrameEvents(pool, hits, misses) {
+ if (!pool || !(hits + misses)) return;
+ await mkdir(pool, { recursive: true }).catch(() => {});
+ await appendFile(path.join(pool, EVENTS), JSON.stringify({ at: Date.now(), kind: "frame", hits, misses }) + "\n").catch(() => {});
+}
+
+// ---- the pool as a whole: stats, prune, verify -------------------------------
+
+/** Every object: `{ kind, path, bytes, onlyPool, used }` (`onlyPool`: the bytes no take links). */
+export async function poolObjects(pool) {
+ const out = [];
+ for (const kind of Object.keys(POOL_KINDS)) {
+ const kdir = path.join(pool, kind);
+ for (const shard of await readdir(kdir).catch(() => [])) {
+ if (shard.startsWith(".")) continue;
+ const sdir = path.join(kdir, shard);
+ const sst = await stat(sdir).catch(() => null);
+ if (!sst?.isDirectory()) continue;
+ for (const name of await readdir(sdir).catch(() => [])) {
+ const p = path.join(sdir, name);
+ const st = await lstat(p).catch(() => null);
+ if (!st) continue;
+ if (kind === "frame") {
+ if (!st.isFile()) continue;
+ out.push({ kind, path: p, bytes: st.size, onlyPool: st.nlink <= 1 ? st.size : 0, linked: st.nlink > 1, used: sst.mtimeMs });
+ continue;
+ }
+ if (!st.isDirectory()) continue;
+ let bytes = 0;
+ let only = 0;
+ let linked = false;
+ for (const f of await readdir(p).catch(() => [])) {
+ const fs = await lstat(path.join(p, f)).catch(() => null);
+ if (!fs?.isFile()) continue;
+ bytes += fs.size;
+ if (f === META || fs.nlink <= 1) only += fs.size;
+ else linked = true;
+ }
+ out.push({ kind, path: p, bytes, onlyPool: linked ? 0 : only, linked, used: st.mtimeMs });
+ }
+ }
+ }
+ return out;
+}
+
+/** The cap on the bytes only the pool holds: `UMTOOL_RENDER_POOL_MAX_GB`, else the default. */
+export function poolMaxBytes(env = process.env) {
+ const gb = Number(env.UMTOOL_RENDER_POOL_MAX_GB);
+ return (Number.isFinite(gb) && gb >= 0 ? gb : POOL_MAX_GB_DEFAULT) * 1024 ** 3;
+}
+
+/**
+ * Size, what only the pool holds, hits and misses per kind (from the events,
+ * `since` ms), the biggest objects.
+ */
+export async function poolStats(pool, { since = 0, top = 10 } = {}) {
+ const objs = await poolObjects(pool);
+ const kinds = {};
+ for (const k of Object.keys(POOL_KINDS)) kinds[k] = { objects: 0, bytes: 0, onlyPool: 0, hits: 0, misses: 0 };
+ for (const o of objs) {
+ kinds[o.kind].objects += 1;
+ kinds[o.kind].bytes += o.bytes;
+ kinds[o.kind].onlyPool += o.onlyPool;
+ }
+ const text = await readFile(path.join(pool, EVENTS), "utf8").catch(() => "");
+ for (const line of text.split("\n")) {
+ if (!line) continue;
+ let e;
+ try {
+ e = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (!kinds[e.kind] || e.at < since) continue;
+ if (Number.isFinite(e.hits)) {
+ kinds[e.kind].hits += e.hits;
+ kinds[e.kind].misses += e.misses ?? 0;
+ } else if (e.hit) kinds[e.kind].hits += 1;
+ else kinds[e.kind].misses += 1;
+ }
+ const bytes = objs.reduce((n, o) => n + o.bytes, 0);
+ const onlyPool = objs.reduce((n, o) => n + o.onlyPool, 0);
+ const biggest = [...objs].sort((a, b) => b.bytes - a.bytes).slice(0, top).map((o) => ({ kind: o.kind, path: o.path, bytes: o.bytes, linked: o.onlyPool === 0 }));
+ return { pool, objects: objs.length, bytes, onlyPool, maxOnlyPool: poolMaxBytes(), kinds, biggest };
+}
+
+/**
+ * Evict least-recently-used objects that no take links until the bytes only
+ * the pool holds are under `maxBytes`; tmp directories over a day old go too.
+ * `dryRun` says what would go.
+ */
+export async function poolPrune(pool, { maxBytes = poolMaxBytes(), dryRun = false } = {}) {
+ const objs = await poolObjects(pool);
+ let only = objs.reduce((n, o) => n + o.onlyPool, 0);
+ const before = only;
+ const gone = [];
+ // An object a take links (any file with a second name) is never a candidate.
+ const free = objs.filter((o) => !o.linked).sort((a, b) => a.used - b.used);
+ for (const o of free) {
+ if (only <= maxBytes) break;
+ if (!dryRun) await rm(o.path, { recursive: true, force: true });
+ only -= o.onlyPool;
+ gone.push({ kind: o.kind, path: o.path, bytes: o.bytes });
+ }
+ for (const kind of Object.keys(POOL_KINDS)) {
+ for (const name of await readdir(path.join(pool, kind)).catch(() => [])) {
+ if (!name.startsWith(".tmp-")) continue;
+ const p = path.join(pool, kind, name);
+ const st = await stat(p).catch(() => null);
+ if (st && Date.now() - st.mtimeMs > 86_400_000 && !dryRun) await rm(p, { recursive: true, force: true });
+ }
+ }
+ return { before, after: only, maxBytes, evicted: gone.length, bytes: gone.reduce((n, o) => n + o.bytes, 0), gone };
+}
+
+/**
+ * Check a sample of objects: each unit's files against the sha256 its meta
+ * recorded, each frame a PNG. Returns the problems (and removes nothing).
+ */
+export async function poolVerify(pool, { sample = 50, all = false } = {}) {
+ const objs = await poolObjects(pool);
+ const pick = all ? objs : [...objs].sort(() => Math.random() - 0.5).slice(0, sample);
+ const problems = [];
+ for (const o of pick) {
+ if (o.kind === "frame") {
+ const head = await readFile(o.path).then((b) => b.subarray(0, 8).toString("hex"), () => null);
+ if (head !== "89504e470d0a1a0a") problems.push(`${o.path}: not a PNG`);
+ continue;
+ }
+ const meta = await readFile(path.join(o.path, META), "utf8").then((t) => JSON.parse(t), () => null);
+ if (!meta) {
+ problems.push(`${o.path}: no ${META}`);
+ continue;
+ }
+ for (const [n, f] of Object.entries(meta.files ?? {})) {
+ const got = await fileSha(path.join(o.path, n)).catch(() => null);
+ if (got !== f.sha256) problems.push(`${o.path}/${n}: ${got ? "its bytes are not the ones put in" : "missing"}`);
+ }
+ }
+ return { checked: pick.length, of: objs.length, problems };
+}
+
+/** Prune at most once an hour per pool (the end of a build calls this). */
+export async function poolPruneThrottled(pool, env = process.env) {
+ if (!pool) return null;
+ const mark = path.join(pool, ".pruned");
+ const st = await stat(mark).catch(() => null);
+ if (st && Date.now() - st.mtimeMs < 3_600_000) return null;
+ await mkdir(pool, { recursive: true }).catch(() => {});
+ await writeFile(mark, new Date().toISOString() + "\n").catch(() => {});
+ return poolPrune(pool, { maxBytes: poolMaxBytes(env) }).catch(() => null);
+}
diff --git a/umtool/report-to-video/render-pool.test.mjs b/umtool/report-to-video/render-pool.test.mjs
@@ -0,0 +1,237 @@
+// The render pool (render-pool.mjs): put and fetch by hard link, hits and
+// misses, the cap's least-recently-used eviction that never takes a linked
+// object, verify, where the pool is -- and the KEYS: every input that changes
+// a unit's pixels, sound or timing changes the key the pool files it under
+// (each field of a fixture mutated in turn).
+//
+// Run with: node --test umtool/report-to-video/render-pool.test.mjs
+import assert from "node:assert/strict";
+import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ POOL_KINDS, objectPath, poolFetch, poolFor, poolFrame, poolId, poolPrune, poolPut, poolPutFrames, poolStats, poolVerify,
+} from "./render-pool.mjs";
+
+const tmp = (p) => mkdtempSync(path.join(tmpdir(), p));
+
+test("put links a unit in; fetch links it out (the same inode); a miss is a miss; hits and misses counted", async () => {
+ const dir = tmp("pool-");
+ try {
+ const pool = path.join(dir, "pool");
+ const a = path.join(dir, "a");
+ mkdirSync(a);
+ writeFileSync(path.join(a, "seg.mp4"), "picture");
+ writeFileSync(path.join(a, "rec.json"), "{}");
+ assert.equal(await poolFetch(pool, "clip", "k1", { "seg.mp4": path.join(a, "x.mp4") }), false);
+ assert.equal(await poolPut(pool, "clip", "k1", { "seg.mp4": path.join(a, "seg.mp4"), "cut.json": path.join(a, "rec.json") }), true);
+ const b = path.join(dir, "b");
+ mkdirSync(b);
+ writeFileSync(path.join(b, "seg.mp4"), "an older build"); // replaced, through a rename
+ assert.equal(await poolFetch(pool, "clip", "k1", { "seg.mp4": path.join(b, "seg.mp4"), "cut.json": path.join(b, "cut.json") }), true);
+ assert.equal(statSync(path.join(b, "seg.mp4")).ino, statSync(path.join(a, "seg.mp4")).ino, "one inode: the pool costs no disk");
+ assert.equal(readFileSync(path.join(b, "seg.mp4"), "utf8"), "picture");
+ // Another kind, the same key: another object.
+ assert.notEqual(poolId("post", "k1"), poolId("clip", "k1"));
+ assert.equal(await poolFetch(pool, "post", "k1", { "seg.mp4": path.join(b, "p.mp4") }), false);
+ const st = await poolStats(pool);
+ assert.equal(st.kinds.clip.hits, 1);
+ assert.equal(st.kinds.clip.misses, 1);
+ assert.equal(st.kinds.post.misses, 1);
+ assert.equal(st.kinds.clip.objects, 1);
+ assert.equal(st.onlyPool, 0, "both takes link it");
+ assert.deepEqual((await poolVerify(pool, { all: true })).problems, []);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("frames: one file per frame key, linked; a second put of a key keeps the first", async () => {
+ const dir = tmp("pool-f-");
+ try {
+ const pool = path.join(dir, "pool");
+ const f1 = path.join(dir, "f1.png");
+ writeFileSync(f1, Buffer.from("89504e470d0a1a0a00", "hex"));
+ const f2 = path.join(dir, "f2.png");
+ writeFileSync(f2, Buffer.from("89504e470d0a1a0a01", "hex"));
+ assert.equal(await poolFrame(pool, "fk1"), null);
+ assert.equal(await poolPutFrames(pool, [["fk1", f1], ["fk1", f2]]), 1);
+ const got = await poolFrame(pool, "fk1");
+ assert.equal(statSync(got).ino, statSync(f1).ino);
+ assert.deepEqual((await poolVerify(pool, { all: true })).problems, []);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("prune: least recently used first, only what no take links, down to the cap; verify finds changed bytes", async () => {
+ const dir = tmp("pool-p-");
+ try {
+ const pool = path.join(dir, "pool");
+ const src = path.join(dir, "src");
+ mkdirSync(src);
+ const put = async (k, bytes) => {
+ const f = path.join(src, `${k}.mp4`);
+ writeFileSync(f, "x".repeat(bytes));
+ await poolPut(pool, "chunk", k, { "chunk.mp4": f });
+ return f;
+ };
+ const fa = await put("a", 1000);
+ const fb = await put("b", 1000);
+ const fc = await put("c", 1000);
+ // Only the pool holds a and b; c is still linked by a "take".
+ rmSync(fa);
+ rmSync(fb);
+ void fc;
+ const old = new Date(Date.now() - 3600_000);
+ utimesSync(objectPath(pool, "chunk", "a"), old, old); // a used longest ago
+ const dry = await poolPrune(pool, { maxBytes: 1500, dryRun: true });
+ assert.equal(dry.evicted, 1);
+ assert.match(dry.gone[0].path, new RegExp(poolId("chunk", "a")));
+ const done = await poolPrune(pool, { maxBytes: 0 });
+ assert.equal(done.evicted, 2, "a and b go; c, linked, never");
+ assert.ok(existsSync(objectPath(pool, "chunk", "c")));
+ // A file changed under the pool: verify says so.
+ const c = path.join(objectPath(pool, "chunk", "c"), "chunk.mp4");
+ rmSync(c);
+ writeFileSync(c, "y");
+ assert.equal((await poolVerify(pool, { all: true })).problems.length, 1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("poolFor: the named pool, off with 0, and none for an out/ outside the media root", async () => {
+ assert.equal(await poolFor("/x/out", { UMTOOL_RENDER_POOL: "/p" }), "/p");
+ assert.equal(await poolFor("/x/out", { UMTOOL_RENDER_POOL: "0" }), null);
+ assert.equal(await poolFor(path.join(tmpdir(), "nowhere"), {}), null, "a test's or a scratch copy's build never writes the operator's pool");
+ assert.deepEqual(Object.keys(POOL_KINDS).sort(), ["chunk", "clip", "frame", "post", "sound"]);
+});
+
+// ---- the keys: every field that changes a unit changes its key ----------------
+
+/** Every leaf path of an object: [["a"], ["b", "c"], …]. */
+function leaves(o, at = []) {
+ if (o === null || typeof o !== "object") return [at];
+ const ks = Object.keys(o);
+ if (!ks.length) return [at];
+ return ks.flatMap((k) => leaves(o[k], [...at, k]));
+}
+function mutate(o, at) {
+ const c = structuredClone(o);
+ let p = c;
+ for (const k of at.slice(0, -1)) p = p[k];
+ const k = at[at.length - 1];
+ const v = p[k];
+ p[k] = typeof v === "number" ? v + 1 : typeof v === "boolean" ? !v : v === null ? "x" : `${v}~`;
+ return c;
+}
+
+test("post key: every field of the entry, the box, the render's palette, fonts and fps, the encode, the files' stamps", async () => {
+ const { postSegmentKey, postSegmentKeyOf } = await import("./post-render.mjs");
+ const base = {
+ entry: {
+ type: "post", id: "p1", post: "a/1", platform: "x", author: "A", handle: "a", date: "2026-10-19T12:00:00Z", text: "words",
+ media: [{ src: "m.png", type: "image", crop: { top: 0.1 } }], narration: { rate: 1.1, takes: [{ file: "t.wav", lufs: -20 }], pick: 0 },
+ hold: 12, follow: { dim: 0.7 }, thread: { dim: 0.5 },
+ },
+ box: { width: 1600, height: 880 },
+ place: ["pad=1920:1080"],
+ render: { palette: { bg: "#000", fg: "#fff" }, fontRegular: "/f/r.ttf", fontBold: "/f/b.ttf", fps: 30, postNarration: { rate: 1.08, linger: 0.85 } },
+ encode: ["-crf", "21", "-preset", "slow"],
+ stamps: ["/p/m.png:100:1", "/p/t.wav:200:2"],
+ plan: { narration: { at: 0.25, seconds: 10 }, follow: { blocks: [1] } },
+ };
+ const key = (f) => postSegmentKey(postSegmentKeyOf({ ...f, take: { file: "t.wav" } }));
+ const k0 = key(base);
+ const fields = ["entry", "box", "place", "encode", "stamps", "plan"].flatMap((top) => leaves(base[top]).map((p) => [top, ...p]));
+ fields.push(["render", "palette", "bg"], ["render", "fontRegular"], ["render", "fontBold"], ["render", "fps"], ["render", "postNarration", "linger"]);
+ const missed = fields.filter((at) => key(mutate(base, at)) === k0).map((at) => at.join("."));
+ assert.deepEqual(missed, [], "a post segment's key covers every input that draws or times it");
+ assert.ok(fields.length > 25, `${fields.length} fields mutated`);
+});
+
+test("chunk key: the segment, the chrome's frames, the overlay's place, the encode settings, the span's length", async () => {
+ const { chunkVideoArgs } = await import("./build-video.mjs");
+ const { chunkKey } = await import("./chunked-encode.mjs");
+ const render = { width: 64, height: 36, fps: 30, transition: 0, preset: "slow", crf: 21, audioRate: 48000, audioChannels: 2 };
+ const region = { name: "deck", frames: "/c/deck-frames", x: 0, y: 20, width: 64, height: 16 };
+ const keyOf = ({ r = render, reg = region, segId = "s1", seqId = "d1", durs = [10, 12], span = { a: 300, b: 660 } } = {}) => {
+ const starts = [0, durs[0]];
+ const proto = chunkVideoArgs({ segments: ["/x/a.mp4", "/x/b.mp4"], durs, starts, span, D: 0, render: r, chrome: { regions: [reg] }, totalFrames: Math.round((durs[0] + durs[1]) * 30), outPath: "" });
+ const ids = proto.inputs.map((x) => (x.kind === "seg" ? { seg: segId } : { seq: seqId }));
+ return chunkKey({ keyArgv: proto.keyArgv, inputs: ids, ffmpeg: "ff" });
+ };
+ const k0 = keyOf();
+ const changed = {
+ segment: keyOf({ segId: "s2" }), frames: keyOf({ seqId: "d2" }),
+ crf: keyOf({ r: { ...render, crf: 22 } }), preset: keyOf({ r: { ...render, preset: "medium" } }), fps: keyOf({ r: { ...render, fps: 25 } }),
+ x: keyOf({ reg: { ...region, x: 2 } }), y: keyOf({ reg: { ...region, y: 2 } }), length: keyOf({ span: { a: 300, b: 650 }, durs: [10, 11.6667] }),
+ };
+ for (const [what, k] of Object.entries(changed)) assert.notEqual(k, k0, `${what} changes the chunk's key`);
+ // A segment before it grew: the chunk moved, its key the same (position-free).
+ assert.equal(keyOf({ durs: [11, 12], span: { a: 330, b: 690 } }), k0);
+});
+
+test("sound key: each segment's length in the cut, its joins, the rate, the channels, the bitrate", async () => {
+ const { hardCutSoundArgs, withCutEdits } = await import("./build-video.mjs");
+ const render = { fps: 30, audioRate: 48000, audioChannels: 2, audioBitrate: "160k" };
+ const argv = ({ durs = [10, 12], joins = null, r = render } = {}) => {
+ const a = hardCutSoundArgs({ durs, joins, render: r });
+ return JSON.stringify([a.pin(0, "<in>", "<pin>"), a.pin(1, "<in>", "<pin>"), a.encode("<l>", "<o>")]);
+ };
+ const k0 = argv();
+ assert.notEqual(argv({ durs: [10, 12.0333] }), k0);
+ assert.notEqual(argv({ joins: withCutEdits(null, 2, { mutes: new Map([[0, 3]]) }) }), k0);
+ assert.notEqual(argv({ r: { ...render, audioRate: 44100 } }), k0);
+ assert.notEqual(argv({ r: { ...render, audioChannels: 1 } }), k0);
+ assert.notEqual(argv({ r: { ...render, audioBitrate: "128k" } }), k0);
+});
+
+test("clip key: its ffmpeg argv, each input file's contents, its cut record, the ffmpeg binary", async () => {
+ const { segmentKey } = await import("./segment-cache.mjs");
+ const dir = tmp("pool-k-");
+ try {
+ const f = path.join(dir, "in.mp4");
+ writeFileSync(f, "source");
+ const key = (o = {}) => segmentKey({ argv: ["-i", f, "-crf", "21"], record: { id: "c1", snap: 1.2 }, outDir: dir, ffmpeg: "ffmpeg", ...o });
+ const k0 = await key();
+ assert.notEqual(await key({ argv: ["-i", f, "-crf", "22"] }), k0);
+ assert.notEqual(await key({ record: { id: "c1", snap: 1.3 } }), k0);
+ writeFileSync(f, "source2");
+ assert.notEqual(await key(), k0, "an input's bytes");
+ // Two takes' out dirs: the same key (the out dir is `<out>` in it).
+ writeFileSync(f, "source");
+ const other = tmp("pool-k2-");
+ linkSync(f, path.join(other, "in.mp4"));
+ assert.equal(await segmentKey({ argv: ["-i", f, "-crf", "21"], record: { id: "c1", snap: 1.2 }, outDir: other, ffmpeg: "ffmpeg" }), k0);
+ rmSync(other, { recursive: true, force: true });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("umtool pool stats|prune|verify --json", async () => {
+ const { poolCommand } = await import("../lib/report/poolCli.mjs");
+ const dir = tmp("pool-cli-");
+ try {
+ const pool = path.join(dir, "pool");
+ const f = path.join(dir, "c.mp4");
+ writeFileSync(f, "chunk");
+ await poolPut(pool, "chunk", "k", { "chunk.mp4": f });
+ const out = [];
+ assert.equal(await poolCommand(["stats", "--pool", pool, "--json"], { log: (l) => out.push(l) }), 0);
+ assert.equal(JSON.parse(out[0]).kinds.chunk.objects, 1);
+ out.length = 0;
+ assert.equal(await poolCommand(["prune", "--pool", pool, "--max-gb", "0", "--dry-run", "--json"], { log: (l) => out.push(l) }), 0);
+ assert.equal(JSON.parse(out[0]).evicted, 0, "a linked object is never evicted");
+ out.length = 0;
+ assert.equal(await poolCommand(["verify", "--pool", pool, "--all"], { log: (l) => out.push(l) }), 0);
+ assert.match(out[0], /checked 1 of 1 object\(s\): all as put in/);
+ assert.equal(await poolCommand(["bogus", "--pool", pool], { log: () => {} }), 2);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/segment-cache.mjs b/umtool/report-to-video/segment-cache.mjs
@@ -31,6 +31,8 @@ import { createReadStream } from "node:fs";
import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
+import { poolFetch, poolFor, poolPut } from "./render-pool.mjs";
+
/** 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. */
@@ -159,7 +161,7 @@ async function sameBytes(a, b) {
* 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 }>}
+ * @returns {Promise<{ reused: false | "key" | "bytes" | "pool", 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}`);
@@ -177,6 +179,17 @@ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmp
emit("note", { message: `${id}: segment key matches but the file probes ${got ?? "unreadable"}s, not ${prev.segSeconds}s — rebuilt` });
}
}
+ // The render pool (render-pool.mjs): the same segment built by any take of any project.
+ const pool = noCache ? null : await poolFor(outDir);
+ if (pool && (await poolFetch(pool, "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }))) {
+ const rec = await readFile(cutRecordOf(seg), "utf8").then(JSON.parse, () => null);
+ const got = await probe(seg).catch(() => null);
+ if (rec?.segKey === key && got != null && Math.abs(got - rec.segSeconds) <= tol) {
+ emit("note", { message: `${id}: segment from the render pool (key ${key.slice(0, 12)})` });
+ return { reused: "pool", key, seconds: rec.segSeconds };
+ }
+ emit("note", { message: `${id}: the render pool's segment does not probe as recorded — rebuilt` });
+ }
const tmp = path.join(path.dirname(seg), `.${path.basename(seg, ".mp4")}.${process.pid}.partial.mp4`);
await rm(tmp, { force: true });
try {
@@ -191,6 +204,7 @@ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmp
await rename(tmp, seg);
}
await replaceText(cutRecordOf(seg), JSON.stringify({ ...recordForKey(record), segKey: key, segSeconds: seconds }) + "\n");
+ if (pool) await poolPut(pool, "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) });
return { reused, key, seconds };
} finally {
await rm(tmp, { force: true });