commit 870e7434f16daaf4f1c6007a31333b71edcf9706
parent 012e048c2d842160a1ea0d248f3c4d292db08e77
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 29 Oct 2026 10:30:23 -0400
Merge lane/render-cache-2: take --from reuses fully, the variant ladder from the master's chunks, seeded fit scales
Conflicts: takeMaker.mjs (makeTake's doc: both the keep-frames marker and the
build lock / prune-after sentences), variants.mjs (imports: render-estimate's
renderEstimateMb and the ladder-chunks imports). takePrune.mjs now names
out/ladder/chunks/ as work (the ladder's rung chunks) and no longer treats
out/ladder/ as a variant dir; its writer-name test checks LADDER_DIR.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
16 files changed, 1162 insertions(+), 65 deletions(-)
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -932,8 +932,10 @@ umtool take <project> --id final-uncensored --label "Final, uncensored" --set re
hard-links `takes/final-blurred/out/sourced/`'s clip segments (the files `SEGMENT_FILE_SUFFIXES`
names), each keyed chrome render (`chrome/<layer>-frames/` with its `.key`; a layer kept aside in
-`takes/<other>/out/.keep-frames/<layer>-frames` is linked in as `chrome/<layer>-frames`) and its
-finished crossfade batches into this take's `out/sourced/`, then renders as usual: whatever still
+`takes/<other>/out/.keep-frames/<layer>-frames` is linked in as `chrome/<layer>-frames`), its
+finished crossfade batches, its final-encode chunks and their record (`chunks/chunks.json`, unless
+this take's own is newer) into this take's `out/sourced/` -- the same for `out/full/` when the other
+take built that variant -- and its variant-ladder chunks into `out/ladder/chunks/`, then renders as usual: whatever still
matches is reused, the rest is rebuilt. A batch keys by its segments' file names, sizes and mtimes
(no longer their full paths), so the same batch keys alike in both takes; a batch the other take
made under the old path key is adopted when this take's segments are those very files (the same
@@ -943,7 +945,9 @@ refuses a take that does not exist, this take itself, or a take with no `out/sou
anything is written. A chrome layer reuses its frames only when they are on disk: a build prunes
`chrome/<layer>-frames` after its mux (1–3 GB a layer for a full cut), so make the take you will
start a twin from with **`--keep-frames`** (passed to the build), or its twin captures the chrome
-again. The blur is in the segments' pictures only — no chrome layer draws it — so an uncensored
+again. `--keep-frames` also marks the take (`out/.keep-frames/asked.json`): a later build of it
+without the flag (a `--rebuild`) sets its chrome sequences aside in `out/.keep-frames/` instead of
+pruning them, where a `--from` twin finds them. The blur is in the segments' pictures only — no chrome layer draws it — so an uncensored
twin rebuilds the blurred clips, their crossfade batches and the final overlay pass, and reuses
the rest.
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -54,11 +54,14 @@ export const TAKE_USAGE = [
`cut. Default window: --at ${DEFAULT_WINDOW.at} --dur ${DEFAULT_WINDOW.dur}. Nothing is fetched. --quick encodes`,
"the render with x264 veryfast (the render only: the take's manifest, what a pick uses, keeps its own).",
"--effect NAME is one of `umtool takes effects <project>` (an overlay effect's patch, before --patch's).",
- "--from TAKE hard-links that take's built clip segments, chrome frames and crossfade batches into this",
- "take's out/ first; the render then reuses each one whose key still matches this cut and rebuilds the rest",
- "(an uncensored twin of a blurred take rebuilds only the blurred clip). The other take's files are never",
- "changed. --keep-frames keeps this take's chrome frames after the mux (1-3 GB a layer for a full cut), so",
- "a later --from can reuse them; without it they are pruned, and a --from twin captures the chrome again.",
+ "--from TAKE hard-links that take's built clip segments, chrome frames, crossfade batches, encode chunks",
+ "(and their record), its full variant's too, and its variant-ladder chunks into this take's out/ first; the",
+ "render then reuses each one whose key still matches this cut and rebuilds the rest (an uncensored twin of",
+ "a blurred take rebuilds only the blurred clip). The other take's files are never changed. --keep-frames",
+ "keeps this take's chrome frames after the mux (1-3 GB a layer for a full cut), so a later --from can reuse",
+ "them, and marks the take (out/.keep-frames/asked.json): a later build of it without the flag sets its",
+ "frames aside in out/.keep-frames/ instead of pruning them. Without it they are pruned, and a --from twin",
+ "captures the chrome again.",
].join("\n");
export const TAKES_USAGE = [
diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs
@@ -21,6 +21,22 @@
// when its key (its inputs' CONTENTS) is
// (chunked-encode.mjs), and the content-
// hash memo, merged
+// chunks/chunks.json the other take's record of its chunks,
+// when this take has none or an older one:
+// the build's "why re-encoded" compares
+// against it rather than "first build"
+//
+// All of that for the `sourced` variant, and for the `full` variant too when
+// the other take built one (out/full/, its own .keep-frames/full/). And, from
+// the other take's out/ (not a variant's):
+//
+// ladder/chunks/<key>.mp4|m4a each encoded rung chunk of the variant
+// ladder (ladder-chunks.mjs), keyed by the
+// master chunk it was made from and the
+// rung's settings; and, into this take's
+// own ladder/ladder.json (written, not
+// linked), each size-capped rung's last
+// good scale it has none of
//
// THIS take's own files win when they are newer (release fast-rerender): a
// take re-run `--force --from <other>` after it was stopped mid-render has
@@ -37,7 +53,8 @@
// REPLACES rather than writes -- a segment through a rename
// (encodeSegmentCached), its records and texts through a rename (replaceFile),
// a chrome sequence by removing the directory and rendering a new one, a batch
-// through a rename after the stale ones are removed -- so a rebuild here never
+// through a rename after the stale ones are removed, the chunk record through a
+// rename (replaceFile) -- so a rebuild here never
// changes a byte of the other take's. Nothing else is linked: the chrome
// compositions (chrome/deck/index.html …) are written in place each run.
//
@@ -45,12 +62,15 @@
import { link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
-import { DEFAULT_VARIANT, SEGMENT_FILE_SUFFIXES, XFADE_FROM_FILE } from "umtool-report-to-video/build-video";
-import { CHUNKS_DIR, HASH_MEMO_FILE } from "umtool-report-to-video/chunked-encode";
+import { DEFAULT_VARIANT, SEGMENT_FILE_SUFFIXES, VARIANTS, XFADE_FROM_FILE } from "umtool-report-to-video/build-video";
+import { CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE } from "umtool-report-to-video/chunked-encode";
+import { LADDER_CHUNKS_DIR, LADDER_DIR, isLadderChunkFile } from "umtool-report-to-video/ladder-chunks";
+import { KEEP_FRAMES_DIR, keptFramesDir } from "umtool-report-to-video/prune-frames";
+import { seedLadderFit } from "umtool-report-to-video/variants";
import { takesDirOf } from "./takes.mjs";
-/** Where `--from` keeps a layer aside: the other take's `out/.keep-frames/<layer>-frames`. */
-export const KEEP_FRAMES_DIR = ".keep-frames";
+/** Where a take keeps a layer aside: its `out/.keep-frames/<layer>-frames` (prune-frames.mjs). */
+export { KEEP_FRAMES_DIR };
const isFile = async (p) => (await lstat(p).catch(() => null))?.isFile() === true;
const isDir = async (p) => (await lstat(p).catch(() => null))?.isDirectory() === true;
@@ -96,14 +116,49 @@ export async function fromTakeSourced(projectDir, id, from) {
}
/**
- * Hard-link take `from`'s built files into `takeOut/sourced` (see the top of the file).
- * @returns {Promise<{ segments: number, frames: string[], batches: number, chunks: number, keptOwn: string[], keptOwnFrames: string[] }>}
+ * Hard-link take `from`'s built files into `takeOut/<variant>` -- `sourced`,
+ * and `full` when the other take built it -- and its ladder chunks into
+ * `takeOut/ladder/` (see the top of the file). The counts are summed over the
+ * variants; a frame layer of the full variant is named `full/<layer>-frames`.
+ * @returns {Promise<{ segments: number, frames: string[], batches: number, chunks: number, records: number,
+ * ladder: number, ladderFit?: string[], variants: string[], keptOwn: string[], keptOwnFrames: string[] }>}
*/
export async function linkFromTake(projectDir, id, from, takeOut) {
const src = await fromTakeSourced(projectDir, id, from);
- const dst = path.join(takeOut, DEFAULT_VARIANT);
- if (path.resolve(src) === path.resolve(dst)) throw new Error(`--from ${from}: that is this take's own out/`);
- const out = { segments: 0, frames: [], batches: 0 };
+ const otherOut = path.dirname(src);
+ if (path.resolve(src) === path.resolve(path.join(takeOut, DEFAULT_VARIANT))) throw new Error(`--from ${from}: that is this take's own out/`);
+ const out = { segments: 0, frames: [], batches: 0, chunks: 0, records: 0, ladder: 0, variants: [], keptOwn: [], keptOwnFrames: [] };
+ for (const variant of VARIANTS) {
+ const vSrc = path.join(otherOut, variant);
+ if (variant !== DEFAULT_VARIANT && !(await isDir(vSrc))) continue;
+ const got = await linkVariant({ src: vSrc, dst: path.join(takeOut, variant), kept: keptFramesDir(otherOut, variant), from });
+ const tag = (x) => (variant === DEFAULT_VARIANT ? x : `${variant}/${x}`);
+ out.segments += got.segments;
+ out.batches += got.batches;
+ out.chunks += got.chunks;
+ out.records += got.records;
+ out.frames.push(...got.frames.map(tag));
+ out.keptOwn.push(...got.keptOwn.map(tag));
+ out.keptOwnFrames.push(...got.keptOwnFrames.map(tag));
+ out.variants.push(variant);
+ }
+ // The variant ladder's encoded chunks, by content key: theirs beside ours.
+ const ladder = path.join(otherOut, LADDER_DIR, LADDER_CHUNKS_DIR);
+ const ladderOut = path.join(takeOut, LADDER_DIR, LADDER_CHUNKS_DIR);
+ for (const f of await names(ladder)) {
+ if (!isLadderChunkFile(f) || !(await isFile(path.join(ladder, f)))) continue;
+ await mkdir(ladderOut, { recursive: true });
+ if (!(await isFile(path.join(ladderOut, f))) && (await linkFile(path.join(ladder, f), path.join(ladderOut, f)))) out.ladder += 1;
+ }
+ // Its size-capped rungs' last good scales, as where this take's start: the
+ // chunks the two cuts share then key alike on those rungs too.
+ out.ladderFit = await seedLadderFit(otherOut, takeOut);
+ return out;
+}
+
+/** One variant's files, `src` (the other take's out/<variant>) into `dst`; `kept` its set-aside layers. */
+async function linkVariant({ src, dst, kept, from }) {
+ const out = { segments: 0, frames: [], batches: 0, chunks: 0, records: 0, keptOwn: [], keptOwnFrames: [] };
const segs = path.join(src, "segments");
const segOut = path.join(dst, "segments");
@@ -122,7 +177,6 @@ export async function linkFromTake(projectDir, id, from, takeOut) {
}
const newest = async (dir, files) => Math.max(0, ...(await Promise.all(files.map((f) => lstat(path.join(dir, f)).then((st) => st.mtimeMs, () => 0)))));
const ownNames = await names(segOut);
- out.keptOwn = [];
for (const [id, theirs] of [...groups].sort((x, y) => x[0].localeCompare(y[0]))) {
const own = ownNames.filter((f) => !f.startsWith(".") && idOf(f) === id);
const ownFiles = [];
@@ -144,7 +198,6 @@ export async function linkFromTake(projectDir, id, from, takeOut) {
// The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside.
const chrome = path.join(src, "chrome");
- const kept = path.join(path.dirname(src), KEEP_FRAMES_DIR);
// 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]) {
@@ -157,7 +210,6 @@ export async function linkFromTake(projectDir, id, from, takeOut) {
}
}
if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true });
- out.keptOwnFrames = [];
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);
@@ -184,12 +236,20 @@ export async function linkFromTake(projectDir, id, from, takeOut) {
// The final encode's chunks and sound, by content key: theirs beside ours.
const chunks = path.join(src, CHUNKS_DIR);
const chunksOut = path.join(dst, CHUNKS_DIR);
- out.chunks = 0;
for (const f of await names(chunks)) {
if (!/^(chunk|audio)-[0-9a-f]+\.(mp4|m4a)$/.test(f) || !(await isFile(path.join(chunks, f)))) continue;
await mkdir(chunksOut, { recursive: true });
if (!(await isFile(path.join(chunksOut, f))) && (await linkFile(path.join(chunks, f), path.join(chunksOut, f)))) out.chunks += 1;
}
+ // Their record of the chunks, unless ours is newer: what "why re-encoded" compares with.
+ const theirRecord = await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null);
+ if (theirRecord?.isFile()) {
+ const ownRecord = await lstat(path.join(chunksOut, CHUNKS_RECORD)).catch(() => null);
+ if (!ownRecord?.isFile() || ownRecord.mtimeMs < theirRecord.mtimeMs) {
+ await mkdir(chunksOut, { recursive: true });
+ if (await linkFile(path.join(chunks, CHUNKS_RECORD), path.join(chunksOut, CHUNKS_RECORD))) out.records += 1;
+ }
+ }
// The content-hash memo: theirs merged into ours (both name files by inode).
const memoOf = (d) => readFile(path.join(d, HASH_MEMO_FILE), "utf8").then((t) => JSON.parse(t), () => null);
const [theirMemo, ownMemo] = await Promise.all([memoOf(src), memoOf(dst)]);
diff --git a/umtool/lib/report/takeFrom.test.mjs b/umtool/lib/report/takeFrom.test.mjs
@@ -136,6 +136,84 @@ test("linkFromTake: this take's own NEWER build (a re-run after a stop) is kept,
}
});
+test("linkFromTake: the chunk record (unless ours is newer), the full variant, the ladder chunks", async () => {
+ const p = await project();
+ try {
+ // The other take's chunks and their record, and a built full variant with a set-aside layer.
+ await mkdir(path.join(p.src, "chunks"), { recursive: true });
+ await writeFile(path.join(p.src, "chunks", "chunk-0a1b.mp4"), "chunk");
+ await writeFile(path.join(p.src, "chunks", "chunks.json"), '{"version":1,"chunks":[]}\n');
+ await writeFile(path.join(p.src, "chunks", "concat.txt"), "file 'chunk-0a1b.mp4'\n");
+ const other = path.dirname(p.src);
+ const full = path.join(other, "full");
+ await mkdir(path.join(full, "segments"), { recursive: true });
+ await mkdir(path.join(full, "chunks"), { recursive: true });
+ await writeFile(path.join(full, "segments", "s01.mp4"), "full s01");
+ await writeFile(path.join(full, "segments", "s01.cut.json"), "{}");
+ await writeFile(path.join(full, "chunks", "chunk-ffee.mp4"), "full chunk");
+ await writeFile(path.join(full, "chunks", "chunks.json"), "{}\n");
+ const keptFull = path.join(other, ".keep-frames", "full", "deck-frames");
+ await mkdir(keptFull, { recursive: true });
+ await writeFile(path.join(keptFull, "frame_000001.png"), "full deck");
+ await writeFile(path.join(keptFull, ".key"), "kf\n");
+
+ const out = path.join(p.dir, "takes", "twin", "out");
+ const got = await linkFromTake(p.dir, "twin", "blurred", out);
+ assert.deepEqual(got.variants, ["sourced", "full"]);
+ assert.equal(got.records, 2);
+ assert.equal(got.chunks, 2);
+ assert.ok(sameFile(path.join(p.src, "chunks", "chunks.json"), path.join(out, "sourced", "chunks", "chunks.json")));
+ assert.ok(!existsSync(path.join(out, "sourced", "chunks", "concat.txt")), "the concat list is written in place by the build: not linked");
+ assert.ok(sameFile(path.join(full, "segments", "s01.mp4"), path.join(out, "full", "segments", "s01.mp4")));
+ assert.ok(sameFile(path.join(full, "chunks", "chunk-ffee.mp4"), path.join(out, "full", "chunks", "chunk-ffee.mp4")));
+ assert.ok(got.frames.includes("full/deck-frames"), got.frames.join(", "));
+ assert.equal(await readFile(path.join(out, "full", "chrome", "deck-frames", ".key"), "utf8"), "kf\n");
+ assert.equal(await readFile(path.join(out, "sourced", "chrome", "deck-frames", "frame_000001.png"), "utf8"), "png", "sourced's deck is sourced's");
+
+ // Our own NEWER record is kept.
+ const ours = path.join(out, "sourced", "chunks", "chunks.json");
+ await rm(ours);
+ await writeFile(ours, '{"version":1,"ours":true}\n');
+ const later = new Date(Date.now() + 60_000);
+ await utimes(ours, later, later);
+ const again = await linkFromTake(p.dir, "twin", "blurred", out);
+ assert.equal(again.records, 0);
+ assert.match(await readFile(ours, "utf8"), /"ours":true/);
+ // The other take's ladder chunks (its out/ladder/chunks/), by key; nothing else of the ladder.
+ const ladder = path.join(other, "ladder", "chunks");
+ await mkdir(ladder, { recursive: true });
+ const rungFile = `rung-${"ab".repeat(12)}.mp4`;
+ await writeFile(path.join(ladder, rungFile), "rung");
+ await writeFile(path.join(ladder, `.rung-${"cd".repeat(12)}.1.partial.mp4`), "half");
+ const basis = { maxMiB: 24, seconds: 781.37, srcHeight: 1080, maxHeight: null };
+ await writeFile(path.join(other, "ladder", "ladder.json"), JSON.stringify({
+ version: 1, master: { id: "x" },
+ rungs: { "720p": { keys: ["a"], audio: "copy", master: "x", file: "f" }, fit24: { keys: ["b"], audio: "c", master: "x", file: "g", fit: { basis, scale: 0.94 } } },
+ }));
+ const withLadder = await linkFromTake(p.dir, "twin", "blurred", out);
+ assert.equal(withLadder.ladder, 1);
+ assert.ok(sameFile(path.join(ladder, rungFile), path.join(out, "ladder", "chunks", rungFile)));
+ assert.deepEqual((await import("node:fs")).readdirSync(path.join(out, "ladder", "chunks")), [rungFile]);
+ // Their record is not linked; their size-capped rung's scale seeds ours.
+ assert.deepEqual(withLadder.ladderFit, ["fit24"]);
+ const seededRec = JSON.parse(await readFile(path.join(out, "ladder", "ladder.json"), "utf8"));
+ assert.deepEqual(seededRec.rungs, { fit24: { keys: [], audio: null, master: null, file: null, fit: { basis, scale: 0.94 } } });
+ assert.ok(!sameFile(path.join(other, "ladder", "ladder.json"), path.join(out, "ladder", "ladder.json")));
+ // Our own scale is never overwritten.
+ seededRec.rungs.fit24.fit.scale = 0.88;
+ await writeFile(path.join(out, "ladder", "ladder.json"), JSON.stringify(seededRec));
+ const again2 = await linkFromTake(p.dir, "twin", "blurred", out);
+ assert.equal(again2.ladder, 0);
+ assert.deepEqual(again2.ladderFit, []);
+ assert.equal(JSON.parse(await readFile(path.join(out, "ladder", "ladder.json"), "utf8")).rungs.fit24.fit.scale, 0.88);
+ // No full variant on the other side: only sourced.
+ await rm(full, { recursive: true });
+ assert.deepEqual((await linkFromTake(p.dir, "twin", "blurred", out)).variants, ["sourced"]);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
test("makeTake --from: linked before the render; --keep-frames reaches the build; a bad --from is refused before anything is written", async () => {
const p = await project();
try {
@@ -149,6 +227,9 @@ test("makeTake --from: linked before the render; --keep-frames reaches the build
const opts = { render, probe: async () => 1, styles: {} };
await makeTake(p.dir, { id: "twin", label: "Twin", patch: { render: { blur: "off" } }, window: "full" }, { ...opts, from: "blurred", keepFrames: true });
assert.deepEqual(seen, [{ keepFrames: true, linked: true }]);
+ // --keep-frames marks the take: a later build of it sets its frames aside.
+ assert.ok(existsSync(path.join(p.dir, "takes", "twin", "out", ".keep-frames", "asked.json")));
+ assert.ok(!existsSync(path.join(p.dir, "takes", "blurred", "out", ".keep-frames", "asked.json")), "the other take is not marked");
for (const [from, re] of [["twin", /that is this take/], ["nope", /no such take/]]) {
await assert.rejects(makeTake(p.dir, { id: "twin", label: "Twin", window: "full" }, { ...opts, force: true, from }), re);
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -48,6 +48,7 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
import { mergePatch } from "umtool-report-to-video/montage-styles";
import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings";
+import { markKeepFrames } from "umtool-report-to-video/prune-frames";
import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs";
import { replaceManifest } from "./manifest.mjs";
import { withEditNotes } from "./edit-guard.mjs";
@@ -480,7 +481,9 @@ export async function linkSharedOut(projectDir, takeOut) {
* `from`: another take whose built segments, chrome renders and crossfade
* batches are hard-linked in before the render (takeFrom.mjs), so the build
* reuses whatever still matches. `keepFrames`: the build keeps its chrome
- * frames after the mux (build-video --keep-frames), for a later `from`.
+ * frames after the mux (build-video --keep-frames), for a later `from`, and
+ * the take is marked (out/.keep-frames/asked.json) so a later build of it
+ * sets its frames aside rather than pruning them (prune-frames.mjs).
* `pruneAfter: false`: no prune after the take is made (see below).
*
* While it builds, the take holds a build lock (`takes/<id>/.building.json`,
@@ -587,12 +590,18 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
await (opts.ensureOut ?? ((d) => mkdir(d, { recursive: true })))(takeOut);
const linked = await linkSharedOut(projectDir, takeOut);
if (linked.length) log(`${spec.id}: reusing the project's ${linked.join(" and ")}`);
+ // Asked once, kept: a later build of this take without --keep-frames sets
+ // its chrome frames aside in out/.keep-frames/ rather than pruning them.
+ if (opts.keepFrames === true) await markKeepFrames(takeOut, { now });
if (fromTake) {
const got = await fromTake.linkFromTake(projectDir, spec.id, /** @type {string} */ (opts.from), takeOut);
log(
`${spec.id}: linked from ${opts.from}: ${got.segments} segment file(s), ` +
`${got.frames.length ? got.frames.join(", ") : "no chrome frames"}, ${got.batches} crossfade batch(es), ` +
- `${got.chunks ?? 0} encode chunk(s) — reused where they still match`,
+ `${got.chunks ?? 0} encode chunk(s)${got.records ? ` and ${got.records} chunk record(s)` : ""}` +
+ `${got.ladder ? `, ${got.ladder} ladder chunk(s)` : ""}` +
+ `${got.ladderFit?.length ? ` (the scale ${got.ladderFit.join(", ")} landed at)` : ""}` +
+ `${(got.variants?.length ?? 1) > 1 ? ` (variants ${got.variants.join(", ")})` : ""} — reused where they still match`,
);
// This take's own newer build, kept (takeFrom.mjs): said, so a re-run says why it did not start over.
if (got.keptOwn?.length || got.keptOwnFrames?.length) {
diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs
@@ -10,6 +10,8 @@
// except the WORK this file names, all of it under the take's `out/`:
//
// out/.keep-frames/ layers kept aside for a --from (takeFrom.mjs)
+// out/ladder/chunks/ the variant ladder's encoded rung chunks
+// (ladder-chunks.mjs; ladder.json stays)
// out/clips-raw/ a real directory of raw clip copies (the
// usual one is a LINK to the project's: not work)
// out/<variant>/segments/*.mp4 each clip's encoded segment -- its records
@@ -95,7 +97,8 @@ export const DISK_GUARD_DEFAULTS = Object.freeze({ thresholdGB: 30, floorGB: 10
// not imported, so the CLI need not load build-video.mjs to prune).
export const KEEP_FRAMES_DIR = ".keep-frames"; // takeFrom.mjs
export const XFADE_FROM_FILE = ".from.json"; // build-video.mjs
-const NOT_VARIANTS = new Set(["clips-raw", "narration", "bench-excerpts", "posts-media", KEEP_FRAMES_DIR]);
+export const LADDER_DIR = "ladder"; // ladder-chunks.mjs
+const NOT_VARIANTS = new Set(["clips-raw", "narration", "bench-excerpts", "posts-media", KEEP_FRAMES_DIR, LADDER_DIR]);
// kind "files": the files in that directory whose names match, never the
// directory or anything else in it.
const IN_VARIANT = [
@@ -360,6 +363,7 @@ export async function workPathsOf(takeDir, { reportsRoot = REPORTS_ROOT, mediaRo
};
await add(path.join(/* turbopackIgnore: true */ out, KEEP_FRAMES_DIR), "dir", "chrome frames kept aside for --from");
await add(path.join(/* turbopackIgnore: true */ out, "clips-raw"), "dir", "raw clip copies");
+ await add(path.join(/* turbopackIgnore: true */ out, LADDER_DIR, "chunks"), "dir", "the variant ladder's encoded chunks");
for (const v of await names(out)) {
if (!v.isDirectory() || v.name.startsWith(".") || NOT_VARIANTS.has(v.name)) continue;
const vdir = path.join(/* turbopackIgnore: true */ out, v.name);
diff --git a/umtool/lib/report/takePrune.test.mjs b/umtool/lib/report/takePrune.test.mjs
@@ -14,6 +14,7 @@ import {
BUILD_LOCK,
DiskGuardRefused,
KEEP_FRAMES_DIR,
+ LADDER_DIR,
PRUNE_RECORD,
XFADE_FROM_FILE,
deleteViewOf,
@@ -474,7 +475,10 @@ test("the names it prunes by are its writers' names", async () => {
const bv = await import("umtool-report-to-video/build-video");
const ce = await import("umtool-report-to-video/chunked-encode");
const tf = await import("./takeFrom.mjs");
+ const lc = await import("umtool-report-to-video/ladder-chunks");
assert.equal(XFADE_FROM_FILE, bv.XFADE_FROM_FILE);
+ assert.equal(LADDER_DIR, lc.LADDER_DIR);
+ assert.equal(lc.LADDER_CHUNKS_DIR, "chunks");
assert.equal(KEEP_FRAMES_DIR, tf.KEEP_FRAMES_DIR);
assert.equal(bv.DEFAULT_VARIANT, "sourced");
assert.equal(ce.CHUNKS_DIR, "chunks");
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -2905,8 +2905,9 @@ usual reason a naive concat produces a broken or audio-desynced file.
| `preset` | x264's | `medium` | |
At most 12. `master` takes no settings. A crf variant re-encodes the picture
-at its height (lanczos, never up) and copies the sound and the chapters. A
-`maxMiB` variant is two-pass x264: its sound AAC 48 kb/s mono when the whole
+at its height (lanczos, never up) and copies the sound and the chapters; one
+at the master's own height IS the master (`<slug>.<name>.mp4` a hard link of
+it, never re-encoded). A `maxMiB` variant is x264 at a bitrate: its sound AAC 48 kb/s mono when the whole
budget is under 300 kb/s, else 96 kb/s stereo; its height the largest of
1080/720/480 (no taller than the cut) whose picture keeps at least 100 kb/s
per 480p's worth of pixels (225 at 720p, 506 at 1080p) — the 20-minute Huck
@@ -2914,8 +2915,41 @@ cut at 24 MiB is 480p at ~115 kb/s; 2 % of the budget is left for the
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
+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
+by the master's inode and the record), each rung is encoded chunk by chunk:
+
+- a rung chunk is `out/ladder/chunks/rung-<key>.mp4`, its key
+ `sha256(master chunk key, the rung's settings, ffmpeg)` (`rungChunkKey`);
+ only a key not on disk is encoded (`encodeChunkCached`), `REPORT_VIDEO_CHUNK_JOBS`
+ (default 2) at once;
+- the rung is the chunks joined by the concat demuxer, `-c copy`, with the
+ master's sound, metadata and chapters copied;
+- a rung whose keys, sound and master are the ones its file was joined from
+ (`out/ladder/ladder.json`) is not touched at all;
+- a `maxMiB` rung is one-pass ABR per chunk at the plan's bitrate, its sound
+ encoded once (`audio-<key>.m4a`, keyed by the master's sound's packets);
+ while it lands over it is lowered by what it overshot (at least 6 %), and
+ the scale it last landed under at is kept, so the next run starts there
+ with the same keys and encodes nothing;
+- rung chunks no rung of the ladder names are removed after a run;
+- `umtool take --from` links the other take's `out/ladder/chunks/` and seeds
+ this take's `ladder.json` with its size-capped rungs' last good scales
+ (`seedLadderFit`; never over one of this take's own), so a twin's first
+ ladder run encodes only the chunks that differ, on every rung.
+
+So a change to one clip re-encodes that clip's chunks on every rung, and a
+second run with nothing changed encodes nothing. `--whole` (or no chunks, or
+a master built another way since) encodes each rung from the whole cut, a
+`maxMiB` one two-pass, as before. `variants.json`'s items carry `encode`:
+`{ from: "chunks", chunks, encoded, reused, seconds, unchanged?, scale? }`,
+`{ from: "master", linked: true }` or `{ from: "whole", seconds }`.
+
```
-node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file]
+node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] [--whole]
```
The slug and the ladder come from the take's `video.manifest.json` beside
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -205,7 +205,7 @@ import { snap } from "./snap.mjs";
export { snap };
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
-import { pruneChromeFrames } from "./prune-frames.mjs";
+import { keepFramesAsked, keptFramesDir, pruneChromeFrames } from "./prune-frames.mjs";
import { encodeSegmentCached, ffmpegIdentity } from "./segment-cache.mjs";
import {
CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, chunkKey, chunkSpans, framesRead, sequenceIdentity, spanSegments, whyRebuilt,
@@ -4874,11 +4874,12 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo
}
await rename(tmpOut, outPath);
- // The record, and nothing kept that this cut does not use.
- await writeFile(path.join(dir, CHUNKS_RECORD), JSON.stringify({
+ // The record, and nothing kept that this cut does not use. Through a rename:
+ // `take --from` hard-links another take's record here (takeFrom.mjs).
+ await replaceFile(path.join(dir, CHUNKS_RECORD), JSON.stringify({
version: 1, builtAt: new Date().toISOString(), frames: N, fps, audio: path.basename(audio),
chunks: plan.map((p) => p.rec),
- }, null, 2) + "\n", "utf8");
+ }, null, 2) + "\n");
// The memo keeps what this cut is made of: a frame or segment gone is forgotten.
memo.pruneUnseen();
await memo.save();
@@ -6149,14 +6150,19 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// a segment. Not under the legacy chart band (`hyper`), whose frames are an
// input made outside the build, nor after `--no-chrome`, which rendered no
// chrome and leaves the last render's frames for a `--chrome-only`.
+ // A take that asked to keep its frames (`<out>/.keep-frames/asked.json`,
+ // umtool take --keep-frames) has them SET ASIDE in `<out>/.keep-frames/`
+ // instead, for a later `take --from` (prune-frames.mjs).
const pruneFrames = async () => {
if (opts.keepFrames || hyper || (deck && opts.noChrome)) return;
- const p = await pruneChromeFrames(outDir);
+ const aside = (await keepFramesAsked(outRoot)) ? keptFramesDir(outRoot, variant) : null;
+ const p = await pruneChromeFrames(outDir, { setAside: aside });
if (p.sequences.length || p.work.length) {
EMIT("note", {
message:
- `pruned ${p.sequences.length} frame sequence(s)` +
- (p.work.length ? ` and ${p.work.length} renderer work dir(s)` : "") +
+ `${p.setAside ? "set aside" : "pruned"} ${p.sequences.length} frame sequence(s)` +
+ (p.setAside ? ` in ${path.relative(outRoot, p.setAside)}/ (this take asked to keep its frames)` : "") +
+ (p.work.length ? ` and ${p.setAside ? "removed " : ""}${p.work.length} renderer work dir(s)` : "") +
`, ${(p.bytes / (1 << 20)).toFixed(0)} MiB (chrome/pruned.json records them; --keep-frames keeps them)`,
});
}
diff --git a/umtool/report-to-video/ladder-chunks.mjs b/umtool/report-to-video/ladder-chunks.mjs
@@ -0,0 +1,280 @@
+// THE VARIANT LADDER FROM THE MASTER'S CHUNKS: each rung of the encode ladder
+// (variants.mjs) is encoded chunk by chunk from the chunks the master itself
+// was joined from (chunked-encode.mjs), each rung chunk keyed by
+//
+// sha256(the master chunk's key, the rung's settings, the ffmpeg binary)
+//
+// and joined with `-c copy`, the sound beside (the master's, copied; or for a
+// size-capped rung, re-encoded once and cached by its own key). A master
+// chunk that did not change keeps its key, so its rung chunks are on disk and
+// only the changed chunks of each rung are encoded again. A rung whose keys
+// are all the ones its file was joined from last time is not joined again.
+//
+// The cache rule is one pure function -- rungChunkKey: chunk key + rung ->
+// key -- and one function that turns a key into a file (encodeChunkCached).
+// Neither knows a manifest, a take or the ladder; they are the `ladder`
+// module's cache rule when the video modules land.
+//
+// Is the master really made of those chunks? chunks.json says what the last
+// chunked build joined; the master may have been built some other way since
+// (a hard-cut take, REPORT_VIDEO_CHUNKED=0). masterFromChunks proves it by
+// CONTENT: the sha256 of the master's video packets is the sha256 of the
+// chunks' packets as the build's mux writes them (the concat demuxer's
+// h264_mp4toannexb, back through an mp4 muxer -- in-band parameter sets on
+// each IDR). A few seconds of reading, no decode.
+//
+// Plain node; every path is a parameter.
+
+import { execFile, spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+
+const execFileP = promisify(execFile);
+const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
+const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe";
+
+/** Bumped when what a rung chunk key covers changes: every rung chunk is encoded once more. */
+export const LADDER_KEY_VERSION = 1;
+/** The ladder's cache, under a build's out/ (beside variants.json). */
+export const LADDER_DIR = "ladder";
+/** Its encoded rung chunks and sounds: `rung-<key>.mp4`, `audio-<key>.m4a`. */
+export const LADDER_CHUNKS_DIR = "chunks";
+/** Its record: what each rung was last joined from. */
+export const LADDER_RECORD = "ladder.json";
+
+const sha256 = (s) => createHash("sha256").update(s).digest("hex");
+
+/** Is `name` a file of the ladder's chunk cache? */
+export const isLadderChunkFile = (name) => /^(rung|audio)-[0-9a-f]{24}\.(mp4|m4a)$/.test(name);
+
+/**
+ * A rung's encode, as the settings that make its pixels:
+ * `{ kind: "crf", height, srcHeight, crf, preset }` or
+ * `{ kind: "abr", height, srcHeight, videoKbps, preset }`.
+ * Only these go into a key; a name or a size cap does not.
+ */
+function rungParts(rung) {
+ const base = { kind: rung.kind, height: rung.height, scaled: rung.height < rung.srcHeight, preset: rung.preset ?? "medium" };
+ if (rung.kind === "crf") return { ...base, crf: rung.crf };
+ if (rung.kind === "abr") return { ...base, videoKbps: rung.videoKbps };
+ throw new Error(`ladder: no rung kind ${rung.kind}`);
+}
+
+/**
+ * THE CACHE RULE: a rung chunk's key from the master chunk's key (which
+ * already names its inputs by content and the encoder that made it), the
+ * rung's settings and the ffmpeg binary that encodes the rung. Pure.
+ */
+export function rungChunkKey({ chunkKey, rung, ffmpeg }) {
+ if (!chunkKey) throw new Error("ladder: a rung chunk key needs the master chunk's key");
+ return sha256(JSON.stringify({ v: LADDER_KEY_VERSION, chunk: chunkKey, rung: rungParts(rung), ffmpeg })).slice(0, 24);
+}
+
+/** A size-capped rung's sound's key: the master's sound (by its packets' hash) at a rate and a layout. Pure. */
+export function rungAudioKey({ audioHash, audio, ffmpeg }) {
+ return sha256(JSON.stringify({ v: LADDER_KEY_VERSION, audio: audioHash, kbps: audio.kbps, channels: audio.channels, ffmpeg })).slice(0, 24);
+}
+
+export const rungChunkFile = (dir, key) => path.join(dir, `rung-${key}.mp4`);
+export const rungAudioFile = (dir, key) => path.join(dir, `audio-${key}.m4a`);
+
+/** One rung chunk's argv: the master chunk re-encoded at the rung's height and settings, picture only. Pure. */
+export function rungChunkArgs({ input, out, rung }) {
+ const p = rungParts(rung);
+ return [
+ "-nostdin", "-v", "error", "-y", "-i", input,
+ "-map", "0:v:0",
+ ...(p.scaled ? ["-vf", `scale=-2:${rung.height}:flags=lanczos`] : []),
+ "-c:v", "libx264", "-preset", p.preset,
+ ...(p.kind === "crf" ? ["-crf", String(p.crf)] : ["-b:v", `${p.videoKbps}k`]),
+ "-pix_fmt", "yuv420p", "-an", out,
+ ];
+}
+
+/** A size-capped rung's sound: the master's, AAC at the plan's rate and layout. Pure. */
+export function rungAudioArgs({ source, out, audio }) {
+ return [
+ "-nostdin", "-v", "error", "-y", "-i", source, "-map", "0:a:0", "-vn",
+ "-c:a", "aac", "-b:a", `${audio.kbps}k`, "-ac", String(audio.channels), out,
+ ];
+}
+
+/**
+ * A rung joined: its chunks by the concat demuxer, the sound (the master's
+ * own, copied, or `audio`), the master's metadata and chapters, all `-c copy`. Pure.
+ */
+export function rungJoinArgs({ listFile, master, audio = null, out }) {
+ return [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "concat", "-safe", "0", "-i", listFile,
+ "-i", master,
+ ...(audio ? ["-i", audio] : []),
+ "-map", "0:v:0", "-map", audio ? "2:a:0" : "1:a?",
+ "-map_metadata", "1", "-map_chapters", "1",
+ "-c", "copy", "-movflags", "+faststart", out,
+ ];
+}
+
+/** A file's video frame count from its container (no decode); null when unreadable. */
+export async function containerFrames(file, ffprobe = FFPROBE()) {
+ const { stdout } = await execFileP(ffprobe, [
+ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=nb_frames", "-of", "csv=p=0", file,
+ ]).catch(() => ({ stdout: "" }));
+ const n = Number.parseInt(String(stdout).trim(), 10);
+ return Number.isFinite(n) ? n : null;
+}
+
+/**
+ * THE KEY -> FILE FUNCTION: the file for `key` in `dir`, encoded by
+ * `encode(tmp)` only when it is not there with `frames` frames. Written
+ * under a work name and renamed, so a half-made chunk is never taken for one.
+ *
+ * @param {{ dir: string, key: string, frames: number, encode: (tmp: string) => Promise<unknown>,
+ * countFrames?: (file: string) => Promise<number | null> }} job
+ * @returns {Promise<{ file: string, reused: boolean }>}
+ */
+export async function encodeChunkCached({ dir, key, frames, encode, countFrames = (f) => containerFrames(f) }) {
+ const file = rungChunkFile(dir, key);
+ if ((await stat(file).catch(() => null))?.isFile() && (await countFrames(file)) === frames) return { file, reused: true };
+ const tmp = path.join(dir, `.rung-${key}.${process.pid}.partial.mp4`);
+ await rm(tmp, { force: true });
+ await encode(tmp);
+ const got = await countFrames(tmp);
+ if (got !== frames) {
+ await rm(tmp, { force: true });
+ throw new Error(`ladder: rung chunk ${key} encoded ${got} frames, expected ${frames}`);
+ }
+ await rename(tmp, file);
+ return { file, reused: false };
+}
+
+/** Run `jobs` (async thunks) `width` at a time; the first failure thrown once they settle. */
+export async function runPool(jobs, width) {
+ let next = 0;
+ let failure = null;
+ const worker = async () => {
+ while (next < jobs.length && !failure) {
+ const k = next;
+ next += 1;
+ try {
+ await jobs[k]();
+ } catch (err) {
+ failure ??= err;
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, width), jobs.length) }, worker));
+ if (failure) throw failure;
+}
+
+/** How many rung chunks are encoded at once: REPORT_VIDEO_CHUNK_JOBS (the build's knob), else 2. */
+export function ladderJobs(env = process.env) {
+ const n = Number(env.REPORT_VIDEO_CHUNK_JOBS);
+ return Number.isInteger(n) && n >= 1 ? Math.min(n, 8) : 2;
+}
+
+// ---- is the master made of these chunks? ------------------------------------
+
+/** `ffmpeg … -f streamhash` lines -> `{ v, a }` (the first video and audio stream's sha256). */
+export function parseStreamHash(text) {
+ const out = { v: null, a: null };
+ for (const line of String(text).split("\n")) {
+ const m = /^\d+,([va]),SHA256=([0-9a-f]+)$/.exec(line.trim());
+ if (m && !out[m[1]]) out[m[1]] = m[2];
+ }
+ return out;
+}
+
+/** The sha256 of a file's video and audio packets. */
+export async function fileStreamHash(file, ffmpeg = FFMPEG()) {
+ const { stdout } = await execFileP(ffmpeg, [
+ "-nostdin", "-v", "error", "-i", file, "-map", "0:v:0", "-map", "0:a:0?", "-c", "copy", "-f", "streamhash", "-hash", "sha256", "-",
+ ], { maxBuffer: 1 << 20 });
+ return parseStreamHash(stdout);
+}
+
+/**
+ * The sha256 of the video packets the build's mux makes of `listFile`'s
+ * chunks: the concat demuxer into a fragmented mp4 on a pipe, read back.
+ */
+export function joinedStreamHash(listFile, ffmpeg = FFMPEG()) {
+ return new Promise((resolve, reject) => {
+ const a = spawn(ffmpeg, [
+ "-nostdin", "-v", "error", "-f", "concat", "-safe", "0", "-i", listFile,
+ "-map", "0:v:0", "-c", "copy", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "-",
+ ], { stdio: ["ignore", "pipe", "pipe"] });
+ const b = spawn(ffmpeg, ["-v", "error", "-i", "-", "-map", "0:v:0", "-c", "copy", "-f", "streamhash", "-hash", "sha256", "-"], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ a.stdout.pipe(b.stdin);
+ b.stdin.on("error", () => {});
+ let out = "";
+ let err = "";
+ b.stdout.on("data", (d) => { out += d; });
+ a.stderr.on("data", (d) => { err += d; });
+ b.stderr.on("data", (d) => { err += d; });
+ let codeA = null;
+ a.on("close", (c) => { codeA = c; });
+ a.on("error", reject);
+ b.on("error", reject);
+ b.on("close", (c) => {
+ if (c !== 0 || (codeA !== null && codeA !== 0)) reject(new Error(`ladder: hashing the joined chunks failed: ${err.trim()}`));
+ else resolve(parseStreamHash(out).v);
+ });
+ });
+}
+
+/** A concat demuxer list of absolute paths. */
+export function concatList(files) {
+ return files.map((f) => `file '${path.resolve(f).replace(/'/g, "'\\''")}'`).join("\n") + "\n";
+}
+
+/** A file's identity for a memo: what changes when it does (`dev:ino:size:mtime`). */
+export async function fileIdentity(file) {
+ const st = await stat(file).catch(() => null);
+ return st?.isFile() ? `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}` : null;
+}
+
+/**
+ * The chunks `master` is made of, when it is: `chunksDir`'s chunks.json,
+ * every chunk on disk, and the master's video packets those chunks' (by
+ * content, above). `memo` is the last answer for this master
+ * (`{ id, record, videoHash, audioHash }`): reused when the master and the
+ * record are the same files. `listFile`: where the chunks' concat list is
+ * written. `ok: false`, with `why`, when the ladder cannot use them.
+ *
+ * @returns {Promise<{ ok: true, chunks: Array<{ a: number, b: number, key: string, file: string }>, fps: number,
+ * frames: number, listFile: string, memo: { id: string, record: string, videoHash: string, audioHash: string | null } }
+ * | { ok: false, why: string }>}
+ */
+export async function masterFromChunks({ master, chunksDir, listFile, memo = null, recordName = "chunks.json", ffmpeg = FFMPEG() }) {
+ const text = await readFile(path.join(chunksDir, recordName), "utf8").catch(() => null);
+ if (!text) return { ok: false, why: "the master has no chunk record (not a chunked build)" };
+ let rec;
+ try {
+ rec = JSON.parse(text);
+ } catch {
+ return { ok: false, why: "the chunk record is not JSON" };
+ }
+ const chunks = Array.isArray(rec?.chunks) ? rec.chunks : [];
+ if (!chunks.length || !(rec.fps > 0)) return { ok: false, why: "the chunk record lists no chunks" };
+ for (const c of chunks) {
+ if (!(Number.isInteger(c.a) && Number.isInteger(c.b) && c.b > c.a && typeof c.key === "string" && typeof c.file === "string")) {
+ return { ok: false, why: "the chunk record is malformed" };
+ }
+ if (!(await stat(path.join(chunksDir, c.file)).catch(() => null))?.isFile()) return { ok: false, why: `chunk ${c.file} is gone` };
+ }
+ const id = await fileIdentity(master);
+ if (!id) return { ok: false, why: "no master file" };
+ const record = createHash("sha1").update(text).digest("hex");
+ // The list the hash is taken over: the record's, written fresh at `listFile`
+ // (the build's concat.txt is written in place and may be another cut's).
+ await writeFile(listFile, concatList(chunks.map((c) => path.join(chunksDir, c.file))), "utf8");
+ const ok = (m) => ({ ok: true, chunks, fps: rec.fps, frames: Number(rec.frames) || chunks[chunks.length - 1].b, listFile, memo: m });
+ if (memo && memo.id === id && memo.record === record && memo.videoHash) return ok(memo);
+ const [own, joined] = await Promise.all([fileStreamHash(master, ffmpeg), joinedStreamHash(listFile, ffmpeg)]);
+ if (!own.v || own.v !== joined) return { ok: false, why: "the master's picture is not these chunks (built another way since)" };
+ return ok({ id, record, videoHash: own.v, audioHash: own.a });
+}
diff --git a/umtool/report-to-video/ladder-chunks.test.mjs b/umtool/report-to-video/ladder-chunks.test.mjs
@@ -0,0 +1,144 @@
+// The variant ladder's cache rule (ladder-chunks.mjs): a rung chunk's key is
+// the master chunk's key, the rung's settings and ffmpeg -- nothing else; the
+// key -> file function encodes only what is not on disk; and a master is
+// recognised as made of its chunks by content, not by a record's say-so.
+//
+// Run with: node --test umtool/report-to-video/ladder-chunks.test.mjs
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ concatList, encodeChunkCached, isLadderChunkFile, masterFromChunks, parseStreamHash, rungAudioKey, rungChunkArgs, rungChunkKey, rungJoinArgs,
+} from "./ladder-chunks.mjs";
+import { CHUNKS_DIR } from "./chunked-encode.mjs";
+import { concatWithXfade, setProgressMode, xfadeConcatArgs } from "./build-video.mjs";
+import { scheduleFrom } from "./deck.mjs";
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+
+test("rungChunkKey: the master chunk, the rung's pixels and ffmpeg -- not a name, not a size cap", () => {
+ const rung = { kind: "crf", height: 720, srcHeight: 1080, crf: 23, preset: "medium" };
+ const k = rungChunkKey({ chunkKey: "abc", rung, ffmpeg: "ff1" });
+ assert.match(k, /^[0-9a-f]{24}$/);
+ assert.equal(rungChunkKey({ chunkKey: "abc", rung: { ...rung, name: "720p", maxMiB: 9 }, ffmpeg: "ff1" }), k);
+ assert.equal(rungChunkKey({ chunkKey: "abc", rung: { ...rung, preset: undefined }, ffmpeg: "ff1" }), k, "medium is the default preset");
+ for (const other of [
+ { chunkKey: "abd", rung, ffmpeg: "ff1" },
+ { chunkKey: "abc", rung: { ...rung, crf: 22 }, ffmpeg: "ff1" },
+ { chunkKey: "abc", rung: { ...rung, height: 480 }, ffmpeg: "ff1" },
+ { chunkKey: "abc", rung: { ...rung, preset: "slow" }, ffmpeg: "ff1" },
+ { chunkKey: "abc", rung, ffmpeg: "ff2" },
+ { chunkKey: "abc", rung: { kind: "abr", height: 720, srcHeight: 1080, videoKbps: 900 }, ffmpeg: "ff1" },
+ ]) assert.notEqual(rungChunkKey(other), k, JSON.stringify(other));
+ const abr = { kind: "abr", height: 480, srcHeight: 1080, videoKbps: 200 };
+ assert.notEqual(rungChunkKey({ chunkKey: "abc", rung: abr, ffmpeg: "f" }), rungChunkKey({ chunkKey: "abc", rung: { ...abr, videoKbps: 188 }, ffmpeg: "f" }));
+ assert.throws(() => rungChunkKey({ chunkKey: "", rung, ffmpeg: "f" }), /master chunk's key/);
+ assert.notEqual(rungAudioKey({ audioHash: "h", audio: { kbps: 48, channels: 1 }, ffmpeg: "f" }), rungAudioKey({ audioHash: "h", audio: { kbps: 96, channels: 2 }, ffmpeg: "f" }));
+});
+
+test("the argvs: scaled only below the source; crf or bitrate; the join copies, the master's sound unless given one", () => {
+ const crf = rungChunkArgs({ input: "in.mp4", out: "o.mp4", rung: { kind: "crf", height: 720, srcHeight: 1080, crf: 23 } });
+ assert.ok(crf.includes("scale=-2:720:flags=lanczos"));
+ assert.deepEqual(crf.slice(crf.indexOf("-crf"), crf.indexOf("-crf") + 2), ["-crf", "23"]);
+ assert.ok(crf.includes("-an") && crf.at(-1) === "o.mp4");
+ const abr = rungChunkArgs({ input: "in.mp4", out: "o.mp4", rung: { kind: "abr", height: 1080, srcHeight: 1080, videoKbps: 900, preset: "fast" } });
+ assert.ok(!abr.includes("-vf"));
+ assert.ok(abr.includes("900k") && abr.includes("fast") && !abr.includes("-crf"));
+ const join = rungJoinArgs({ listFile: "l.txt", master: "m.mp4", out: "x.mp4" });
+ assert.ok(join.includes("1:a?") && join.includes("copy") && join.includes("+faststart"));
+ assert.ok(rungJoinArgs({ listFile: "l.txt", master: "m.mp4", audio: "a.m4a", out: "x.mp4" }).includes("2:a:0"));
+ assert.equal(concatList(["/a/b c.mp4", "/a/it's.mp4"]), "file '/a/b c.mp4'\nfile '/a/it'\\''s.mp4'\n");
+ assert.ok(isLadderChunkFile("rung-FAKE-TEST-VALUE01234567.mp4") && isLadderChunkFile("audio-FAKE-TEST-VALUE01234567.m4a"));
+ assert.ok(!isLadderChunkFile("rung-0123.mp4") && !isLadderChunkFile(".rung-FAKE-TEST-VALUE01234567.1.partial.mp4"));
+ assert.deepEqual(parseStreamHash("0,v,SHA256=aa\n1,a,SHA256=bb\n"), { v: "aa", a: "bb" });
+});
+
+test("encodeChunkCached: encoded once, then found; a wrong frame count is never kept", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "ladder-cache-"));
+ try {
+ let calls = 0;
+ const encode = async (tmp) => {
+ calls += 1;
+ writeFileSync(tmp, "pixels");
+ };
+ const countFrames = async (f) => (existsSync(f) ? 12 : null);
+ const a = await encodeChunkCached({ dir, key: "k".repeat(24), frames: 12, encode, countFrames });
+ assert.equal(a.reused, false);
+ assert.equal(path.basename(a.file), `rung-${"k".repeat(24)}.mp4`);
+ const b = await encodeChunkCached({ dir, key: "k".repeat(24), frames: 12, encode, countFrames });
+ assert.equal(b.reused, true);
+ assert.equal(calls, 1);
+ await assert.rejects(encodeChunkCached({ dir, key: "j".repeat(24), frames: 13, encode, countFrames }), /encoded 12 frames, expected 13/);
+ assert.deepEqual(readdirSync(dir), [`rung-${"k".repeat(24)}.mp4`], "nothing half-made left");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+function run(argv) {
+ const r = spawnSync("ffmpeg", argv);
+ assert.equal(r.status, 0, String(r.stderr));
+}
+
+function segment(dir, i, frames, fps, name = `s${i}`, size = "128x72") {
+ const out = path.join(dir, `${name}.mp4`);
+ run([
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc2=s=${size}: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}`,
+ "-map", "0:v", "-map", "1:a", "-ac", "2",
+ "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", "-shortest",
+ out,
+ ]);
+ return out;
+}
+
+test("masterFromChunks: a chunked master is its chunks; one built another way since is not", { skip: !have && "needs ffmpeg" }, async () => {
+ const fps = 10;
+ const render = { width: 128, height: 72, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 };
+ const root = mkdtempSync(path.join(tmpdir(), "ladder-master-"));
+ const env = process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ process.env.REPORT_VIDEO_CHUNK_FRAMES = "24";
+ setProgressMode(() => {});
+ try {
+ const work = path.join(root, "sourced");
+ mkdirSync(work, { recursive: true });
+ const segments = [25, 40, 33].map((f, i) => segment(root, i, f, fps));
+ const master = path.join(root, "demo.mp4");
+ await concatWithXfade(segments, render, master, null, null, null, { workDir: work });
+ const chunksDir = path.join(work, CHUNKS_DIR);
+ const listFile = path.join(root, "list.txt");
+ const m = await masterFromChunks({ master, chunksDir, listFile });
+ assert.equal(m.ok, true, m.why);
+ assert.ok(m.chunks.length >= 3);
+ assert.equal(m.frames, Math.round(scheduleFrom([2.5, 4, 3.3], 0.5).total * fps));
+ assert.ok(m.memo.videoHash && m.memo.audioHash && m.memo.id);
+ // The memo answers for the same master and record without hashing.
+ const again = await masterFromChunks({ master, chunksDir, listFile, memo: { ...m.memo, videoHash: "memoised" } });
+ assert.equal(again.ok && again.memo.videoHash, "memoised");
+
+ // The same cut built in one pass (the record still on disk): not these chunks.
+ const durs = [2.5, 4, 3.3];
+ run(xfadeConcatArgs({ segments, durs, render: { ...render, crf: 30 }, outPath: path.join(root, "one.mp4"), chrome: null, joins: null }).slice(0));
+ rmSync(master);
+ writeFileSync(master, "");
+ run(["-v", "error", "-y", "-i", path.join(root, "one.mp4"), "-c", "copy", master]);
+ const other = await masterFromChunks({ master, chunksDir, listFile, memo: m.memo });
+ assert.equal(other.ok, false);
+ assert.match(other.why, /not these chunks/);
+ // A chunk gone; no record.
+ rmSync(path.join(chunksDir, m.chunks[1].file));
+ assert.match((await masterFromChunks({ master, chunksDir, listFile })).why, /is gone/);
+ rmSync(chunksDir, { recursive: true });
+ assert.match((await masterFromChunks({ master, chunksDir, listFile })).why, /no chunk record/);
+ } finally {
+ setProgressMode("human");
+ if (env === undefined) delete process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ else process.env.REPORT_VIDEO_CHUNK_FRAMES = env;
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -35,6 +35,7 @@
"./finale": "./finale.mjs",
"./frames-cut": "./frames-cut.mjs",
"./fx": "./fx.mjs",
+ "./ladder-chunks": "./ladder-chunks.mjs",
"./ledger-totals": "./ledger-totals.mjs",
"./montage": "./montage.mjs",
"./montage-styles": "./montage-styles.mjs",
diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs
@@ -22,11 +22,43 @@
// build renders again is counted on disk; the record only answers for one that
// is gone). verify-build reads a pruned sequence's count and key from there, so
// a verified cut stays verifiable.
+//
+// A TAKE THAT ASKED TO KEEP ITS FRAMES (`umtool take --keep-frames`) has
+// `<out>/.keep-frames/asked.json`. A later build of that out/ without
+// --keep-frames (a `--rebuild`, a re-run from the UI) still prunes chrome/,
+// but SETS ASIDE each sequence instead of removing it: renamed to
+// `<out>/.keep-frames/<name>-frames` (the default variant's; another
+// variant's under `.keep-frames/<variant>/`), where `umtool take --from`
+// (takeFrom.mjs) finds it. The record is written either way.
-import { lstat, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
export const PRUNED_RECORD = "pruned.json";
+/** Where an out/ keeps its set-aside chrome sequences: `<out>/.keep-frames/`. */
+export const KEEP_FRAMES_DIR = ".keep-frames";
+/** The marker that the out/'s take asked for its frames to be kept. */
+export const KEEP_FRAMES_ASKED = "asked.json";
+
+/** The directory a variant's sequences are set aside in. */
+export function keptFramesDir(outRoot, variant = "sourced") {
+ const base = path.join(outRoot, KEEP_FRAMES_DIR);
+ return variant === "sourced" ? base : path.join(base, variant);
+}
+
+/** Record that this out/'s frames are to be kept: `<out>/.keep-frames/asked.json`. */
+export async function markKeepFrames(outRoot, { now = () => new Date(), by = "take --keep-frames" } = {}) {
+ const dir = path.join(outRoot, KEEP_FRAMES_DIR);
+ await mkdir(dir, { recursive: true });
+ const tmp = path.join(dir, `.${KEEP_FRAMES_ASKED}.${process.pid}.tmp`);
+ await writeFile(tmp, `${JSON.stringify({ at: now().toISOString(), by }, null, 2)}\n`, "utf8");
+ await rename(tmp, path.join(dir, KEEP_FRAMES_ASKED));
+}
+
+/** Did this out/'s take ask for its frames to be kept? */
+export async function keepFramesAsked(outRoot) {
+ return (await lstat(path.join(outRoot, KEEP_FRAMES_DIR, KEEP_FRAMES_ASKED)).catch(() => null))?.isFile() === true;
+}
const FRAME_RE = /^frame_\d+\.png$/;
/** Is this `chrome/` entry one a prune removes? A real directory, named for it. */
@@ -55,10 +87,12 @@ async function readRecord(chromeDir) {
/**
* Remove `<variantDir>/chrome/<name>-frames` and `chrome/work-*`, recording each
* sequence's frame count and key first. Returns what went and how much.
+ * `setAside` (a directory): each sequence is renamed into it instead of
+ * removed (one there by the same name replaced); `work-*` still goes.
*
- * @returns {Promise<{ sequences: string[], work: string[], bytes: number }>}
+ * @returns {Promise<{ sequences: string[], work: string[], bytes: number, setAside?: string | null }>}
*/
-export async function pruneChromeFrames(variantDir, { now = () => new Date() } = {}) {
+export async function pruneChromeFrames(variantDir, { now = () => new Date(), setAside = null } = {}) {
const chromeDir = path.join(variantDir, "chrome");
const entries = (await readdir(chromeDir, { withFileTypes: true }).catch(() => [])).filter(isPrunable);
const sequences = entries.filter((e) => e.name.endsWith("-frames")).map((e) => e.name).sort();
@@ -78,10 +112,18 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date() } =
const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`);
await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8");
await rename(tmp, path.join(chromeDir, PRUNED_RECORD));
- for (const name of [...sequences, ...work]) {
+ if (setAside && sequences.length) {
+ await mkdir(setAside, { recursive: true });
+ for (const name of sequences) {
+ const to = path.join(setAside, name);
+ await rm(to, { recursive: true, force: true });
+ await rename(path.join(chromeDir, name), to);
+ }
+ }
+ for (const name of [...(setAside ? [] : sequences), ...work]) {
await rm(path.join(chromeDir, name), { recursive: true, force: true });
}
- return { sequences, work, bytes };
+ return { sequences, work, bytes, setAside: setAside && sequences.length ? setAside : null };
}
/**
diff --git a/umtool/report-to-video/prune-frames.test.mjs b/umtool/report-to-video/prune-frames.test.mjs
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
-import { PRUNED_RECORD, frameKeyOf, framesOf, pruneChromeFrames } from "./prune-frames.mjs";
+import { KEEP_FRAMES_DIR, PRUNED_RECORD, frameKeyOf, framesOf, keepFramesAsked, keptFramesDir, markKeepFrames, pruneChromeFrames } from "./prune-frames.mjs";
import { verifyBuild, verifyTeasers } from "./verify-build.mjs";
import { buildVideo, setProgressMode } from "./build-video.mjs";
import { frameCount, teaserSeconds } from "./deck.mjs";
@@ -83,6 +83,35 @@ test("pruneChromeFrames removes chrome/*-frames and chrome/work-* only, and reco
}
});
+test("pruneChromeFrames setAside: the sequences renamed into it (one there replaced), work dirs removed, recorded the same", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "rtv-aside-"));
+ try {
+ const outRoot = path.join(root, "out");
+ const v = path.join(outRoot, "sourced");
+ const chrome = path.join(v, "chrome");
+ frames(path.join(chrome, "deck-frames"), 4, "deck-new");
+ mkdirSync(path.join(chrome, "work-1"), { recursive: true });
+ assert.equal(await keepFramesAsked(outRoot), false);
+ await markKeepFrames(outRoot, { now: () => new Date("2026-10-28T00:00:00Z") });
+ assert.equal(await keepFramesAsked(outRoot), true);
+ assert.equal(JSON.parse(readFileSync(path.join(outRoot, KEEP_FRAMES_DIR, "asked.json"), "utf8")).at, "2026-10-28T00:00:00.000Z");
+ const aside = keptFramesDir(outRoot, "sourced");
+ assert.equal(aside, path.join(outRoot, KEEP_FRAMES_DIR));
+ assert.equal(keptFramesDir(outRoot, "full"), path.join(outRoot, KEEP_FRAMES_DIR, "full"));
+ frames(path.join(aside, "deck-frames"), 9, "deck-old");
+ const r = await pruneChromeFrames(v, { setAside: aside });
+ assert.deepEqual(r.sequences, ["deck-frames"]);
+ assert.equal(r.setAside, aside);
+ assert.ok(!existsSync(path.join(chrome, "deck-frames")) && !existsSync(path.join(chrome, "work-1")));
+ assert.equal(readFileSync(path.join(aside, "deck-frames", ".key"), "utf8"), "deck-new\n");
+ assert.equal(readdirSync(path.join(aside, "deck-frames")).length, 5, "the older one replaced, not merged");
+ assert.deepEqual(JSON.parse(readFileSync(path.join(chrome, PRUNED_RECORD), "utf8")).dirs, { "deck-frames": { frames: 4, key: "deck-new" } });
+ assert.ok(existsSync(path.join(outRoot, KEEP_FRAMES_DIR, "asked.json")), "the marker stays");
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
test("framesOf / frameKeyOf: on disk first; a pruned sequence from the record -- unless the cut is newer than the prune", async () => {
const root = mkdtempSync(path.join(tmpdir(), "rtv-prune-read-"));
try {
@@ -195,6 +224,17 @@ for (let i = 1; i <= Math.round(dur * fps); i += 1) copyFileSync(one, out + "/fr
assert.equal(rec.dirs["teaser-t1-frames"].frames, want);
// The segment is the one the first build made (its record matched).
assert.equal(statSync(path.join(v, "segments", "t1.mp4")).ino, seg.ino);
+
+ // A take that asked to keep its frames: the next build sets them aside.
+ await markKeepFrames(path.join(root, "out"));
+ rmSync(path.join(v, "segments", "t1.mp4"));
+ events.length = 0;
+ await buildVideo({ manifestPath, opts: {} });
+ assert.equal(existsSync(framesDir), false);
+ const aside = path.join(root, "out", KEEP_FRAMES_DIR, "teaser-t1-frames");
+ assert.equal(readdirSync(aside).filter((f) => /^frame_\d+\.png$/.test(f)).length, want);
+ assert.ok(events.some((e) => e.ev === "note" && /^set aside 1 frame sequence\(s\) in \.keep-frames\/ \(this take asked to keep its frames\)/.test(e.message)),
+ events.filter((e) => e.ev === "note").map((e) => e.message).join("\n"));
} finally {
setProgressMode("human");
}
diff --git a/umtool/report-to-video/variants.mjs b/umtool/report-to-video/variants.mjs
@@ -13,23 +13,46 @@
// says what was made: `{ at, source, items: [{ name, path, width, height,
// bytes, kbps }] }`.
//
-// A `maxMiB` variant is two-pass x264 at the largest of 1080/720/480 (no
-// larger than the cut) whose picture keeps at least 100 kb/s per 480p's worth
-// of pixels; its sound AAC 48 kb/s mono when the whole is under 300 kb/s,
-// else 96 kb/s stereo; and it is encoded again 6 % lower while it lands over
-// (x264 overshoots: 24.3 MiB at a 23.1 target, measured).
+// A `maxMiB` variant is x264 at the largest of 1080/720/480 (no larger than
+// the cut) whose picture keeps at least 100 kb/s per 480p's worth of pixels;
+// its sound AAC 48 kb/s mono when the whole is under 300 kb/s, else 96 kb/s
+// stereo; and it is encoded again 6 % lower while it lands over (x264
+// overshoots: 24.3 MiB at a 23.1 target, measured).
//
-// node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file]
+// FROM THE MASTER'S CHUNKS (ladder-chunks.mjs): when the cut is a chunked
+// build whose chunks are still on disk (out/sourced/chunks/, proved to be the
+// master's picture by content), each rung is encoded chunk by chunk -- a rung
+// chunk keyed by the master chunk's key, the rung's settings and ffmpeg, kept
+// in out/ladder/chunks/ -- and joined with `-c copy`; a master chunk that did
+// not change costs nothing on any rung, and a rung whose chunks are all the
+// ones its file was joined from is not touched. A size-capped rung is then
+// per-chunk ABR at the plan's bitrate (one pass; lowered by what it overshot
+// while it lands over), its sound encoded once and cached, and the scale that
+// last landed under the cap is kept in
+// out/ladder/ladder.json, so the next run starts there (same keys: nothing
+// encoded). Otherwise -- no chunks, or a master built another way -- each
+// rung is encoded from the whole cut as before (a size-capped one two-pass).
+//
+// A crf rung at the master's own height IS the master: hard-linked, never
+// re-encoded (a re-encode at the same size only loses picture).
+//
+// node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] [--whole]
//
// The CLI takes the machine's heavy slot (heavy-gate.mjs), declaring the
// ladder's memory estimate (render-estimate.mjs); encodeVariants itself does
// not -- umtool's job runner holds it for the UI.
import { execFile } from "node:child_process";
-import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import { copyFile, link, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { renderEstimateMb } from "./render-estimate.mjs";
+import { CHUNKS_DIR } from "./chunked-encode.mjs";
+import {
+ LADDER_CHUNKS_DIR, LADDER_DIR, LADDER_RECORD, concatList, containerFrames, encodeChunkCached, fileIdentity, isLadderChunkFile,
+ ladderJobs, masterFromChunks, rungAudioArgs, rungAudioFile, rungAudioKey, rungChunkArgs, rungChunkFile, rungChunkKey, rungJoinArgs, runPool,
+} from "./ladder-chunks.mjs";
+import { ffmpegIdentity } from "./segment-cache.mjs";
const execFileP = promisify(execFile);
const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
@@ -161,24 +184,176 @@ export function fitArgs({ source, out, plan, srcHeight, pass, logBase, preset =
];
}
-const itemOf = (name, file, p) => ({
+const itemOf = (name, file, p, encode = null) => ({
name, path: file, width: p.width, height: p.height, bytes: p.bytes,
kbps: Number.isFinite(p.duration) && p.duration > 0 ? Math.round((p.bytes * 8) / p.duration / 1000) : null,
+ ...(encode ? { encode } : {}),
});
+/** The variant the build's own chunks are in: the default variant's (build-video's DEFAULT_VARIANT). */
+const MASTER_VARIANT = "sourced";
+
+/** `file` at `dst` as a hard link (through a rename), a copy across filesystems. */
+async function linkInto(file, dst) {
+ const [a, b] = await Promise.all([lstat(file), lstat(dst).catch(() => null)]);
+ if (b && a.ino === b.ino && a.dev === b.dev) return;
+ const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.link`);
+ await rm(tmp, { force: true });
+ try {
+ await link(file, tmp);
+ } catch (err) {
+ if (/** @type {any} */ (err)?.code !== "EXDEV") throw err;
+ await copyFile(file, tmp);
+ }
+ await rename(tmp, dst);
+}
+
+const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+const sameList = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => x === b[i]);
+
+/**
+ * The ladder over the master's chunks (see the top of the file), or null when
+ * the master is not a chunked build whose chunks are on disk.
+ */
+async function openLadder({ outDir, src, work, slug, onLog }) {
+ const dir = path.join(outDir, LADDER_DIR);
+ const cdir = path.join(dir, LADDER_CHUNKS_DIR);
+ const recFile = path.join(dir, LADDER_RECORD);
+ await mkdir(cdir, { recursive: true });
+ const prev = await readJson(recFile);
+ const rec = prev?.version === 1 && isObj(prev.rungs) ? prev : { version: 1, master: null, rungs: {} };
+ const chunksDir = path.join(outDir, MASTER_VARIANT, CHUNKS_DIR);
+ const m = await masterFromChunks({ master: src, chunksDir, listFile: path.join(work, "master-concat.txt"), memo: rec.master });
+ if (!m.ok) {
+ onLog(`variants: each rung from the whole cut — ${m.why}`);
+ return null;
+ }
+ rec.master = m.memo;
+ const ffmpeg = await ffmpegIdentity(FFMPEG());
+ onLog(`variants: from the master's ${m.chunks.length} chunk(s) (${MASTER_VARIANT}/${CHUNKS_DIR}/)`);
+
+ /**
+ * One rung over the chunks: each rung chunk on disk or encoded, the sound,
+ * joined into a work file -- or nothing at all when the rung's file was
+ * joined from exactly these (`skipped`).
+ */
+ const run = async ({ name, rung, out, audio = null }) => {
+ const t0 = Date.now();
+ const unique = new Map();
+ const keys = m.chunks.map((c) => {
+ const key = rungChunkKey({ chunkKey: c.key, rung, ffmpeg });
+ if (!unique.has(key)) unique.set(key, { key, input: path.join(chunksDir, c.file), frames: c.b - c.a });
+ return key;
+ });
+ const audioKey = audio && m.memo.audioHash ? rungAudioKey({ audioHash: m.memo.audioHash, audio, ffmpeg }) : null;
+ const was = rec.rungs[name];
+ const outId = await fileIdentity(out);
+ if (was && outId && was.file === outId && was.master === m.memo.id && sameList(was.keys, keys) && was.audio === (audioKey ?? "copy")) {
+ return { skipped: true, keys, audioKey, chunks: unique.size, encoded: 0, reused: unique.size, seconds: 0 };
+ }
+ let encoded = 0;
+ const jobs = [...unique.values()].map((j) => async () => {
+ const r = await encodeChunkCached({
+ dir: cdir, key: j.key, frames: j.frames,
+ encode: (tmp) => execFileP(FFMPEG(), rungChunkArgs({ input: j.input, out: tmp, rung }), { maxBuffer: 1 << 26 }),
+ });
+ if (!r.reused) encoded += 1;
+ });
+ let audioFile = null;
+ if (audioKey) {
+ audioFile = rungAudioFile(cdir, audioKey);
+ const file = audioFile;
+ jobs.unshift(async () => {
+ if ((await stat(file).catch(() => null))?.isFile()) return;
+ const tmp = path.join(cdir, `.${path.basename(file)}.${process.pid}.partial.m4a`);
+ await execFileP(FFMPEG(), rungAudioArgs({ source: src, out: tmp, audio }), { maxBuffer: 1 << 26 });
+ await rename(tmp, file);
+ });
+ }
+ onLog(`variant ${name}: ${unique.size} rung chunk(s) of ${keys.length}, ${ladderJobs()} at a time…`);
+ await runPool(jobs, ladderJobs());
+ const listFile = path.join(work, `${slug}.${name}.concat.txt`);
+ await writeFile(listFile, concatList(keys.map((k) => rungChunkFile(cdir, k))), "utf8");
+ const tmp = path.join(work, `${slug}.${name}.partial.mp4`);
+ await execFileP(FFMPEG(), rungJoinArgs({ listFile, master: src, audio: audioFile, out: tmp }), { maxBuffer: 1 << 26 });
+ const got = await containerFrames(tmp);
+ if (got !== m.frames) throw new Error(`variant ${name}: the joined rung holds ${got} frames; the cut is ${m.frames}`);
+ return { skipped: false, tmp, keys, audioKey, chunks: unique.size, encoded, reused: unique.size - encoded, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)) };
+ };
+
+ /** What a rung's file was joined from, once it is in place. */
+ const remember = async (name, out, r, extra = {}) => {
+ rec.rungs[name] = { keys: r.keys, audio: r.audioKey ?? "copy", master: m.memo.id, file: await fileIdentity(out), ...extra };
+ };
+
+ /** The record written; rung chunks no rung of `ladder` names, gone. */
+ const save = async (ladder) => {
+ for (const n of Object.keys(rec.rungs)) if (!ladder.some((v) => v.name === n)) delete rec.rungs[n];
+ const keep = new Set();
+ for (const r of Object.values(rec.rungs)) {
+ for (const k of r.keys ?? []) keep.add(path.basename(rungChunkFile(cdir, k)));
+ if (r.audio && r.audio !== "copy") keep.add(path.basename(rungAudioFile(cdir, r.audio)));
+ }
+ for (const f of await readdir(cdir).catch(() => [])) {
+ if ((isLadderChunkFile(f) && !keep.has(f)) || /\.partial\.(mp4|m4a)$/.test(f)) await rm(path.join(cdir, f), { force: true });
+ }
+ const tmp = path.join(dir, `.${LADDER_RECORD}.${process.pid}.tmp`);
+ await writeFile(tmp, JSON.stringify(rec, null, 2) + "\n", "utf8");
+ await rename(tmp, recFile);
+ };
+
+ return { run, remember, save, rec };
+}
+
+/**
+ * Seed `toOut`'s ladder record with `fromOut`'s size-capped rungs' last good
+ * scales (`take --from`, takeFrom.mjs): a rung this out/ has no scale for
+ * starts where the other take's landed, so the chunks the two cuts share key
+ * alike and are not encoded again. Never overwrites a scale of this out/'s
+ * own. Returns the rung names seeded.
+ *
+ * @param {string} fromOut
+ * @param {string} toOut
+ * @returns {Promise<string[]>}
+ */
+export async function seedLadderFit(fromOut, toOut) {
+ const theirs = await readJson(path.join(fromOut, LADDER_DIR, LADDER_RECORD));
+ if (theirs?.version !== 1 || !isObj(theirs.rungs)) return [];
+ const file = path.join(toOut, LADDER_DIR, LADDER_RECORD);
+ const own = await readJson(file);
+ const rec = own?.version === 1 && isObj(own.rungs) ? own : { version: 1, master: null, rungs: {} };
+ const seeded = [];
+ for (const [name, r] of Object.entries(theirs.rungs)) {
+ const fit = isObj(r) ? r.fit : null;
+ if (!isObj(fit) || !isObj(fit.basis) || !(fit.scale > 0 && fit.scale <= 1)) continue;
+ if (isObj(rec.rungs[name]?.fit)) continue;
+ rec.rungs[name] = { ...(isObj(rec.rungs[name]) ? rec.rungs[name] : { keys: [], audio: null, master: null, file: null }), fit: { basis: fit.basis, scale: fit.scale } };
+ seeded.push(name);
+ }
+ if (!seeded.length) return [];
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = path.join(path.dirname(file), `.${LADDER_RECORD}.${process.pid}.seed`);
+ await writeFile(tmp, JSON.stringify(rec, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+ return seeded;
+}
+
+const encodeOf = (r) => ({ from: "chunks", chunks: r.chunks, encoded: r.encoded, reused: r.reused, seconds: r.seconds, ...(r.skipped ? { unchanged: true } : {}) });
+
/**
* Make the variants of `<outDir>/<slug>.mp4` (or `source`). `variants` is the
* ladder (validated here); `only` names the ones to make now -- the others'
* rows in variants.json are kept. Each is written under a temporary name and
- * renamed, so a half-made file is never taken for one.
+ * renamed, so a half-made file is never taken for one. `chunked: false`
+ * encodes every rung from the whole cut even when the master's chunks are there.
*
* @param {string} outDir
* @param {{ slug: string, variants?: object[], only?: string[] | null, source?: string | null,
- * onLog?: (line: string) => void }} opts
+ * onLog?: (line: string) => void, chunked?: boolean }} opts
* @returns {Promise<{ at: string, source: string, items: Array<{ name: string, path: string,
- * width: number, height: number, bytes: number, kbps: number | null }> }>}
+ * width: number, height: number, bytes: number, kbps: number | null, encode?: Record<string, unknown> }> }>}
*/
-export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS, only = null, source = null, onLog = () => {} } = {}) {
+export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS, only = null, source = null, onLog = () => {}, chunked = true } = {}) {
const errors = validateVariants(variants);
if (errors.length) throw new Error(errors.join("; "));
if (!slug) throw new Error("variants: no slug");
@@ -193,7 +368,10 @@ export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS
const made = [];
const work = path.join(outDir, ".variants");
await mkdir(work, { recursive: true });
+ const needsEncode = todo.some((v) => v.name !== "master" && !(v.maxMiB === undefined && Math.min(v.height ?? sp.height, sp.height) === sp.height));
+ let ladder = null;
try {
+ if (chunked && needsEncode) ladder = await openLadder({ outDir, src, work, slug, onLog });
for (const v of todo) {
if (v.name === "master") {
made.push(itemOf("master", src, sp));
@@ -202,10 +380,67 @@ export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS
}
const out = path.join(outDir, `${slug}.${v.name}.mp4`);
const tmp = path.join(work, `${slug}.${v.name}.partial.mp4`);
+ let encode = { from: "whole" };
+ const t0 = Date.now();
if (v.maxMiB === undefined) {
const height = Math.min(v.height ?? sp.height, sp.height);
- onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}…`);
- await execFileP(FFMPEG(), crfArgs({ source: src, out: tmp, height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset }), { maxBuffer: 1 << 26 });
+ if (height === sp.height) {
+ // The master's own height: the master itself.
+ await linkInto(src, out);
+ const p = await probeOut(out);
+ made.push(itemOf(v.name, out, p, { from: "master", linked: true }));
+ onLog(`variant ${v.name}: ${height}p is the master's height — ${path.basename(out)} is the master (linked, not re-encoded)`);
+ continue;
+ }
+ if (ladder) {
+ const rung = { kind: "crf", height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset };
+ onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}, by chunk…`);
+ const r = await ladder.run({ name: v.name, rung, out });
+ if (!r.skipped) await rename(r.tmp, out);
+ await ladder.remember(v.name, out, r);
+ encode = encodeOf(r);
+ } else {
+ onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}…`);
+ await execFileP(FFMPEG(), crfArgs({ source: src, out: tmp, height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset }), { maxBuffer: 1 << 26 });
+ await rename(tmp, out);
+ }
+ } else if (ladder) {
+ const limit = v.maxMiB * 2 ** 20;
+ const basis = { maxMiB: v.maxMiB, seconds: sp.duration, srcHeight: sp.height, maxHeight: v.height ?? null };
+ const was = ladder.rec.rungs[v.name]?.fit;
+ // Where the last run landed under the cap: the same keys, nothing encoded.
+ let scale = was && JSON.stringify(was.basis) === JSON.stringify(basis) && was.scale > 0 && was.scale <= 1 ? was.scale : 1;
+ const sums = { chunks: 0, encoded: 0, reused: 0, seconds: 0, tries: 0 };
+ for (let tries = 0; ; tries += 1) {
+ const plan = fitPlan({ ...basis, scale });
+ const rung = { kind: "abr", height: plan.height, srcHeight: sp.height, videoKbps: plan.videoKbps, preset: v.preset };
+ onLog(`variant ${v.name}: ${plan.height}p, ${plan.videoKbps} kb/s picture + ${plan.audio.kbps} kb/s ${plan.audio.channels === 1 ? "mono" : "stereo"}, by chunk (scale ${Number(scale.toFixed(4))})…`);
+ const r = await ladder.run({ name: v.name, rung, out, audio: plan.audio });
+ sums.tries = tries + 1;
+ sums.chunks = r.chunks;
+ sums.encoded += r.encoded;
+ sums.reused = r.reused;
+ sums.seconds += r.seconds;
+ if (r.skipped) {
+ encode = { ...encodeOf(r), scale };
+ break;
+ }
+ const got = (await stat(r.tmp)).size;
+ const last = tries >= 3;
+ if (got <= limit || last) {
+ if (got > limit) onLog(`variant ${v.name}: still ${(got / 2 ** 20).toFixed(2)} MiB over ${v.maxMiB} after ${tries + 1} tries — kept`);
+ await rename(r.tmp, out);
+ await ladder.remember(v.name, out, r, { fit: { basis, scale } });
+ encode = { from: "chunks", ...sums, seconds: Number(sums.seconds.toFixed(1)), scale };
+ break;
+ }
+ await rm(r.tmp, { force: true });
+ // One-pass ABR over short chunks overshoots more than two passes over
+ // the whole: lower by what it overshot (3 % more), at least the step.
+ const next = scale * Math.min(1 - FIT_RETRY_STEP, (limit / got) * 0.97);
+ onLog(`variant ${v.name}: ${(got / 2 ** 20).toFixed(2)} MiB is over ${v.maxMiB} — again ${Math.round((1 - next / scale) * 100)} % lower`);
+ scale = next;
+ }
} else {
const limit = v.maxMiB * 2 ** 20;
let scale = 1;
@@ -225,12 +460,19 @@ export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS
scale *= 1 - FIT_RETRY_STEP;
onLog(`variant ${v.name}: ${(got / 2 ** 20).toFixed(2)} MiB is over ${v.maxMiB} — again ${Math.round(FIT_RETRY_STEP * 100)} % lower`);
}
+ await rename(tmp, out);
}
- await rename(tmp, out);
+ if (encode.from === "whole") encode = { from: "whole", seconds: Number(((Date.now() - t0) / 1000).toFixed(1)) };
const p = await probeOut(out);
- made.push(itemOf(v.name, out, p));
- onLog(`variant ${v.name}: ${path.basename(out)} ${p.width}x${p.height}, ${(p.bytes / 2 ** 20).toFixed(2)} MiB`);
+ made.push(itemOf(v.name, out, p, encode));
+ const how = encode.from === "chunks"
+ ? encode.unchanged
+ ? " — unchanged (every rung chunk the one it was joined from), not touched"
+ : ` — ${encode.encoded} rung chunk(s) encoded, ${encode.reused} reused, in ${encode.seconds}s`
+ : "";
+ onLog(`variant ${v.name}: ${path.basename(out)} ${p.width}x${p.height}, ${(p.bytes / 2 ** 20).toFixed(2)} MiB${how}`);
}
+ if (ladder) await ladder.save(variants);
} finally {
await rm(work, { recursive: true, force: true });
}
@@ -254,19 +496,20 @@ export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS
// ---- the CLI ---------------------------------------------------------------
-/** argv after the script: `<take out dir> [--slug s] [--only a,b] [--source file]`. */
+/** argv after the script: `<take out dir> [--slug s] [--only a,b] [--source file] [--whole]` (--whole: never from the chunks). */
export function parseVariantArgs(argv) {
- const out = { outDir: null, slug: null, only: null, source: null };
+ const out = { outDir: null, slug: null, only: null, source: null, chunked: true };
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
if (a === "--slug") out.slug = argv[++i] ?? null;
else if (a === "--only") out.only = String(argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
else if (a === "--source") out.source = argv[++i] ?? null;
+ else if (a === "--whole") out.chunked = false;
else if (a.startsWith("--")) throw new Error(`variants: unknown option ${a}`);
else if (!out.outDir) out.outDir = a;
else throw new Error(`variants: one take out dir, got ${a} too`);
}
- if (!out.outDir) throw new Error("usage: variants.mjs <take out dir> [--slug s] [--only name,…] [--source file]");
+ if (!out.outDir) throw new Error("usage: variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] [--whole]");
return out;
}
@@ -284,7 +527,7 @@ async function main() {
if (!slug) throw new Error(`variants: no --slug and no video.manifest.json beside ${outDir}`);
const variants = variantsOf(manifest?.render);
const run = () => encodeVariants(outDir, {
- slug, variants, only: args.only, source: args.source ? path.resolve(args.source) : null,
+ slug, variants, only: args.only, source: args.source ? path.resolve(args.source) : null, chunked: args.chunked,
onLog: (line) => process.stderr.write(`${line}\n`),
});
// By a URL made from the script's own path at run time, as build-video's
diff --git a/umtool/report-to-video/variants.test.mjs b/umtool/report-to-video/variants.test.mjs
@@ -5,15 +5,19 @@
// Run with: pnpm test:scripts
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
-import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
- DEFAULT_VARIANTS, encodeVariants, fitPlan, parseVariantArgs, validateVariants, VARIANTS_FILE, variantsOf,
+ DEFAULT_VARIANTS, encodeVariants, fitPlan, parseVariantArgs, seedLadderFit, validateVariants, VARIANTS_FILE, variantsOf,
} from "./variants.mjs";
+import { CHUNKS_DIR, CHUNKS_RECORD } from "./chunked-encode.mjs";
+import { LADDER_CHUNKS_DIR, LADDER_DIR, LADDER_RECORD } from "./ladder-chunks.mjs";
+import { concatWithXfade, setProgressMode } from "./build-video.mjs";
const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
@@ -58,7 +62,8 @@ test("fitPlan: the Huck cut at 24 MiB is 480p with mono sound; a short cut gets
});
test("parseVariantArgs", () => {
- assert.deepEqual(parseVariantArgs(["out", "--slug", "s", "--only", "720p, fit24"]), { outDir: "out", slug: "s", only: ["720p", "fit24"], source: null });
+ assert.deepEqual(parseVariantArgs(["out", "--slug", "s", "--only", "720p, fit24"]), { outDir: "out", slug: "s", only: ["720p", "fit24"], source: null, chunked: true });
+ assert.equal(parseVariantArgs(["out", "--whole"]).chunked, false);
assert.throws(() => parseVariantArgs([]), /usage/);
assert.throws(() => parseVariantArgs(["a", "--wat"]), /unknown option --wat/);
});
@@ -132,3 +137,140 @@ test("the CLI: the take's manifest names the slug and the ladder", { skip: !have
rmSync(take, { recursive: true, force: true });
}
});
+
+// ---- the ladder from the master's chunks (ladder-chunks.mjs) -----------------
+
+function run(argv) {
+ const r = spawnSync("ffmpeg", argv);
+ assert.equal(r.status, 0, String(r.stderr));
+ return r;
+}
+
+function segment(dir, i, frames, fps, name = `s${i}`) {
+ const out = path.join(dir, `${name}.mp4`);
+ run([
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc2=s=320x180: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}`,
+ "-map", "0:v", "-map", "1:a", "-ac", "2",
+ "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", "-shortest",
+ out,
+ ]);
+ return out;
+}
+
+const md5 = (file) => createHash("md5").update(readFileSync(file)).digest("hex");
+const frameMd5 = (file, vf = null) => String(spawnSync("ffmpeg", ["-v", "error", "-i", file, ...(vf ? ["-vf", vf] : []), "-map", "0:v", "-f", "framemd5", "-"]).stdout)
+ .split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split(",").at(-1).trim());
+const nbFrames = (file) => Number(String(spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).stdout).trim());
+
+test("the ladder from the master's chunks: each rung chunk encoded once; a second run touches nothing; a changed segment re-encodes only its chunks", { skip: !have && "needs ffmpeg" }, async () => {
+ const fps = 10;
+ const render = { width: 320, height: 180, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 };
+ const out = mkdtempSync(path.join(tmpdir(), "variants-chunks-"));
+ const env = process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ process.env.REPORT_VIDEO_CHUNK_FRAMES = "24";
+ setProgressMode(() => {});
+ try {
+ const work = path.join(out, "sourced");
+ const segDir = path.join(out, "segs");
+ mkdirSync(work, { recursive: true });
+ mkdirSync(segDir, { recursive: true });
+ const segments = [25, 40, 33, 30].map((f, i) => segment(segDir, i, f, fps));
+ const master = path.join(out, "demo.mp4");
+ await concatWithXfade(segments, render, master, null, null, null, { workDir: work });
+ const N = nbFrames(master);
+ const chunkCount = JSON.parse(readFileSync(path.join(work, CHUNKS_DIR, CHUNKS_RECORD), "utf8")).chunks.length;
+ assert.ok(chunkCount >= 4, `${chunkCount} chunks`);
+
+ const variants = [
+ { name: "master" },
+ { name: "same", height: 180, crf: 22 },
+ // Lossless, so the rung is exactly the master scaled, frame for frame.
+ { name: "half", height: 144, crf: 0, preset: "ultrafast" },
+ { name: "fit", maxMiB: 0.35, preset: "ultrafast" },
+ ];
+ const logs = [];
+ const doc1 = await encodeVariants(out, { slug: "demo", variants, onLog: (l) => logs.push(l) });
+ const by = (doc) => Object.fromEntries(doc.items.map((i) => [i.name, i]));
+ const r1 = by(doc1);
+ // At the master's height: the master, linked.
+ assert.equal(statSync(path.join(out, "demo.same.mp4")).ino, statSync(master).ino);
+ assert.deepEqual(r1.same.encode, { from: "master", linked: true });
+ assert.equal(r1.half.encode.from, "chunks");
+ assert.equal(r1.half.encode.encoded, r1.half.encode.chunks);
+ assert.equal(r1.half.height, 144);
+ assert.equal(nbFrames(r1.half.path), N);
+ assert.deepEqual(frameMd5(r1.half.path), frameMd5(master, "scale=-2:144:flags=lanczos"), "the rung is the master at its height, frame for frame");
+ assert.ok(r1.fit.bytes <= 0.35 * 2 ** 20, `${r1.fit.bytes} bytes`);
+ assert.equal(nbFrames(r1.fit.path), N);
+ const ch = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels", "-of", "csv=p=0", r1.fit.path]);
+ assert.equal(String(ch.stdout).trim(), "1", "a size-capped rung's sound is its own");
+ const rec1 = JSON.parse(readFileSync(path.join(out, LADDER_DIR, LADDER_RECORD), "utf8"));
+ assert.ok(rec1.rungs.fit.fit.scale > 0 && rec1.rungs.fit.fit.scale <= 1);
+ assert.ok(!rec1.rungs.same, "a linked rung has no chunks");
+ const sums = { half: md5(r1.half.path), fit: md5(r1.fit.path) };
+ const ids = { half: statSync(r1.half.path).mtimeMs, fit: statSync(r1.fit.path).mtimeMs };
+
+ // Again: nothing encoded, nothing joined, the same bytes.
+ const doc2 = await encodeVariants(out, { slug: "demo", variants });
+ const r2 = by(doc2);
+ for (const n of ["half", "fit"]) {
+ assert.equal(r2[n].encode.unchanged, true, n);
+ assert.equal(r2[n].encode.encoded, 0, n);
+ assert.equal(md5(r2[n].path), sums[n], n);
+ assert.equal(statSync(r2[n].path).mtimeMs, ids[n], `${n} not touched`);
+ }
+ assert.equal(r2.fit.encode.scale, rec1.rungs.fit.fit.scale, "the fit starts where it last landed");
+
+ // A twin out/ (what `take --from` makes): the master's chunks and the
+ // ladder's linked, the fit's scale seeded -- its first ladder run encodes nothing.
+ const twin = path.join(out, "twin");
+ mkdirSync(path.join(twin, "sourced", CHUNKS_DIR), { recursive: true });
+ mkdirSync(path.join(twin, LADDER_DIR, LADDER_CHUNKS_DIR), { recursive: true });
+ for (const f of readdirSync(path.join(work, CHUNKS_DIR))) linkSync(path.join(work, CHUNKS_DIR, f), path.join(twin, "sourced", CHUNKS_DIR, f));
+ for (const f of readdirSync(path.join(out, LADDER_DIR, LADDER_CHUNKS_DIR))) linkSync(path.join(out, LADDER_DIR, LADDER_CHUNKS_DIR, f), path.join(twin, LADDER_DIR, LADDER_CHUNKS_DIR, f));
+ linkSync(master, path.join(twin, "demo.mp4"));
+ assert.deepEqual(await seedLadderFit(out, twin), ["fit"]);
+ const rt = by(await encodeVariants(twin, { slug: "demo", variants }));
+ assert.equal(rt.half.encode.encoded, 0);
+ assert.equal(rt.fit.encode.encoded, 0, JSON.stringify(rt.fit.encode));
+ assert.equal(md5(rt.half.path), sums.half);
+ assert.equal(md5(rt.fit.path), sums.fit);
+ rmSync(twin, { recursive: true });
+
+ // A rung's file gone: joined again from the cached chunks, to the same bytes.
+ rmSync(r1.half.path);
+ const r3 = by(await encodeVariants(out, { slug: "demo", variants, only: ["half"] }));
+ assert.equal(r3.half.encode.encoded, 0);
+ assert.ok(!r3.half.encode.unchanged);
+ assert.equal(md5(r3.half.path), sums.half, "the join is deterministic");
+
+ // One segment re-made with other pixels (the same length): only its chunks, on every rung.
+ segment(segDir, 7, 33, fps, "s2");
+ await concatWithXfade(segments, render, master, null, null, null, { workDir: work });
+ const rec = JSON.parse(readFileSync(path.join(work, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ const changed = rec.chunks.filter((c) => c.parts.segments.some((s) => s.name === "s2")).length;
+ assert.ok(changed >= 1 && changed < rec.chunks.length);
+ const r4 = by(await encodeVariants(out, { slug: "demo", variants }));
+ assert.equal(r4.half.encode.encoded, new Set(rec.chunks.filter((c) => c.parts.segments.some((s) => s.name === "s2")).map((c) => c.key)).size);
+ assert.equal(r4.half.encode.reused, r4.half.encode.chunks - r4.half.encode.encoded);
+ assert.deepEqual(frameMd5(r4.half.path), frameMd5(master, "scale=-2:144:flags=lanczos"));
+ assert.ok(r4.fit.encode.encoded < r4.fit.encode.chunks || r4.fit.encode.tries > 1, JSON.stringify(r4.fit.encode));
+ assert.equal(statSync(path.join(out, "demo.same.mp4")).ino, statSync(master).ino, "the linked rung follows the new master");
+ // The cache holds what the ladder names, nothing else.
+ const rec4 = JSON.parse(readFileSync(path.join(out, LADDER_DIR, LADDER_RECORD), "utf8"));
+ const named = new Set(Object.values(rec4.rungs).flatMap((r) => r.keys));
+ const onDisk = readdirSync(path.join(out, LADDER_DIR, LADDER_CHUNKS_DIR)).filter((f) => f.startsWith("rung-"));
+ assert.equal(onDisk.length, named.size);
+
+ // --whole (chunked: false): the old way, from the whole cut.
+ const r5 = by(await encodeVariants(out, { slug: "demo", variants, only: ["half"], chunked: false }));
+ assert.equal(r5.half.encode.from, "whole");
+ } finally {
+ setProgressMode("human");
+ if (env === undefined) delete process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ else process.env.REPORT_VIDEO_CHUNK_FRAMES = env;
+ rmSync(out, { recursive: true, force: true });
+ }
+});