commit 873ffc79d7f63fbad02109b5e8d6500bc8c0e70e
parent ded904e15918be306ed893afb98f02b89cf9cf4d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 28 Oct 2026 23:16:39 -0400
umtool variants: the encode ladder from the master's chunks
Each rung of render.variants is now encoded chunk by chunk from the chunks the
master was joined from (out/sourced/chunks/), and joined with -c copy plus the
master's sound, metadata and chapters. The cache rule is its own module,
report-to-video/ladder-chunks.mjs, with no manifest, take or ladder in it:
rungChunkKey({ chunkKey, rung, ffmpeg }) sha256(master chunk key, the
rung's pixel settings, ffmpeg)
encodeChunkCached({ dir, key, frames, encode })
key -> out/ladder/chunks/rung-<key>.mp4,
encoded only when not on disk
masterFromChunks(...) the master IS these chunks, proved
by the sha256 of its video packets
against the chunks' as the build's
mux writes them (memoised by inode)
so it can become the `ladder` module's cache rule. A rung whose keys, sound and
master are the ones its file was joined from (out/ladder/ladder.json) is not
touched; a master chunk that did not change costs nothing on any rung.
A crf rung at the master's own height is the master, hard-linked, never
re-encoded. A size-capped (maxMiB) rung is one-pass ABR per chunk, its sound
encoded once and cached; while it lands over it is lowered by what it
overshot (at least the 6 % step), and the scale it last landed under at is
persisted, so the next run has the same keys and encodes nothing. No chunks,
a master built another way since, or --whole: each rung from the whole cut as
before. variants.json items carry `encode` (from, chunks, encoded, reused).
take --from also links the other take's out/ladder/chunks/.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 856 insertions(+), 32 deletions(-)
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -904,8 +904,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
@@ -915,7 +917,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/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs
@@ -27,7 +27,13 @@
// 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/).
+// 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
//
// 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
@@ -55,6 +61,7 @@ import { link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "no
import path from "node:path";
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 { takesDirOf } from "./takes.mjs";
@@ -106,7 +113,8 @@ export async function fromTakeSourced(projectDir, id, from) {
/**
* Hard-link take `from`'s built files into `takeOut/<variant>` -- `sourced`,
- * and `full` when the other take built it (see the top of the file). The counts are summed over the
+ * 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, variants: string[], keptOwn: string[], keptOwnFrames: string[] }>}
@@ -130,6 +138,14 @@ export async function linkFromTake(projectDir, id, from, takeOut) {
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;
+ }
return out;
}
diff --git a/umtool/lib/report/takeFrom.test.mjs b/umtool/lib/report/takeFrom.test.mjs
@@ -136,7 +136,7 @@ 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) and the full variant", async () => {
+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.
@@ -179,6 +179,19 @@ test("linkFromTake: the chunk record (unless ours is newer) and the full variant
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");
+ await writeFile(path.join(other, "ladder", "ladder.json"), "{}");
+ 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]);
+ assert.ok(!existsSync(path.join(out, "ladder", "ladder.json")), "the record is this take's own");
+ assert.equal((await linkFromTake(p.dir, "twin", "blurred", out)).ladder, 0);
// 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"]);
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,37 @@ 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.
+
+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/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/variants.mjs b/umtool/report-to-video/variants.mjs
@@ -13,21 +13,44 @@
// 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); 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 { 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";
@@ -159,24 +182,143 @@ 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 };
+}
+
+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");
@@ -191,7 +333,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));
@@ -200,10 +345,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;
@@ -223,12 +425,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 });
}
@@ -252,19 +461,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;
}
@@ -282,7 +492,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,7 +5,8 @@
// 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, 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";
@@ -14,6 +15,9 @@ import { fileURLToPath } from "node:url";
import {
DEFAULT_VARIANTS, encodeVariants, fitPlan, parseVariantArgs, 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,124 @@ 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 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 });
+ }
+});