commit c82fb58bb0a4dee913f5a9f6f292bbe47edaa1c9
parent f0f84cf1e62dd0708ac327ea789aa1b37a330e18
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 20:00:45 -0500
Merge lane/fast-fix-render: a small fix re-renders in minutes -- the hard-cut deck build is encoded in keyed chunks, one per segment, position-independent (a post that grows moves later chunks without re-encoding them), frame-exact (the concat's 0.3 s A/V drift gone); the cut's sound pinned per segment and keyed by its audio; the deck captured only where a chunk still to encode needs it; THE RENDER POOL -- post, clip, chunk, sound and frame units shared across every take by their keys, hard-linked, a size cap that never evicts a linked file, umtool pool stats|prune|verify (operator, 4 Nov: "every clip ... put into a shared cached clip pool by all input params by default"); fallbacks REPORT_VIDEO_CHUNKED=0, UMTOOL_CHROME_LAZY=0, UMTOOL_RENDER_POOL=0
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
20 files changed, 1810 insertions(+), 57 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A small fix to a report-video take re-renders in minutes, not half an hour.** A take renders hard cuts, and its final picture was one overlay pass over the whole cut on every take -- 12.6 of mid-6's 30 minutes, 26 of mid-7's 60 -- however small the change. The pass is now in keyed chunks, one segment's run each: `umtool take … --from <take>` re-encodes only the chunks of the post it touched, and a post that grew or shrank moves the chunks after it without changing them (the deck's frames after it are the same frames, later). The deck is drawn only where a chunk to encode reads it, so a take `--from` a pruned one no longer captures the whole deck again (12,347 captures, ~3 minutes on mid-7), and the cut's sound is keyed by each segment's audio, so a caption or a knob that moves no word keeps it. The picture is now frame-exact: the old pass laid each next segment at the longer of its picture and its sound, the footage up to 0.3 s behind the deck by the end of the cut.
- **A recorded take can be cleaned up, or given a stock synthetic voice, by the editor.** umtool's derived takes (`umtool posts narrate <p> <item> --derive <n> --op enhance|convert`, the post bench's **run AI on take #n**) said "not installed": the editor had no voice ops. It now has two, each a job on a new `voice` queue, its engine run behind the machine's heavy slot with a declared memory estimate: `pnpm ops voice-enhance` (denoise, soften the room, level — DeepFilterNet 3, or RNNoise through ffmpeg with nothing to install) and `pnpm ops voice-convert` (the timing and pitch contour kept, the timbre swapped — OpenVoice v2's converter or Seed-VC). The result is a 48 kHz mono WAV exactly as long as the take, so a derived take lines up with its source; a take recorded part by part is processed part by part. A conversion lands only on a STOCK voice of our own TTS engines (`zac`, `orpheus:leah`, `kokoro:am_michael`): a file or a recording is refused as a target, whatever it holds. The engines are installed by `archilyzer voice setup --engine <id>`, which says what it downloads and how big first; `settings.voice` picks the defaults (SETTINGS.md); OPERATING.md, "Enhance or convert a recorded take".
- **X post captures keep the post's context: what it quotes and what it answers.** A post video drew a reply ("you called me a Leftist…") with nothing it answered, because the archive row named no parent, no quote and no links. `capture-posts` on an X channel now reads, off the page it already loads, the post it answers (the archive's in-reply-to id, else the post directly above it) and the post it quotes — author, display name, check, date, words and media links — into the post's `capture.json` as `context`, with no extra page load (`"context": false` turns it off). `"contextOnly": true` loads one page per post for that alone (and the avatars it shows) and writes nothing else: `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<post id>", …],"contextOnly":true}' --wait`. Not verified against live X yet; the first run is the check. Needs a restart of the editor.
- **The X fetcher keeps quoted posts.** A timeline read never recorded what a post quotes (gallery-dl drops the quoted tweet unless asked). Every read now asks for it, and a quote becomes the quoting post's `quoted` — never archived as one of the account's own posts; an account quoting its own older post still archives that post when the walk reaches it. Posts already archived keep what they have (a re-fetch does not rewrite them; their context comes from `contextOnly`). Needs a restart of the editor.
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
@@ -2014,6 +2014,17 @@ pruning them, where a `--from` twin finds them. The blur is in the segments' pic
twin rebuilds the blurred clips, their crossfade batches and the final overlay pass, and reuses
the rest.
+**A small fix is a few minutes, not a whole render.** A take renders hard cuts (`--no-xfade`, unless it sets a transition), and
+its final picture is encoded in keyed CHUNKS, one segment's run each (report-to-video
+`chunked-encode.mjs`): a chunk is encoded again only when its segment or the deck frames over it
+changed. A post that grew or shrank moves every later chunk without changing it -- the deck's frames
+after it are the same frames, later -- so `--from` the take before re-encodes only the touched
+post's chunks. The deck's frames themselves are keyed by what they draw, and a take draws only the
+ones its chunks to encode read: a twin of a pruned take captures the touched post's frames, not the
+whole cut's again (about 90 s for a 31-minute cut). `UMTOOL_CHROME_LAZY=0` draws them all. The cut's sound
+is one pass (about 90 s, begun beside the capture), reused when no segment's sound changed (a
+caption or a knob that moves no word keeps it).
+
A layer whose page changed reuses its frames FRAME BY FRAME (report-to-video `frame-keys.mjs`, each
module's `frameKeys`: the deck, the stamps, the feed, the finale, the thread rail, the flips, the
stats, the effects and a teaser): every frame's key is the page's static part and what is on screen
@@ -2085,6 +2096,51 @@ 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 unit a
+build reuses from its own `out/` that the pool has not got (built before the pool, or linked in by
+`--from`) is filed then, so the first build after the pool fills it. 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. The disk guard before a render, still under its threshold after pruning takes'
+ work files, has the pool give back what only it holds, by the deficit.
+- **`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/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs
@@ -199,14 +199,17 @@ async function linkVariant({ src, dst, kept, from }) {
for (const f of ownFiles) if (!theirs.includes(f)) await rm(path.join(segOut, f), { force: true });
}
- // The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside.
+ // The keyed renders: chrome/<layer>-frames, with its .key (or, a sparse
+ // one -- only the frames its build's chunks read -- its .sparse), else the
+ // one kept aside.
+ const marker = async (d) => (await lstat(path.join(d, ".key")).catch(() => null)) ?? (await lstat(path.join(d, ".sparse")).catch(() => null));
const chrome = path.join(src, "chrome");
// Both there: the one whose .key was written last (the other is an older cut's).
const layers = new Map();
for (const dir of [chrome, kept]) {
for (const f of await names(dir)) {
if (!f.endsWith("-frames")) continue;
- const key = await lstat(path.join(dir, f, ".key")).catch(() => null);
+ const key = await marker(path.join(dir, f));
if (!key?.isFile()) continue;
const had = layers.get(f);
if (!had || key.mtimeMs > had.at) layers.set(f, { dir: path.join(dir, f), at: key.mtimeMs });
@@ -215,8 +218,8 @@ async function linkVariant({ src, dst, kept, from }) {
if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true });
for (const [name, { dir, at }] of [...layers].sort((x, y) => x[0].localeCompare(y[0]))) {
const mine = path.join(dst, "chrome", name);
- const ownKey = await lstat(path.join(mine, ".key")).catch(() => null);
- const theirKey = await lstat(path.join(dir, ".key")).catch(() => null);
+ const ownKey = await marker(mine);
+ const theirKey = await marker(dir);
const same = ownKey && theirKey && ownKey.ino === theirKey.ino && ownKey.dev === theirKey.dev;
if (ownKey?.isFile() && !same && ownKey.mtimeMs > at) {
// This take's own render is the newer: kept; theirs beside it for frame reuse.
diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs
@@ -1045,7 +1045,7 @@ export class DiskGuardRefused extends Error {}
* free?: (dir: string) => Promise<number | null>, pruneAll?: () => Promise<{ freedBytes: number, results: any[] }> }} o
* @returns {Promise<{ checked: boolean, freeBefore: number | null, freeAfter: number | null, freedBytes: number }>}
*/
-export async function diskGuard({ dirs, env = process.env, say = () => {}, free = freeBytesAt, pruneAll = () => pruneAllProjects({ by: "disk-guard" }) }) {
+export async function diskGuard({ dirs, env = process.env, say = () => {}, free = freeBytesAt, pruneAll = () => pruneAllProjects({ by: "disk-guard" }), prunePool = poolDeficitPrune }) {
const s = guardSettings(env);
if (!s.enabled) return { checked: false, freeBefore: null, freeAfter: null, freedBytes: 0 };
const least = async () => {
@@ -1069,7 +1069,16 @@ export async function diskGuard({ dirs, env = process.env, say = () => {}, free
} catch (err) {
say(`disk guard: the prune failed — ${err instanceof Error ? err.message : err}`);
}
- const after = await least();
+ let after = await least();
+ // Still under: the render pool gives back what only it holds, least recently used first.
+ if (after.min !== null && after.min < s.thresholdBytes) {
+ const r = await prunePool({ dirs, env, deficit: s.thresholdBytes - after.min }).catch(() => null);
+ if (r?.evicted) {
+ say(`disk guard: the render pool evicted ${r.evicted} object(s), ${fmtBytes(r.bytes)}`);
+ freedBytes += r.bytes;
+ after = await least();
+ }
+ }
if (after.min !== null && after.min < s.floorBytes) {
throw new DiskGuardRefused(
`disk guard: only ${fmtBytes(after.min)} free under ${after.at}, under the ${fmtBytes(s.floorBytes)} a render needs — nothing was rendered. ` +
@@ -1080,6 +1089,21 @@ export async function diskGuard({ dirs, env = process.env, say = () => {}, free
return { checked: true, freeBefore: before.min, freeAfter: after.min, freedBytes };
}
+/**
+ * The disk guard's last resort before refusing: the render pool (render-pool.mjs)
+ * of the first of `dirs` it serves, pruned by `deficit` bytes of what only it holds.
+ */
+async function poolDeficitPrune({ dirs, env, deficit }) {
+ const { poolFor, poolPrune, poolStats } = await import("umtool-report-to-video/render-pool");
+ for (const d of dirs) {
+ const pool = d ? await poolFor(d, env) : null;
+ if (!pool) continue;
+ const st = await poolStats(pool);
+ return poolPrune(pool, { maxBytes: Math.max(0, st.onlyPool - deficit) });
+ }
+ return null;
+}
+
/** For build-video's CLI: the guard over its --out (or its manifest's directory) and the projects root. */
export async function guardBeforeRender({ out, manifestPath, env = process.env, say }) {
const where = out ? path.resolve(/* turbopackIgnore: true */ out) : path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ manifestPath));
diff --git a/umtool/lib/report/takePrune.test.mjs b/umtool/lib/report/takePrune.test.mjs
@@ -484,3 +484,22 @@ test("the names it prunes by are its writers' names", async () => {
assert.equal(ce.CHUNKS_DIR, "chunks");
assert.equal(ce.HASH_MEMO_FILE, ".content-hashes.json");
});
+
+test("the disk guard: still under the threshold after the takes' prune, the render pool gives back what only it holds", async () => {
+ const GB = 1024 ** 3;
+ const said = [];
+ let free = 8 * GB;
+ let asked = null;
+ const r = await diskGuard({
+ dirs: ["/x"], env: {}, free: async () => free, say: (l) => said.push(l),
+ pruneAll: async () => ({ freedBytes: 0, results: [] }),
+ prunePool: async ({ deficit }) => {
+ asked = deficit;
+ free += 15 * GB;
+ return { evicted: 3, bytes: 15 * GB };
+ },
+ });
+ assert.equal(asked, 22 * GB, "the deficit to the 30 GB threshold");
+ assert.equal(r.freedBytes, 15 * GB);
+ assert.ok(said.some((l) => /the render pool evicted 3 object\(s\), 15\.0 GiB/.test(l)), said.join("\n"));
+});
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -1953,6 +1953,38 @@ parsing — wrapping the expression in single quotes is what protects them.
2) encodes that many at once; `REPORT_VIDEO_CHUNKED=0` or
`render.chunkedEncode: false` goes back to the batched single pass. It needs
no crossfade batches: no chunk opens more than a few segments.
+- **A hard-cut deck build is chunked too** (lane fast-fix-render): a take's
+ `--no-xfade` render, and `--chrome-only` with `transition: 0`. Before, its
+ picture was the stream-copied concat and then ONE overlay pass over the whole
+ cut -- 12.6 minutes of mid-6's 30 -- on every take, however small the change.
+ Now each chunk is one segment's run (a long one cut every 1800 frames from its
+ first frame), its join chain on it, the deck over it; a post that grew MOVES
+ the chunks after it without changing their keys (the deck's frame keys are
+ the same frames, later: measured on mid-6, a post 3 s longer draws no frame
+ key the cut did not have), so a fix re-encodes the chunks of the segment it
+ touched. The picture is frame-exact, where the copied concat laid each next
+ segment at the longer of its picture and its sound (0.30 s, 9 frames, by the
+ end of mid-6, its last 9 frames cut off); the sound is pinned the same way
+ (`hardCutSoundArgs`: each segment's sound as PCM exactly as long as its
+ picture, end to end, encoded once -- begun beside the deck's capture, and
+ keyed by each segment's SOUND, its audio packets: a fix to a post's picture
+ alone keeps the cut's sound).
+- **The deck is drawn only where a chunk to encode reads it** (`deckWant`,
+ compose-chrome's `want`): when the deck's shell is the cut's one overlay
+ layer and the encode is chunked, the build plans its chunks from the deck's
+ frame keys BEFORE the capture (`planChunks`, `framesNeeded`) and the capture
+ draws only the frames the chunks to encode read. A take `--from` one whose
+ frames were pruned no longer captures the whole cut again (mid-6: 11,996
+ captures, 90 s) to re-encode one post's chunk. The sequence is then SPARSE:
+ its `.frame-keys` whole, a `.sparse` (`{ key, frames, absent }`) in place of
+ its `.key`, never "cached whole"; what it has is reused by key, verify-build
+ and the prune record read its length from `.sparse`, `take --from` links it
+ like any keyed layer. `UMTOOL_CHROME_LAZY=0` draws every frame.
+- **A chunk's chrome layers key by their frame keys** when a sequence carries
+ `.frame-keys` (every keyed layer does): what its frames DRAW, not their bytes.
+ A layer captured again after a prune draws "a hair differently" per renderer
+ worker, which by bytes made every chunk of the cut new; by keys, a recaptured
+ deck is the deck it was. A sequence without them keys by its bytes.
- **Chrome frames are reused by their keys** (`frame-keys.mjs`). The deck, the
stamps, the feed and the finale are cue-interpreter pages, so what a frame
draws is the page less its cue list plus every element's value at that frame
@@ -2965,7 +2997,7 @@ container. It is encoded again 6 % lower while it lands over (x264
overshoots: 24.3 MiB at a 23.1 target, measured), four tries at most.
**From the master's chunks** (`ladder-chunks.mjs`). When the cut is a chunked
-build (`chunked-encode.mjs`, the default with a transition) whose chunks are
+build (`chunked-encode.mjs`, the default with a transition or a deck) whose chunks are
still in `out/sourced/chunks/`, and the master's video packets are those
chunks' (checked by content: the sha256 of the master's packets against the
chunks' as the build's mux writes them -- a few seconds, no decode, memoised
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -238,8 +238,9 @@ 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, chunkKey, chunkSpans, framesRead, sequenceIdentity, spanSegments, whyRebuilt,
+ CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, SPARSE_FILE, chunkKey, chunkSpans, frameFile, frameKeysIdentity, framesRead, readFrameKeys, sequenceIdentity, spanSegments, whyRebuilt,
} from "./chunked-encode.mjs";
// The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table,
// in common, plain JS so bare `node` can load it.
@@ -4489,7 +4490,7 @@ export async function concatWithXfade(segments, render, outPath, railPlan, chrom
const D = render.transition ?? 0.5;
// The cut itself (dips drawn, no rail): in keyed chunks (chunked-encode.mjs).
if (!railPlan && dip && D > 0 && chunkedEncodeOn(render)) {
- await chunkedXfadeConcat({ segments, render, outPath, chrome, joins, workDir });
+ await chunkedConcat({ segments, render, outPath, chrome, joins, workDir });
return;
}
const { durs } = await cutOffsets(segments, D, render.fps, joins);
@@ -4825,7 +4826,9 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins
const { a, b } = span;
const { first, last } = spanSegments(span, starts, durs, fps);
const segs = segments.slice(first, last + 1);
- const g = xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, {
+ // A hard-cut cut (D = 0, a take's): the run joined as hardCutFilterArgs
+ // joins the whole cut -- each input's join chain, then `concat`.
+ const g = D === 0 ? hardCutVideoGraph(segs.length, joins ? joins.slice(first, last + 1) : null, render) : xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, {
audio: false,
ctx: { hasPrev: first > 0, prevJoin: joins?.[first - 1] ?? null, hasNext: last < segments.length - 1 },
// Offsets to the microsecond: one rounded UP past its frame's timestamp
@@ -4901,6 +4904,170 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins
}
/**
+ * A run of a hard-cut cut's segments as one picture: each input's join chain
+ * (its picture half), then `concat` -- hardCutFilterArgs' video side, for a
+ * chunk of the final encode. One input is its own chain. Pure.
+ *
+ * @returns {{ parts: string[], vlab: string }}
+ */
+export function hardCutVideoGraph(n, joins, render) {
+ const parts = [];
+ const vs = [];
+ for (let i = 0; i < n; i += 1) {
+ const c = joinInputChain(i, joins?.[i] ?? null, render, { only: "v" });
+ parts.push(...c.parts);
+ vs.push(c.v);
+ }
+ if (n === 1) return { parts, vlab: vs[0] };
+ parts.push(`${vs.join("")}concat=n=${n}:v=1:a=0[hcv]`);
+ return { parts, vlab: "[hcv]" };
+}
+
+/**
+ * A hard-cut cut's sound (D = 0), as two kinds of ffmpeg run. Pure.
+ *
+ * pin(i, seg, out) segment i's sound alone (`-vn`), its join's sound on
+ * it, laid on its own clock (AUDIO_ON_CLOCK) and PINNED
+ * to its picture's length in the cut (`durs[i]`, frames
+ * ÷ fps, hold included) -- as the crossfade's graph pins
+ * it -- as PCM: an exact number of samples
+ * encode(list, out) the pins end to end (the concat demuxer: every pin is
+ * exactly as long as its picture, so each starts on its
+ * segment's first frame), encoded once
+ *
+ * Pinned because a segment's sound routinely ends a few ms off its picture
+ * (AAC frames do not end on video frames), and the stream-copied concat the
+ * hard-cut build used to make laid each next segment at the LONGER of the
+ * two: 34 of mid-6's 84 segments, 0.30 s (9 frames) by the end of its cut,
+ * the footage and its sound that much behind the deck and its last 9 frames
+ * cut off. The chunks lay every picture frame-exact; the sound is laid the same.
+ *
+ * In pins rather than one graph over every segment: one ffmpeg holding the
+ * 84 segments open took 241 s for mid-6's sound; the pins, a few at a time,
+ * and one encode of their PCM take the encode's time (~75 s, native aac).
+ */
+export function hardCutSoundArgs({ durs, joins = null, render }) {
+ const head = ["-nostdin", "-v", "error", "-y"];
+ const pcm = ["-c:a", "pcm_s16le", "-ar", String(render.audioRate), "-ac", String(render.audioChannels)];
+ return {
+ pin: (i, seg, out) => {
+ const c = joinInputChain(0, joins?.[i] ?? null, render, { only: "a" });
+ const len = durs[i].toFixed(6);
+ const graph = [...c.parts, `${c.a}${AUDIO_ON_CLOCK},apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS[pa]`].join(";");
+ return [...head, "-vn", "-i", seg, "-filter_complex", graph, "-map", "[pa]", ...pcm, "-f", "wav", out];
+ },
+ encode: (list, out) => [
+ ...head, "-f", "concat", "-safe", "0", "-i", list, "-map", "0:a", ...cutAudioEncodeArgs(render), out,
+ ],
+ };
+}
+
+/** The hard-cut sound passes in flight, by their file: the early start and the encode share one. */
+const SOUND_IN_FLIGHT = new Map();
+
+/** The content-hash memo of a work dir, one per process (the early sound and the encode share it). */
+const MEMOS = new Map();
+function memoAt(workDir) {
+ const file = path.join(workDir, HASH_MEMO_FILE);
+ if (!MEMOS.has(file)) MEMOS.set(file, HashMemo.open(file));
+ return MEMOS.get(file);
+}
+
+/**
+ * A segment's SOUND, as an identity: the sha1 of its audio packets with
+ * their timestamps (ffmpeg's framehash, stream-copied: no decode, ~0.1 s).
+ * A post whose picture changed and whose words did not (a caption, a knob)
+ * has the same sound, and the cut's sound is not encoded again for it.
+ */
+export async function soundIdentity(file) {
+ const { stdout } = await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-i", file, "-map", "0:a:0", "-c", "copy", "-f", "framehash", "-hash", "sha256", "-"], { maxBuffer: 1 << 28 });
+ const body = String(stdout).split("\n").filter((l) => !l.startsWith("#software")).join("\n");
+ return createHash("sha1").update(body).digest("hex");
+}
+
+/** Each segment's sound identity (soundIdentity), memoised by inode in `memo`, 8 at a time. */
+async function soundIdentities(memo, segments) {
+ const out = new Array(segments.length);
+ await runPool(segments.map((s, i) => async () => {
+ out[i] = await memo.derived(s, "sound", soundIdentity);
+ if (!out[i]) throw new Error(`the cut's sound: segment ${s} is not a file`);
+ }), 8);
+ return out;
+}
+
+/**
+ * Make (or find) a hard-cut cut's sound: `<dir>/audio-<key>.m4a`, keyed by
+ * the segments' contents and every argv that makes it (hardCutSoundArgs).
+ * Started by the build as soon as the segments and joins are known -- beside
+ * the deck's capture -- and awaited by the chunked encode, which calls it
+ * again with the same arguments (one pass, shared). Resolves to the file.
+ *
+ * @param {{ segments: string[], durs: number[], joins?: Array<object|null>|null, render: object, dir: string, workDir: string, ffmpeg?: string|null }} job
+ */
+export function hardCutSound(job) {
+ const run = (async () => {
+ const { segments, durs, joins = null, render, dir, workDir } = job;
+ // Keyed by each segment's SOUND, not its file: a fix to a post's picture
+ // alone leaves the cut's sound as it was.
+ const sounds = await soundIdentities(await memoAt(workDir), segments);
+ const ffmpeg = job.ffmpeg ?? (await ffmpegIdentity(FFMPEG));
+ const a = hardCutSoundArgs({ durs, joins, render });
+ const keyArgv = [...segments.map((_, i) => a.pin(i, `<in:${i}>`, "<pin>")), a.encode("<list>", "<out>")];
+ return path.join(dir, `audio-${chunkKey({ keyArgv: keyArgv.flat(), inputs: sounds.map((h) => ({ sound: h })), ffmpeg })}.m4a`);
+ })();
+ return run.then((audio) => {
+ if (!SOUND_IN_FLIGHT.has(audio)) {
+ const made = makeHardCutSound(job, audio).finally(() => SOUND_IN_FLIGHT.delete(audio));
+ SOUND_IN_FLIGHT.set(audio, made);
+ }
+ return SOUND_IN_FLIGHT.get(audio);
+ });
+}
+
+/**
+ * Begin a hard-cut build's sound (hardCutSound) without waiting for it: its
+ * failure is the chunked encode's to report, when it asks for the same sound.
+ */
+export async function startHardCutSound({ segments, render, joins = null, outDir }) {
+ const { durs } = await cutOffsets(segments, 0, render.fps, joins);
+ hardCutSound({ segments, durs, joins, render, dir: path.join(outDir, CHUNKS_DIR), workDir: outDir }).catch(() => {});
+}
+
+async function makeHardCutSound({ segments, durs, joins = null, render, dir, workDir }, audio) {
+ const pool = await poolFor(workDir);
+ if (await exists(audio)) {
+ EMIT("note", { message: "final encode: the cut's sound unchanged — reused" });
+ await poolPut(pool, "sound", path.basename(audio), { "sound.m4a": audio });
+ return { audio, reused: true };
+ }
+ await mkdir(dir, { recursive: true });
+ 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}`);
+ await rm(pins, { recursive: true, force: true });
+ await mkdir(pins, { recursive: true });
+ try {
+ const files = segments.map((_, i) => path.join(pins, `pin-${String(i).padStart(4, "0")}.wav`));
+ await runPool(segments.map((seg, i) => () => execFileP(FFMPEG, a.pin(i, seg, files[i]), { maxBuffer: 1 << 26 })), 4);
+ const list = path.join(pins, "pins.txt");
+ await writeFile(list, concatListText(files), "utf8");
+ await mkdir(dir, { recursive: true });
+ 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 });
+ }
+ EMIT("note", { message: `final encode: the cut's sound encoded in ${((Date.now() - t0) / 1000).toFixed(1)}s` });
+ return { audio, reused: false };
+}
+
+/**
* The cut's sound in one pass: every segment's audio alone (`-vn`), joined
* exactly as xfadeGraph joins it (each pinned to its picture's length, the
* mutes, holds, fades and dips on their inputs, the acrossfades), encoded
@@ -4967,15 +5134,30 @@ export async function logRebuild(workDir, entry) {
}
/**
- * concatWithXfade's chunked encode (chunked-encode.mjs): plan the chunks,
- * key each by its inputs' contents, encode only the ones whose key is not on
- * disk (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when
- * its key matches), and join them into `outPath`. Every chunk's frame count
- * is checked, and so is the cut's.
+ * The chunked final encode (chunked-encode.mjs): plan the chunks, key each by
+ * its inputs' contents, encode only the ones whose key is not on disk
+ * (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when its
+ * key matches), and join them into `outPath`. Every chunk's frame count is
+ * checked, and so is the cut's.
+ *
+ * Two callers: concatWithXfade (the crossfaded cut, `D` its transition) and
+ * the hard-cut deck build (`hardCut`, a take's `--no-xfade`: D = 0, each chunk
+ * one segment's run, the sound the segments' own, stream-copied when nothing
+ * 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
+ * are `todo`. chunkedConcat runs it; so does a build that asks, before the
+ * deck is captured, which deck frames its chunks to encode will read
+ * (`frameKeys`: a sequence's frame keys known before its frames are).
*/
-async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, joins = null, workDir }) {
- const t0 = Date.now();
- const D = render.transition ?? 0.5;
+export async function planChunks({ segments, render, chrome = null, joins = null, workDir, hardCut = false, frameKeys = null, quiet = false }) {
+ const D = hardCut ? 0 : render.transition ?? 0.5;
const fps = render.fps;
const { durs, starts, total } = await cutOffsets(segments, D, fps, joins);
const N = Math.round(total * fps);
@@ -4986,17 +5168,24 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
});
const dir = path.join(workDir, CHUNKS_DIR);
await mkdir(dir, { recursive: true });
- const memo = await HashMemo.open(path.join(workDir, HASH_MEMO_FILE));
+ const memo = await memoAt(workDir);
const ffmpeg = await ffmpegIdentity(FFMPEG);
const prev = await readFile(path.join(dir, CHUNKS_RECORD), "utf8").then((t) => JSON.parse(t), () => null);
const prevChunks = Array.isArray(prev?.chunks) ? prev.chunks : [];
- EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` });
+ if (!quiet) EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` });
const segHash = await memo.hashAll(segments);
segHash.forEach((h, i) => {
if (!h) throw new Error(`chunked encode: segment ${segments[i]} is not a file`);
});
+ // Each chrome sequence's frame keys, when it carries them (chunked-encode.mjs):
+ // a chunk then keys by what its frames draw, not by their bytes.
+ const frameKeysByDir = new Map(frameKeys ?? []);
+ for (const r of chrome?.regions ?? []) {
+ const count = WINDOW_REGIONS.has(r.name) ? Number(r.frameCount) : N;
+ if (!frameKeysByDir.has(r.frames)) frameKeysByDir.set(r.frames, await readFrameKeys(r.frames, count));
+ }
const plan = [];
for (const span of spans) {
const proto = chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: "" });
@@ -5005,7 +5194,8 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
for (const inp of proto.inputs) {
if (inp.kind === "seg") ids.push({ seg: segHash[inp.index] });
else {
- const id = inp.range ? await sequenceIdentity(memo, inp.dir, inp.range) : "none";
+ const fk = frameKeysByDir.get(inp.dir);
+ const id = !inp.range ? "none" : fk ? frameKeysIdentity(fk, inp.range) : await sequenceIdentity(memo, inp.dir, inp.range);
ids.push({ seq: id });
layers[inp.region] = id;
}
@@ -5022,23 +5212,92 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
graph: createHash("sha1").update(JSON.stringify(proto.keyArgv)).digest("hex").slice(0, 16),
},
};
- plan.push({ span, file, rec, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv });
+ plan.push({ span, file, rec, inputs: proto.inputs, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv });
}
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;
+ // (A chunk of its own the pool has not got -- encoded before it, or linked in by --from -- is filed.)
+ else if (got === p.span.b - p.span.a && pool) await poolPut(pool, "chunk", p.rec.key, { "chunk.mp4": p.file });
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, pool };
+}
+
+/**
+ * The deck's `want` (compose-chrome): draw only the frames the chunked
+ * encode will read -- a fix `--from` a take whose frames were pruned captures
+ * the touched post's frames, not the whole cut's (mid-6: 11,996 captures,
+ * 90 s). Only when the deck's shell is the cut's one overlay layer (another
+ * layer's frames are in the same chunks' keys, and are captured beside it),
+ * and the encode is chunked. `UMTOOL_CHROME_LAZY=0` draws every frame.
+ */
+export function deckWant({ schedule, render, outDir, segments, joins = null, hardCut, env = process.env }) {
+ if (env.UMTOOL_CHROME_LAZY === "0" || !chunkedEncodeOn(render, env)) return null;
+ const on = deckOverlays().filter((m) => m.on(schedule, render));
+ if (on.length !== 1 || on[0].region !== "deck" || on[0].kind !== "overlay-whole") return null;
+ const regions = on[0].regions(schedule, { render, outDir });
+ const framesDir = regions[0].frames;
+ return (fk) => framesNeeded({ framesDir, fk, segments, render, chrome: { regions, outLabel: "[hfout]" }, joins, workDir: outDir, hardCut });
+}
+
+/**
+ * The frames of chrome sequence `framesDir` the chunks to encode read
+ * (0-based), when its frame keys are `fk`: what a build asks the capture to
+ * draw (compose-chrome `want`). Every other frame is in a chunk on disk.
+ */
+export async function framesNeeded({ framesDir, fk, ...job }) {
+ const { todo, plan } = await planChunks({ ...job, frameKeys: new Map([[framesDir, fk]]), quiet: true });
+ const need = new Set();
+ for (const p of todo) {
+ for (const inp of p.inputs) {
+ if (inp.kind !== "seq" || inp.dir !== framesDir || !inp.range) continue;
+ for (let n = inp.range[0]; n <= inp.range[1]; n += 1) need.add(n - 1);
+ }
+ }
+ EMIT("note", { message: `chrome: ${todo.length} of ${plan.length} chunk(s) to encode read ${need.size} of ${fk.length} ${path.basename(framesDir)} frames — only those are drawn` });
+ return need;
+}
+
+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, 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();
+ for (const p of todo) {
+ for (const inp of p.inputs) {
+ if (inp.kind !== "seq" || !inp.range) continue;
+ if (!sparse.has(inp.dir)) sparse.set(inp.dir, await exists(path.join(inp.dir, SPARSE_FILE)));
+ if (!sparse.get(inp.dir)) continue;
+ for (let n = inp.range[0]; n <= inp.range[1]; n += 1) {
+ if (!(await exists(frameFile(inp.dir, n)))) {
+ throw new Error(`chunked encode: chunk ${p.rec.anchor} reads ${frameFile(inp.dir, n)}, which was not drawn (a sparse ${inp.region} sequence)`);
+ }
+ }
+ }
+ }
const why = new Map();
for (const p of todo) why.set(p, whyRebuilt(p.rec, prevChunks));
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.
@@ -5049,19 +5308,26 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
EMIT("note", { message: ` encode ${ps.length} chunk(s) — ${w} (at ${at})` });
}
- // The sound: one pass, keyed by the segments' contents and its argv.
- const audioProto = cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1);
- const audioKey = chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg });
- const audio = path.join(dir, `audio-${audioKey}.m4a`);
- const audioJob = async () => {
+ // The sound: one pass, keyed by the segments' contents and its argv (a
+ // hard cut's pinned end to end, hardCutSound -- perhaps begun already).
+ const audioProto = D === 0 ? null : cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1);
+ let audio = D === 0 ? null : path.join(dir, `audio-${chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg })}.m4a`);
+ const audioJob = D === 0 ? async () => {
+ audio = (await hardCutSound({ segments, durs, joins, render, dir, workDir, ffmpeg })).audio;
+ } : async () => {
if (await exists(audio)) {
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` });
};
@@ -5080,6 +5346,7 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
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) ` +
@@ -5111,6 +5378,7 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
// 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 });
@@ -5295,7 +5563,7 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re
* feed's, each posts window's, the stamps', the stats'.
* Dynamic import: compose-chrome imports this file.
*/
-async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null }) {
+async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null, drawOnly = null }) {
const { composeChrome } = await import("./compose-chrome.mjs");
// Each layer's outcome, said and logged (rebuild.ndjson): cached whole,
// frames reused, or rendered.
@@ -5336,6 +5604,8 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
const r = await composeChrome({
manifestPath, outDir, variant, region: mod.region, doRender: true,
fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence", ...win,
+ // The deck's frames the chunked encode will read, and only those (deckWant).
+ ...(mod.region === "deck" && drawOnly && duration == null ? { want: drawOnly } : {}),
});
if (r.frameCount !== want) {
throw new Error(
@@ -5348,6 +5618,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
emitChrome({
phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", ...named,
...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}),
+ ...(r.absent ? { absent: r.absent } : {}),
frames: r.frameCount, key: r.key, dir: r.frames,
seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
});
@@ -6419,6 +6690,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 });
@@ -6626,6 +6900,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// inputs (null without any).
const joins = await cutJoins({ schedule, entries, segments: segs, render });
const prerail = prerailPath(outDir, manifest.slug, D);
+ if (D === 0 && !opts.chromePreview && chunkedEncodeOn(render)) await startHardCutSound({ segments: segs, render, joins, outDir });
if (opts.chromePreview) {
const at = Math.max(0, Math.min(opts.chromePreview.at, schedule.total - 1 / render.fps));
@@ -6648,10 +6923,15 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
return { out, failures: [] };
}
- const plan = await renderDeck({ manifestPath, render, outDir, variant, schedule });
+ const plan = await renderDeck({
+ manifestPath, render, outDir, variant, schedule, drawOnly: deckWant({ schedule, render, outDir, segments: segs, joins, hardCut: D === 0 }),
+ });
EMIT("chrome", { phase: "overlay" });
EMIT("concat", { mode: D === 0 ? "hardcut" : "xfade", n: segs.length });
- if (D === 0) {
+ if (D === 0 && chunkedEncodeOn(render)) {
+ // In keyed chunks, as the full build's (chunkedConcat).
+ await chunkedConcat({ segments: segs, render, outPath: dirs.final, chrome: plan, joins, workDir: outDir, hardCut: true });
+ } else if (D === 0) {
// The hard-cut concat is a stream copy of these very segments; when
// nothing changed since it was made it is reused, and the overlay is
// the only encode.
@@ -6752,6 +7032,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const joins = await cutJoins({ schedule: deck ? schedule : null, entries, segments, render });
const railPlan = opts.noRail ? null : await buildRailPlan(manifest, render, entries, segments, D, outDir);
+ // A hard-cut deck build's sound needs only the segments and the joins: it
+ // is begun now, beside the deck's capture, and the chunked encode awaits it.
+ if (D === 0 && deck && !opts.noChrome && !railPlan && chunkedEncodeOn(render)) await startHardCutSound({ segments, render, joins, outDir });
// The rendered chrome, if this manifest asks for it. Absent, `chromePlan` is
// null and every line below behaves exactly as it did -- which is the claim
@@ -6774,7 +7057,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// skips the render when its key and frame count match). `--no-chrome` keeps
// the deck's framing and leaves the panel off -- a fast look at the picture.
if (deck && !opts.noChrome) {
- chromePlan = await renderDeck({ manifestPath, render, outDir, variant, schedule });
+ // Lazily (deckWant) when the cut's chunked encode is the deck's only reader.
+ const want = !railPlan && (D === 0 || chunkedEncodeOn(render)) ? deckWant({ schedule, render, outDir, segments, joins, hardCut: D === 0 }) : null;
+ chromePlan = await renderDeck({ manifestPath, render, outDir, variant, schedule, drawOnly: want });
EMIT("chrome", { phase: "overlay" });
}
@@ -6798,10 +7083,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
await concatHardCut(segments, outDir, prerail, { joins, render });
await assertConcatLength(prerail, railPlan.total, render.fps, "hard-cut concat");
await applyRail(prerail, final, render, railPlan, null, await cutDips(segments, joins));
- } else if (chromePlan) {
+ } else if (chromePlan && chunkedEncodeOn(render)) {
// Only the deck reaches here (the band refused above, and the deck
- // refuses a rail). Hard-cut concat to the prerail, then ONE overlay
- // re-encode to the final.
+ // refuses a rail): in keyed chunks, each a segment's run with the deck
+ // over it, so a take re-encodes only the chunks whose segment or deck
+ // frames changed -- a post that grew moves the chunks after it, it does
+ // not change them (chunkedConcat).
+ await chunkedConcat({ segments, render, outPath: final, chrome: chromePlan, joins, workDir: outDir, hardCut: true });
+ } else if (chromePlan) {
+ // REPORT_VIDEO_CHUNKED=0: hard-cut concat to the prerail, then ONE
+ // overlay re-encode to the final.
await concatHardCut(segments, outDir, prerail, { record: true, joins, render });
await assertConcatLength(prerail, schedule.total, render.fps, "hard-cut concat");
await applyChrome(prerail, final, render, chromePlan, null, await cutDips(segments, joins));
diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs
@@ -30,6 +30,16 @@
// different is a new key. Nothing is keyed by a name or a time that could
// say "same" about different pixels.
//
+// A chrome sequence that carries its FRAME KEYS (`.frame-keys`, written by
+// compose-chrome beside its `.key`: what each frame draws, frame-keys.mjs) is
+// identified by the keys of the frames a chunk reads rather than by their
+// bytes. Those keys are the contract the capture already reuses frames by;
+// and a layer captured again (its frames pruned after the last mux) draws
+// "a hair differently" per renderer worker -- a few pixels, a few levels --
+// which by bytes made every chunk of the cut new. By keys, a recaptured deck
+// is the deck it was, and only a chunk whose frames DRAW something else is
+// encoded again. A sequence without them is keyed by its bytes, as before.
+//
// Plain node; every path is a parameter.
import { createHash } from "node:crypto";
@@ -174,6 +184,28 @@ export class HashMemo {
return h;
}
+ /**
+ * Something computed from a file's contents (`compute(file)`, a string),
+ * memoised beside its hash by the same identity under `tag` -- a segment's
+ * SOUND, say, which a build keys apart from its picture. null when it is
+ * not a regular file.
+ */
+ async derived(file, tag, compute) {
+ const st = await stat(file).catch(() => null);
+ if (!st?.isFile()) return null;
+ const id = `${tag}:${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}`;
+ this.seen.add(id);
+ const had = this.map.get(id);
+ if (had) return had;
+ const h = await compute(file);
+ const after = await stat(file).catch(() => null);
+ if (after && `${tag}:${after.dev}:${after.ino}:${after.size}:${after.mtimeMs}` === id) {
+ this.map.set(id, h);
+ this.dirty = true;
+ }
+ return h;
+ }
+
/** Hash many files, `width` at a time; the hashes in order. */
async hashAll(files, width = 8) {
const out = new Array(files.length);
@@ -206,13 +238,46 @@ export class HashMemo {
async save() {
if (!this.file || !this.dirty) return;
- const tmp = `${this.file}.${process.pid}.tmp`;
+ // A tmp of its own per save: a build may save while another save of the same memo is in flight.
+ HashMemo.saves = (HashMemo.saves ?? 0) + 1;
+ const tmp = `${this.file}.${process.pid}.${HashMemo.saves}.tmp`;
await writeFile(tmp, JSON.stringify({ v: 1, h: Object.fromEntries(this.map) }), "utf8");
await rename(tmp, this.file);
this.dirty = false;
}
}
+/** Beside a chrome sequence's `.key`: each frame's key, frame 1 on line 1 (compose-chrome writes it). */
+export const FRAME_KEYS_FILE = ".frame-keys";
+
+/**
+ * Beside a SPARSE chrome sequence's `.frame-keys`, in place of its `.key`:
+ * `{ key, frames, absent }`. compose-chrome writes one when a build asked it
+ * to capture only the frames its chunks to encode read (`want`): the other
+ * frames' keys are known and their chunks are on disk, so they are not drawn.
+ * A sparse sequence is never "cached whole"; what it has is reused by key.
+ */
+export const SPARSE_FILE = ".sparse";
+
+/**
+ * A sequence's frame keys, when it has them for exactly `count` frames and is
+ * finished (its `.key` -- or a sparse one's `.sparse` -- is written last);
+ * else null, and it is keyed by bytes.
+ */
+export async function readFrameKeys(dir, count) {
+ const done = async (f) => (await stat(path.join(dir, f)).catch(() => null))?.isFile() === true;
+ if (!(await done(".key")) && !(await done(SPARSE_FILE))) return null;
+ const text = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").catch(() => null);
+ if (!text) return null;
+ const keys = text.split("\n").filter(Boolean);
+ return keys.length === count ? keys : null;
+}
+
+/** What a run `[lo, hi]` (1-based) of a sequence contributes to a key, by its frame keys. */
+export function frameKeysIdentity(keys, [lo, hi]) {
+ return `fk:${createHash("sha1").update(keys.slice(lo - 1, hi).join("\n")).digest("hex")}`;
+}
+
/** A frame sequence's file name for 1-based frame `n` (frame_%06d.png). */
export const frameFile = (dir, n) => path.join(dir, `frame_${String(n).padStart(6, "0")}.png`);
diff --git a/umtool/report-to-video/chunked-encode.test.mjs b/umtool/report-to-video/chunked-encode.test.mjs
@@ -1,5 +1,5 @@
// The chunked final encode (chunked-encode.mjs, build-video's
-// chunkedXfadeConcat): the spans a cut is cut into, what a chunk's key covers
+// chunkedConcat): the spans a cut is cut into, what a chunk's key covers
// (and that a MOVED chunk keys as it did while a changed input does not), and
// real ffmpeg runs -- a chunked build of a small cut with joins, a hold, a dip,
// a whole-cut chrome sequence and a posts window, losslessly encoded, frame for
@@ -17,7 +17,9 @@ import test from "node:test";
import {
CHUNKS_DIR, CHUNKS_RECORD, HashMemo, chunkKey, chunkSpans, framesRead, spanSegments, whyRebuilt,
} from "./chunked-encode.mjs";
-import { chunkVideoArgs, concatWithXfade, dipWindows, setProgressMode, withCutEdits, xfadeConcatArgs } from "./build-video.mjs";
+import {
+ applyChromeArgs, chunkVideoArgs, chunkedConcat, concatListText, concatWithXfade, dipWindows, hardCutFilterArgs, setProgressMode, withCutEdits, xfadeConcatArgs,
+} from "./build-video.mjs";
import { scheduleFrom } from "./deck.mjs";
test("chunkSpans: anchored where each segment is fully in, long spans cut from the anchor", () => {
@@ -335,3 +337,222 @@ test("two spans that key alike are encoded once and joined twice", { skip: !have
rmSync(dir, { recursive: true, force: true });
}
});
+
+// ---- the hard-cut deck build (a take's --no-xfade) ----------------------------
+
+/** A segment whose sound runs `extra` seconds past its picture (as an AAC-padded one does). */
+function longSoundSegment(dir, i, frames, fps, extra) {
+ const out = path.join(dir, `l${i}.mp4`);
+ run([
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc2=s=64x36:r=${fps}:d=${frames / fps + 1},trim=end_frame=${frames},colorchannelmixer=rr=${0.4 + 0.1 * i}`,
+ "-f", "lavfi", "-i", `sine=f=${300 + 100 * i}:r=48000:d=${frames / fps + extra}`,
+ "-map", "0:v", "-map", "1:a", "-ac", "2",
+ "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac",
+ out,
+ ]);
+ return out;
+}
+
+/** A sequence directory made of other frames (hard links), with frame keys when `keys` is given. */
+function linkedSequence(dir, files, keys = null) {
+ rmSync(dir, { recursive: true, force: true });
+ mkdirSync(dir, { recursive: true });
+ files.forEach((f, k) => linkSync(f, path.join(dir, `frame_${String(k + 1).padStart(6, "0")}.png`)));
+ if (keys) {
+ writeFileSync(path.join(dir, ".frame-keys"), keys.join("\n") + "\n");
+ writeFileSync(path.join(dir, ".key"), "k\n");
+ }
+}
+
+const R10 = { width: 64, height: 36, fps: 10, transition: 0, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0, palette: { bg: "#101820" } };
+
+test("a chunked hard-cut deck build is the hard-cut concat and its overlay pass, frame for frame, with NO drift: each segment at its own frame, its sound with it", { skip: !have }, async () => {
+ const fps = 10;
+ const dir = mkdtempSync(path.join(tmpdir(), "chunked-hc-"));
+ const events = [];
+ setProgressMode((e) => events.push(e));
+ process.env.REPORT_VIDEO_CHUNK_FRAMES = "24";
+ try {
+ // Each segment's sound runs past its picture (0.15 s): a stream-copied
+ // concat laid each next segment that much late.
+ const lens = [25, 40, 33, 30];
+ const segments = lens.map((f, i) => longSoundSegment(dir, i, f, fps, 0.15));
+ const N = lens.reduce((a, b) => a + b, 0);
+ sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12);
+ const chrome = { regions: [{ name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" };
+
+ // The old path's drift: the copied concat is longer than the segments' frames.
+ const list = path.join(dir, "list.txt");
+ writeFileSync(list, concatListText(segments));
+ const copied = path.join(dir, "copied.mp4");
+ run(["-v", "error", "-y", "-f", "concat", "-safe", "0", "-fflags", "+genpts", "-i", list, "-c", "copy", copied]);
+ assert.ok(audioSeconds(copied) > N / fps + 0.4, `the copy laid each segment by its sound (${audioSeconds(copied)} vs ${N / fps})`);
+
+ // Frame-exact: the segments' pictures end to end (lossless; a silent
+ // track for the overlay pass to copy), then one overlay pass.
+ const prerail = path.join(dir, "prerail.mp4");
+ run([
+ "-v", "error", "-y", ...segments.flatMap((f) => ["-i", f]), "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo",
+ "-filter_complex", `${segments.map((_, i) => `[${i}:v]`).join("")}concat=n=${segments.length}:v=1:a=0[v]`,
+ "-map", "[v]", "-map", `${segments.length}:a`, "-shortest",
+ "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", prerail,
+ ]);
+ assert.equal(probeFrames(prerail), N);
+ const single = path.join(dir, "single.mp4");
+ run(applyChromeArgs(prerail, single, R10, chrome).slice(1));
+
+ const chunked = path.join(dir, "chunked.mp4");
+ await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true });
+ assert.equal(probeFrames(chunked), N);
+ const want = frameMd5(single);
+ const got = frameMd5(chunked);
+ assert.equal(got.length, want.length);
+ assert.deepEqual(got.map((h, f) => (h === want[f] ? null : f)).filter((f) => f != null), [], "every frame is the overlay pass's");
+ // The sound pinned to the picture: as long as the cut, every segment's at its own frame.
+ assert.ok(Math.abs(audioSeconds(chunked) - N / fps) < 0.03, `the sound runs the cut (${audioSeconds(chunked)} vs ${N / fps})`);
+ // NO DRIFT (lane/join-continuity: mid-7's master ran 0.33-0.385 s late on its schedule by the end,
+ // the concat demuxer placing each file by its longer stream). The master is the segments'
+ // pictures summed, frame for frame; each segment's first frame is at its schedule's frame and
+ // its own tone is playing just after it -- where the copied concat had the one before still.
+ const starts = lens.map((_, i) => lens.slice(0, i).reduce((a, b) => a + b, 0));
+ // (Without the deck -- whose overlay converts every pixel through RGB -- the lossless master is the
+ // segments' own frames, exactly.)
+ const bareDir = path.join(dir, "bare");
+ mkdirSync(bareDir);
+ const bare = path.join(bareDir, "bare.mp4");
+ await chunkedConcat({ segments, render: R10, outPath: bare, workDir: bareDir, hardCut: true });
+ const master = frameMd5(bare);
+ assert.equal(master.length, lens.reduce((a, b) => a + b, 0), "the master is the sum of the segments' pictures");
+ segments.forEach((f, i) => {
+ assert.deepEqual(master.slice(starts[i], starts[i] + lens[i]), frameMd5(f), `segment ${i} is the master's frames ${starts[i]}-${starts[i] + lens[i] - 1}, exactly`);
+ });
+ const toneAt = (file, at) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(at), "-t", "0.2", "-i", file, "-map", "0:a", "-ac", "1", "-ar", "48000", "-f", "s16le", "-"], { maxBuffer: 1 << 24 });
+ const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, r.stdout.length >> 1);
+ let z = 0;
+ for (let k = 1; k < pcm.length; k += 1) if ((pcm[k - 1] < 0) !== (pcm[k] < 0)) z += 1;
+ return z / 2 / (pcm.length / 48000);
+ };
+ starts.forEach((s, i) => {
+ const hz = toneAt(chunked, s / fps + 0.05);
+ assert.ok(Math.abs(hz - (300 + 100 * i)) < 40, `segment ${i}'s sound starts with its picture (${hz.toFixed(0)} Hz, want ${300 + 100 * i})`);
+ });
+ // (The copied concat, for contrast, is still playing segment 2's tone where segment 3's picture starts.)
+ assert.ok(Math.abs(toneAt(copied, starts[3] / fps + 0.05) - 600) >= 40, "the copy drifted");
+ const record = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ // Anchored at each segment's start, a long one cut every 24 frames from it.
+ assert.deepEqual(record.chunks.map((c) => [c.a, c.b]), [[0, 25], [25, 49], [49, 65], [65, 89], [89, 98], [98, 122], [122, 128]]);
+ for (const c of record.chunks) assert.equal(c.parts.segments.length, 1, "a hard-cut chunk is one segment's run");
+
+ // Again: nothing encoded.
+ events.length = 0;
+ await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true });
+ assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "nothing encoded the second time");
+ assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? "")));
+
+ // Segment 2's picture made again, its sound the same packets (a caption
+ // fixed): its chunks are encoded, the cut's sound is not.
+ const other = longSoundSegment(dir, 5, 33, fps, 0.15);
+ const remade = path.join(dir, "remade.mp4");
+ run(["-v", "error", "-y", "-i", other, "-i", segments[2], "-map", "0:v", "-map", "1:a", "-c", "copy", remade]);
+ rmSync(segments[2]);
+ linkSync(remade, segments[2]);
+ events.length = 0;
+ await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true });
+ assert.ok(events.some((e) => /5\/7 chunk\(s\) unchanged/.test(e.message ?? "")), events.map((e) => e.message).join("\n"));
+ assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? "")), "a new picture over the same sound keeps the cut's sound");
+ } finally {
+ setProgressMode("human");
+ delete process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("a chunked hard-cut build with joins (a hold, a dip, the end fade) is hardCutFilterArgs and the overlay, frame for frame", { skip: !have }, async () => {
+ const fps = 10;
+ const dir = mkdtempSync(path.join(tmpdir(), "chunked-hcj-"));
+ setProgressMode(() => {});
+ process.env.REPORT_VIDEO_CHUNK_FRAMES = "24";
+ try {
+ const lens = [25, 40, 33, 30];
+ const segments = lens.map((f, i) => segment(dir, i, f, fps));
+ const joins = withCutEdits([null, { hold: 0.8, move: null }, null, null], 4, {
+ dips: new Map([[2, { seconds: 0.6, lastFrame: 32, black: 0.3 }]]),
+ fade: { seconds: 0.5, lastFrame: 29 },
+ });
+ const durs = lens.map((f, i) => f / fps + (joins?.[i]?.hold ?? 0));
+ const N = Math.round(scheduleFrom(durs, 0).total * fps);
+ sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12);
+ const chrome = { regions: [{ name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" };
+
+ const prerail = path.join(dir, "prerail.mp4");
+ run(hardCutFilterArgs(segments, joins, R10, prerail).slice(1));
+ const single = path.join(dir, "single.mp4");
+ run(applyChromeArgs(prerail, single, R10, chrome, null, dipWindows(joins, durs, 0, fps)).slice(1));
+
+ const chunked = path.join(dir, "chunked.mp4");
+ await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, joins, workDir: dir, hardCut: true });
+ assert.equal(probeFrames(chunked), N);
+ assert.deepEqual(frameMd5(chunked), frameMd5(single));
+ assert.ok(Math.abs(audioSeconds(chunked) - N / fps) < 0.05, `the sound runs the cut (${audioSeconds(chunked)} vs ${N / fps})`);
+ } finally {
+ setProgressMode("human");
+ delete process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("a post that grew re-encodes its own chunks only: the deck after it MOVED, keyed by bytes or by its frame keys", { skip: !have }, async () => {
+ const fps = 10;
+ const dir = mkdtempSync(path.join(tmpdir(), "chunked-hcs-"));
+ const events = [];
+ setProgressMode((e) => events.push(e));
+ try {
+ const lens = [25, 30, 33, 30];
+ const segments = lens.map((f, i) => segment(dir, i, f, fps));
+ const N = lens.reduce((a, b) => a + b, 0);
+ // The deck: one frame per cut frame, and its frame keys (here: the frame's own number).
+ const pool = path.join(dir, "pool");
+ sequence(pool, N + 20, fps, 64, 12);
+ const poolFile = (n) => path.join(pool, `frame_${String(n).padStart(6, "0")}.png`);
+ const deck = path.join(dir, "chrome", "deck-frames");
+ const framesA = Array.from({ length: N }, (_, k) => poolFile(k + 1));
+ linkedSequence(deck, framesA, framesA.map((_, k) => `f${k + 1}`));
+ const chrome = { regions: [{ name: "deck", frames: deck, x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" };
+ const out = path.join(dir, "cut.mp4");
+ await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true });
+ const rec1 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ assert.equal(rec1.chunks.length, 4);
+
+ // Segment 1 made 7 frames longer; the deck holds its last frame 7 frames more
+ // and is otherwise the same frames, later.
+ segments[1] = segment(dir, 7, 37, fps, "s1");
+ const grown = [...framesA.slice(0, 55), ...Array(7).fill(framesA[54]), ...framesA.slice(55)];
+ const grownKeys = [...Array.from({ length: 55 }, (_, k) => `f${k + 1}`), ...Array(7).fill("f55"), ...Array.from({ length: N - 55 }, (_, k) => `f${k + 56}`)];
+ linkedSequence(deck, grown, grownKeys);
+ events.length = 0;
+ await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true });
+ const rec2 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ assert.deepEqual(rec2.chunks.map((c) => c.a), [0, 25, 62, 95]);
+ const enc = rec2.chunks.filter((c, k) => c.key !== rec1.chunks[k].key).map((c) => c.anchor);
+ assert.deepEqual(enc, ["s1.mp4@0"], "only the grown segment's chunk is encoded");
+ assert.ok(events.some((e) => /3\/4 chunk\(s\) unchanged/.test(e.message ?? "")), events.map((e) => e.message).join("\n"));
+ assert.equal(probeFrames(out), N + 7);
+
+ // The deck captured again, a hair different (other bytes), drawing the same: by its keys, nothing to encode.
+ const other = Array.from({ length: N + 7 }, (_, k) => poolFile(((k + 3) % (N + 20)) + 1));
+ linkedSequence(deck, other, grownKeys);
+ events.length = 0;
+ await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true });
+ assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "recaptured frames with the same keys reuse every chunk");
+ // Without frame keys the same frames are other bytes: every chunk again.
+ linkedSequence(deck, other);
+ events.length = 0;
+ await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true });
+ assert.ok(events.some((e) => /0\/4 chunk\(s\) unchanged/.test(e.message ?? "")), "by bytes, other frames are other chunks");
+ } finally {
+ setProgressMode("human");
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -44,6 +44,8 @@ import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, t
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);
@@ -867,7 +869,7 @@ export async function composeChrome({
schedule = null, preview = false, doRender = false,
fps = null, workers = null, quality = "high", format = "png-sequence",
still = null, png = null, from = 0, duration = null, window = null, segment = null, transition = null,
- lease = null,
+ lease = null, want = null,
}) {
// The variant's view, and its own out directory. Handed the whole manifest
// the band would draw claims this cut never makes, and the deck would name
@@ -1017,8 +1019,11 @@ export async function composeChrome({
return { ...result, frames: target, cached: true };
}
if (fk) {
+ // The frames the build will read (`want`, build-video's chunk plan):
+ // only those are captured; the rest are left out (a SPARSE sequence).
+ const need = want ? await want(fk) : null;
const r = await reuseFrames({
- base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(),
+ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(), need,
});
if (r) return { ...result, frames: target, ...r };
}
@@ -1042,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 } : {}) };
@@ -1050,8 +1064,8 @@ export async function composeChrome({
// ---- frame reuse (frame-keys.mjs) --------------------------------------------
-/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1. */
-export const FRAME_KEYS_FILE = ".frame-keys";
+/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1 (the final encode keys its chunks by them). */
+export { FRAME_KEYS_FILE };
const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`;
@@ -1145,7 +1159,7 @@ export function frameDedupOn(env = process.env) {
* is the cheaper one then), or, with `dedup` off, when nothing on disk has
* frame keys.
*/
-async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true }) {
+async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true, need = null }) {
const chrome = path.join(base, "chrome");
const candidates = [target, path.join(chrome, `work-from-${stem}-frames`), path.join(chrome, `work-from-own-${stem}-frames`)];
// Every frame on disk, by key: `occ` holds each key's frames as ids
@@ -1156,24 +1170,48 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
const have = new Map();
for (const dir of candidates) {
const keys = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").then((t) => t.split("\n").filter(Boolean), () => null);
- if (!keys || (await framesOnDisk(dir)) !== keys.length) continue;
+ if (!keys) continue;
+ // A sparse sequence (`.sparse`) offers the frames it has; any other, all or none.
+ const sparse = (await stat(path.join(dir, SPARSE_FILE)).catch(() => null))?.isFile() === true;
+ const present = sparse ? new Set((await readdir(dir)).filter((f) => /^frame_\d+\.png$/.test(f))) : null;
+ if (!sparse && (await framesOnDisk(dir)) !== keys.length) continue;
const d = dirs.length;
dirs.push(dir);
- keysOf.push(keys);
+ // (A frame a sparse sequence lacks keys as nothing: never matched.)
+ keysOf.push(present ? keys.map((k, i) => (present.has(frameName(i + 1)) ? k : null)) : keys);
keys.forEach((k, i) => {
+ if (present && !present.has(frameName(i + 1))) return;
if (!occ.has(k)) occ.set(k, []);
occ.get(k).push(d * 1e7 + i);
if (!have.has(k)) have.set(k, true);
});
}
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
+ // disk and not needed is left out, and the sequence is SPARSE.
+ const wanted = need ? missing.filter((i) => need.has(i)) : missing;
// One capture per new key.
const seen = new Set();
- const capture = missing.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true)));
- if (capture.length > fk.length * 0.9) return null;
+ const capture = wanted.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true)));
+ if (!need && capture.length > fk.length * 0.9) return null;
const capDir = path.join(chrome, `work-capture-${stem}-frames`);
const capProj = path.join(chrome, `work-capture-${stem}`);
if (capture.length) {
@@ -1192,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
@@ -1227,6 +1266,9 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
if (g >= 0) off = g - i;
}
+ // Left out: a frame no disk has and nothing captured draws (a frame of a
+ // captured key is that capture, wanted or not).
+ const absent = pick.filter((src) => !src);
const next = path.join(chrome, `work-next-${stem}-frames`);
await rm(next, { recursive: true, force: true });
await mkdir(next, { recursive: true });
@@ -1234,16 +1276,17 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
// A frame deduplicated onto one inode may be at the filesystem's link cap: one copy stands in (link-or-copy.mjs).
const linkOne = makeLinker();
for (let i = 0; i < fk.length; i += 512) {
- await Promise.all(pick.slice(i, i + 512).map((src, j) => linkOne(src, path.join(next, frameName(i + j + 1)))));
+ await Promise.all(pick.slice(i, i + 512).map((src, j) => (src ? linkOne(src, path.join(next, frameName(i + j + 1))) : null)));
}
await writeFrameKeys(next, fk);
- await writeFile(path.join(next, ".key"), key + "\n", "utf8");
+ if (absent.length) await writeFile(path.join(next, SPARSE_FILE), JSON.stringify({ key, frames: fk.length, absent: absent.length }) + "\n", "utf8");
+ else await writeFile(path.join(next, ".key"), key + "\n", "utf8");
const old = path.join(chrome, `work-old-${stem}-frames`);
await rm(old, { recursive: true, force: true });
await rename(target, old).catch((e) => { if (e?.code !== "ENOENT") throw e; });
await rename(next, target);
for (const d of [old, capDir, capProj, ...candidates.slice(1)]) await rm(d, { recursive: true, force: true });
- return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: missing.length - capture.length };
+ return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: wanted.length - capture.length, ...(absent.length ? { absent: absent.length } : {}) };
}
if (import.meta.url === `file://${process.argv[1]}`) {
diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs
@@ -424,3 +424,62 @@ test("compose-chrome with the deck's items: a changed title captures only the fr
rmSync(dir, { recursive: true, force: true });
}
});
+
+test("compose-chrome `want`: only the frames asked for are drawn (a SPARSE sequence), and what it has is reused by key", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "frame-want-"));
+ const env = process.env.HYPERFRAMES_BIN;
+ try {
+ const stub = path.join(dir, "hf-stub.mjs");
+ writeFileSync(stub, STUB);
+ chmodSync(stub, 0o755);
+ process.env.HYPERFRAMES_BIN = stub;
+ const font = path.join(dir, "face.ttf");
+ writeFileSync(font, "face");
+ const render = { ...RENDER, fontRegular: font, fontBold: font };
+ const mp = path.join(dir, "video.manifest.json");
+ writeFileSync(mp, JSON.stringify({ slug: "f", render, timeline: [] }));
+ const out = path.join(dir, "out", "sourced");
+ mkdirSync(out, { recursive: true });
+ writeFileSync(path.join(out, "schedule.json"), JSON.stringify(schedule(0)));
+ const { composeChrome, FRAME_KEYS_FILE } = await import("./compose-chrome.mjs");
+ const { framesOf, frameKeyOf } = await import("./prune-frames.mjs");
+ const { readFrameKeys, SPARSE_FILE } = await import("./chunked-encode.mjs");
+ const range = (a, b) => new Set(Array.from({ length: b - a }, (_, k) => a + k));
+ const frameFiles = (d) => readdirSync(d).filter((f) => /^frame_\d+\.png$/.test(f));
+ let asked = null;
+
+ // Nothing on disk, frames 100..199 wanted: those are drawn, nothing else.
+ const first = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30, want: async (fk) => ((asked = fk.length), range(100, 200)) });
+ assert.equal(asked, 1200, "want is handed every frame's key");
+ const seq = first.frames;
+ const drawn = new Set(frameFiles(seq));
+ for (const i of range(100, 200)) assert.ok(drawn.has(`frame_${String(i + 1).padStart(6, "0")}.png`), `frame ${i + 1} drawn`);
+ assert.ok(drawn.size < 1200 && first.absent === 1200 - drawn.size, `${drawn.size} drawn (a frame of a captured key is that capture), ${first.absent} left out`);
+ assert.ok(readdirSync(seq).includes(SPARSE_FILE) && !readdirSync(seq).includes(".key"), "sparse: a .sparse, never a .key");
+ assert.equal(await framesOf(seq), 1200, "as long as the cut, for verify-build and the prune record");
+ assert.equal(await frameKeyOf(seq), first.key);
+ assert.equal((await readFrameKeys(seq, 1200))?.length, 1200, "its frame keys stand for its chunks");
+ const keys = readFileSync(path.join(seq, FRAME_KEYS_FILE), "utf8").trim().split("\n");
+ for (const f of drawn) {
+ const i = Number(f.slice(6, 12)) - 1;
+ const [, cut] = readFileSync(path.join(seq, f), "utf8").split(":");
+ assert.equal(keys[Number(cut)], keys[i], `frame ${i + 1} draws its key`);
+ }
+
+ // Asked again for 150..299: 150..199 are on disk; only new keys are captured.
+ const second = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30, want: async () => range(150, 300) });
+ for (const i of range(150, 300)) assert.ok(frameFiles(seq).includes(`frame_${String(i + 1).padStart(6, "0")}.png`), `frame ${i + 1} drawn`);
+ assert.ok(second.reused >= 50, `${second.reused} reused from the sparse sequence`);
+
+ // Without `want`: the whole sequence, a .key and no .sparse; cached whole after.
+ const third = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 });
+ assert.equal(frameFiles(seq).length, 1200);
+ assert.ok(readdirSync(seq).includes(".key") && !readdirSync(seq).includes(SPARSE_FILE));
+ assert.ok(third.reused > 0);
+ assert.equal((await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 })).cached, true);
+ } finally {
+ if (env === undefined) delete process.env.HYPERFRAMES_BIN;
+ else process.env.HYPERFRAMES_BIN = env;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/hardcut-deck.test.mjs b/umtool/report-to-video/hardcut-deck.test.mjs
@@ -0,0 +1,213 @@
+// A take's render: the deck over HARD CUTS (`transition: 0`), built in keyed
+// chunks (build-video chunkedConcat), the deck's frames drawn only where a
+// chunk to encode reads them (deckWant / compose-chrome `want`):
+//
+// - the first build encodes every chunk and draws every frame, then prunes them;
+// - the same cut again draws NO frame and encodes no chunk -- the deck's
+// frame keys say every chunk on disk is still the cut's -- and verify-build
+// still reads the deck as whole;
+// - one still made a second longer: its chunk alone is encoded, the deck's
+// frames drawn only over it, the chunk after it moved and reused.
+//
+// Real encodes, kept tiny; the deck's renderer is a stub that logs how many
+// frames each render drew. Skipped without ffmpeg/ffprobe.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs";
+import { buildVideo, setProgressMode } from "./build-video.mjs";
+import { CHUNKS_DIR, CHUNKS_RECORD } from "./chunked-encode.mjs";
+import { PRUNED_RECORD } from "./prune-frames.mjs";
+import { verifyBuild } from "./verify-build.mjs";
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" };
+const RENDER = {
+ width: 1920, height: 1080, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2,
+ palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ chrome: { engine: "hyperframes", layout: "deck", deck: {} },
+};
+
+const STUB = `#!/usr/bin/env node
+import { spawnSync } from "node:child_process";
+import { appendFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs";
+const a = process.argv.slice(2);
+const out = a[a.indexOf("--output") + 1];
+const fps = Number(a[a.indexOf("--fps") + 1]);
+const html = readFileSync(a.at(-1) + "/index.html", "utf8");
+const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]);
+const w = Number((/data-width="(\\d+)"/.exec(html) ?? [0, 640])[1]);
+const h = Number((/data-height="(\\d+)"/.exec(html) ?? [0, 360])[1]);
+mkdirSync(out, { recursive: true });
+const one = out + "/.one.png";
+spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x112233:size=" + w + "x" + h, "-frames:v", "1", one]);
+const n = Math.round(dur * fps);
+for (let i = 1; i <= n; i += 1) copyFileSync(one, out + "/frame_" + String(i).padStart(6, "0") + ".png");
+appendFileSync(process.env.HF_LOG, n + "\\n");
+`;
+
+test("a hard-cut deck build: keyed chunks, and the deck drawn only where a chunk to encode reads it", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => {
+ const root = mkdtempSync(path.join(tmpdir(), "rtv-hcdeck-"));
+ const env = { bin: process.env.HYPERFRAMES_BIN, log: process.env.HF_LOG };
+ t.after(() => {
+ for (const [k, v] of [["HYPERFRAMES_BIN", env.bin], ["HF_LOG", env.log]]) {
+ 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 drawn = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(Number) : []);
+
+ mkdirSync(path.join(root, "stills"), { recursive: true });
+ for (const [n, c] of [["one", "334455"], ["two", "554433"], ["three", "445533"]]) {
+ const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x${c}:size=320x180`, "-frames:v", "1", path.join(root, "stills", `${n}.png`)]);
+ assert.equal(r.status, 0, String(r.stderr));
+ }
+ const manifestPath = path.join(root, "video.manifest.json");
+ const write = (seconds2) => writeFileSync(manifestPath, JSON.stringify({
+ slug: "hc", title: "Hard cuts", 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: seconds2 },
+ { id: "i3", type: "image", src: "stills/three.png", seconds: 2 },
+ ],
+ }));
+ const v = path.join(root, "out", "sourced");
+ const notes = [];
+ const events = [];
+ setProgressMode((e) => {
+ events.push(e);
+ if (e.ev === "note") notes.push(e.message);
+ });
+ const record = () => JSON.parse(readFileSync(path.join(v, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+
+ // First: every chunk encoded, every frame drawn, the frames pruned after.
+ write(2);
+ await buildVideo({ manifestPath, opts: {} });
+ const rec1 = record();
+ assert.equal(rec1.frames, 60);
+ assert.deepEqual(rec1.chunks.map((c) => c.anchor), ["i1.mp4@0", "i2.mp4@0", "i3.mp4@0"], "one chunk a segment");
+ assert.equal(drawn().reduce((a, b) => a + b, 0) > 0, true);
+ assert.ok(!existsSync(path.join(v, "chrome", "deck-frames")), "pruned after the mux");
+ assert.equal((await verifyBuild(manifestPath, {})).problems.length, 0);
+
+ // The same cut: no chunk encoded, no deck frame drawn.
+ const before = drawn().length;
+ notes.length = 0;
+ await buildVideo({ manifestPath, opts: {} });
+ assert.ok(notes.some((m) => /^final encode: 3\/3 chunk\(s\) unchanged/.test(m)), notes.join("\n"));
+ assert.ok(notes.some((m) => /0 of 3 chunk\(s\) to encode read 0 of 60 deck-frames frames/.test(m)), notes.join("\n"));
+ assert.equal(drawn().length, before, "the renderer was not run");
+ assert.equal(JSON.parse(readFileSync(path.join(v, "chrome", PRUNED_RECORD), "utf8")).dirs["deck-frames"].frames, 60, "the sparse deck recorded as the cut's length");
+ assert.deepEqual((await verifyBuild(manifestPath, {})).problems, []);
+
+ // i2 a second longer: its chunk alone, the deck drawn only over it.
+ notes.length = 0;
+ write(3);
+ await buildVideo({ manifestPath, opts: {} });
+ const rec3 = record();
+ assert.equal(rec3.frames, 70);
+ const encoded = rec3.chunks.filter((c) => !rec1.chunks.some((o) => o.key === c.key)).map((c) => c.anchor);
+ assert.deepEqual(encoded, ["i2.mp4@0"], "only the grown still's chunk");
+ const read = notes.find((m) => /chunk\(s\) to encode read/.test(m));
+ assert.match(read, /1 of 3 chunk\(s\) to encode read (\d+) of 70/);
+ 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: a cut built before it is filed by its next build; 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);
+ });
+ // Built before the pool (off), then again with it: what it reused of its own is filed.
+ process.env.UMTOOL_RENDER_POOL = "0";
+ const ma = project("a");
+ await buildVideo({ manifestPath: ma, opts: {} });
+ process.env.UMTOOL_RENDER_POOL = pool;
+ await buildVideo({ manifestPath: ma, opts: {} });
+ const runs = drawn().length;
+ const { poolStats } = await import("./render-pool.mjs");
+ const s1 = await poolStats(pool);
+ assert.equal(s1.kinds.chunk.objects, 2, "its chunks filed");
+ assert.equal(s1.kinds.sound.objects, 1, "its sound filed");
+
+ // 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
@@ -35,6 +35,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));
@@ -1235,8 +1236,22 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const key = postSegmentKey(postSegmentKeyOf({ entry, redaction, box, place, render, encode, stamps, avatars, take, plan, bleeps, layout, from, prev }));
const record = postRecordPath(seg);
const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null);
+ // The render pool (render-pool.mjs): this item, by this key, built by any take of any project.
+ const pool = await poolFor(outDir);
if (had?.key === key && (await stat(seg).catch(() => null))) {
emit("note", { message: `${entry.id}: post item unchanged — its segment kept` });
+ // (One the pool has not got -- built before it, or linked in by --from -- is filed now: the item as
+ // post-render made it, which a combo badge's pass keeps beside it as `.plain.mp4`.)
+ if (pool) {
+ const badged = await stat(seg.replace(/\.mp4$/, ".combo.json")).catch(() => null);
+ const plain = seg.replace(/\.mp4$/, ".plain.mp4");
+ const made = !badged ? seg : (await stat(plain).catch(() => null)) ? plain : null;
+ if (made) await poolPut(pool, "post", key, { "seg.mp4": made, "post.json": record });
+ }
+ return seg;
+ }
+ 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}`);
@@ -1298,6 +1313,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 } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(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/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs
@@ -61,6 +61,11 @@ export async function keepFramesAsked(outRoot) {
}
const FRAME_RE = /^frame_\d+\.png$/;
+/** A sparse sequence's `.sparse` (`{ key, frames, absent }`), or null. */
+async function sparseRecord(dir) {
+ return readFile(path.join(dir, ".sparse"), "utf8").then((s) => JSON.parse(s), () => null);
+}
+
/** Is this `chrome/` entry one a prune removes? A real directory, named for it. */
export function isPrunable(dirent) {
return dirent.isDirectory() && (dirent.name.endsWith("-frames") || dirent.name.startsWith("work-"));
@@ -103,9 +108,7 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date(), se
let bytes = 0;
for (const name of sequences) {
const dir = path.join(chromeDir, name);
- const files = await readdir(dir).catch(() => []);
- const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null);
- dirs[name] = { frames: files.filter((f) => FRAME_RE.test(f)).length, key };
+ dirs[name] = { frames: await framesOf(dir), key: await frameKeyOf(dir) };
}
for (const name of [...sequences, ...work]) bytes += await dirBytes(path.join(chromeDir, name));
const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs };
@@ -174,6 +177,8 @@ async function recorded(dir, since) {
*/
export async function framesOf(dir, { since = null } = {}) {
const files = await readdir(dir).catch(() => null);
+ // A SPARSE sequence (chunked-encode.mjs SPARSE_FILE) is as long as its record says.
+ if (files?.includes(".sparse")) return Number((await sparseRecord(dir))?.frames ?? 0);
if (files) return files.filter((f) => FRAME_RE.test(f)).length;
return Number((await recorded(dir, since))?.frames ?? 0);
}
@@ -181,6 +186,7 @@ export async function framesOf(dir, { since = null } = {}) {
/** A sequence's render key: its `.key`, or the one the prune recorded; null when neither. */
export async function frameKeyOf(dir, { since = null } = {}) {
const files = await readdir(dir).catch(() => null);
+ if (files?.includes(".sparse")) return (await sparseRecord(dir))?.key ?? null;
if (files) return readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null);
return (await recorded(dir, since))?.key ?? null;
}
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}`);
@@ -172,11 +174,24 @@ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmp
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` });
+ // (Filed in the render pool when it has not got it: built before it, or linked in by --from.)
+ await poolPut(await poolFor(outDir), "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) });
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` });
}
}
+ // 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 +206,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 });