commit 3e6a53b3edd292bbe3c61fa1b8f66298d50a141f
parent fbb239a7b170a1b39e81fa22828f5171f8754c4e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 26 Oct 2026 21:49:43 -0400
report-to-video: the final encode in keyed chunks -- only a chunk whose inputs changed is encoded again
The cut's picture is encoded in chunks anchored on its structure (each
segment's fully-in frame, long ones every 1800 frames from there), each
keyed by its inputs' CONTENTS (segment bytes, the chrome frames it reads),
its graph in its own clock and the encode settings, so an insert or a
longer intro moves later chunks without changing their keys. The sound is
one pass, the two joined by stream copy. Frame for frame the single-pass
graph (lossless test); a changed segment or frame re-encodes only the
chunks that read it. REPORT_VIDEO_CHUNKED=0 / render.chunkedEncode:false
keep the batched pass; REPORT_VIDEO_CHUNK_JOBS sets the parallelism.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
5 files changed, 955 insertions(+), 17 deletions(-)
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -206,7 +206,10 @@ export { snap };
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
import { pruneChromeFrames } from "./prune-frames.mjs";
-import { encodeSegmentCached } from "./segment-cache.mjs";
+import { encodeSegmentCached, ffmpegIdentity } from "./segment-cache.mjs";
+import {
+ CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, chunkKey, chunkSpans, framesRead, sequenceIdentity, spanSegments, whyRebuilt,
+} from "./chunked-encode.mjs";
// The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table,
// in common, plain JS so bare `node` can load it.
import {
@@ -3307,7 +3310,9 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts
...(deck || posts ? ["-reinit_filter", "0"] : []),
...(posts ? ["-itsoffset", offsetArg(r.offset)] : []),
"-framerate", String(render.fps),
- "-start_number", "1",
+ // A chunk of the final encode reads a whole-cut sequence from its own
+ // first frame (`startNumber`, 1-based); everything else from frame 1.
+ "-start_number", String(r.startNumber ?? 1),
"-i", path.join(r.frames, "frame_%06d.png"),
);
const idx = firstInputIdx + i;
@@ -3895,9 +3900,13 @@ export const endFadeAudioFilter = (fade, render) => {
*
* @returns {{ parts: string[], v: string, a: string }}
*/
-export function joinInputChain(i, join, render) {
+export function joinInputChain(i, join, render, { only = null } = {}) {
if (!join) return { parts: [], v: `[${i}:v]`, a: `[${i}:a]` };
- const parts = [];
+ // `only` ("v" | "a"): one side's parts alone, for a graph that carries only
+ // the picture (a chunk of the final encode) or only the sound (its audio pass).
+ const vparts = [];
+ const aparts = [];
+ const parts = vparts;
// The punch-ins first, in the segment's own clock (before a hold clones
// its last frame): each a crop of the footage box scaled back over it.
let vin = `[${i}:v]`;
@@ -3926,8 +3935,8 @@ export function joinInputChain(i, join, render) {
join.dip ? endFadeAudioFilter(join.dip, render) : null,
].filter(Boolean);
const a = af.length ? `[j${i}a]` : `[${i}:a]`;
- if (af.length) parts.push(`[${i}:a]${af.join(",")}${a}`);
- return { parts, v, a };
+ if (af.length) aparts.push(`[${i}:a]${af.join(",")}${a}`);
+ return { parts: only === "v" ? vparts : only === "a" ? aparts : [...vparts, ...aparts], v, a };
}
/**
@@ -4130,12 +4139,18 @@ export async function cutOffsets(segments, D, fps, joins = null) {
* The crossfade concat's filtergraph from the cut's segment lengths (`durs`,
* holds included) and the per-input joins. Without joins, the graph it always was.
*/
-export function xfadeGraph(durs, D, joins = null, render = null, { joined = false } = {}) {
+export function xfadeGraph(durs, D, joins = null, render = null, { joined = false, video = true, audio = true, ctx = null, offsetDigits = 3 } = {}) {
const parts = [];
+ // `video: false` / `audio: false`: one side of the graph alone (the chunked
+ // final encode's picture chunks and its one audio pass). `ctx` makes the
+ // graph a RUN of a longer cut's segments (`{ hasPrev, prevJoin, hasNext }`):
+ // the seam filters at the run's ends are the ones the whole cut puts there.
+ const only = video && !audio ? "v" : audio && !video ? "a" : null;
+ const joinAt = (k) => (k < 0 ? ctx?.prevJoin ?? null : joins?.[k] ?? null);
const ins = durs.map((d, i) => {
// `joined`: the inputs already carry their joins (a batched build's batch
// files), so only each join's `dip` is read -- for the transition after it.
- const c = joinInputChain(i, joined ? null : joins?.[i] ?? null, render);
+ const c = joinInputChain(i, joined ? null : joins?.[i] ?? null, render, { only });
parts.push(...c.parts);
// The sound is pinned to the picture's length before it is crossfaded.
// `xfade` places segment i+1 by the PICTURE's length, `acrossfade` by the
@@ -4156,12 +4171,13 @@ export function xfadeGraph(durs, D, joins = null, render = null, { joined = fals
// 68 ms on the Huck cut).
const len = d.toFixed(6);
const a = `[p${i}a]`;
- parts.push(`${c.a}${AUDIO_ON_CLOCK},apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS${a}`);
+ if (audio) parts.push(`${c.a}${AUDIO_ON_CLOCK},apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS${a}`);
+ if (!video) return { v: c.v, a };
// A blur slide smears and grains each side of a plain seam (transition.mjs).
- const special = (k) => !!(joins?.[k]?.dip || (!joined && (joins?.[k]?.wipe || joins?.[k]?.whip)));
+ const special = (k) => !!(joinAt(k)?.dip || (!joined && (joinAt(k)?.wipe || joinAt(k)?.whip)));
const edges = blurSlideEdges(d, D, render, {
- tail: i < durs.length - 1 && !special(i),
- head: i > 0 && !special(i - 1),
+ tail: (i < durs.length - 1 || !!ctx?.hasNext) && !special(i),
+ head: (i > 0 || !!ctx?.hasPrev) && !special(i - 1),
});
if (!edges) return { v: c.v, a };
const v = `[p${i}e]`;
@@ -4186,8 +4202,8 @@ export function xfadeGraph(durs, D, joins = null, render = null, { joined = fals
const whip = !dip && !wipe && !!joins?.[i - 1]?.whip;
const vx = dip ? "transition=custom:expr='A'" : wipe ? "transition=wipeleft" : whip ? "transition=slideleft" : `transition=${xfadeTransitionOf(render, D)}`;
const ax = dip ? "c1=nofade:c2=nofade" : "c1=tri:c2=tri";
- parts.push(`${vlab}${ins[i].v}xfade=${vx}:duration=${D}:offset=${off.toFixed(3)}[v${i}]`);
- parts.push(`${alab}${ins[i].a}acrossfade=d=${D}:${ax}[a${i}]`);
+ if (video) parts.push(`${vlab}${ins[i].v}xfade=${vx}:duration=${D}:offset=${off.toFixed(offsetDigits)}[v${i}]`);
+ if (audio) parts.push(`${alab}${ins[i].a}acrossfade=d=${D}:${ax}[a${i}]`);
vlab = `[v${i}]`;
alab = `[a${i}]`;
acc = acc + durs[i] - D;
@@ -4239,6 +4255,11 @@ export function hardCutFilterArgs(segments, joins, render, outPath, dips = null)
// pass. Every join is the same dissolve at the same second either way.
export async function concatWithXfade(segments, render, outPath, railPlan, chrome = null, joins = null, { dip = true, workDir = path.dirname(outPath) } = {}) {
const D = render.transition ?? 0.5;
+ // The cut itself (dips drawn, no rail): in keyed chunks (chunked-encode.mjs).
+ if (!railPlan && dip && D > 0 && chunkedEncodeOn(render)) {
+ await chunkedXfadeConcat({ segments, render, outPath, chrome, joins, workDir });
+ return;
+ }
const { durs } = await cutOffsets(segments, D, render.fps, joins);
const plan = xfadeBatches(segments.length, xfadeBatchSize(render));
const batches = plan
@@ -4520,6 +4541,351 @@ export function xfadeConcatArgs({ segments, durs, render, outPath, railPlan = nu
];
}
+// ---- the chunked final encode (chunked-encode.mjs) ---------------------------
+
+/** Is the final encode chunked? `REPORT_VIDEO_CHUNKED=0` or `render.chunkedEncode: false` say no. */
+export function chunkedEncodeOn(render = {}, env = process.env) {
+ if (env.REPORT_VIDEO_CHUNKED === "0") return false;
+ return render?.chunkedEncode !== false;
+}
+
+/** How many chunks are encoded at once: `REPORT_VIDEO_CHUNK_JOBS`, else 2. */
+export function chunkJobs(env = process.env) {
+ const n = Number(env.REPORT_VIDEO_CHUNK_JOBS);
+ return Number.isInteger(n) && n >= 1 ? Math.min(n, 8) : 2;
+}
+
+/** A chunk's picture encode: the cut's own settings, no sound. */
+const chunkEncodeArgs = (render) => [
+ "-c:v", "libx264",
+ "-preset", render.preset ?? "medium",
+ "-crf", String(render.crf ?? 20),
+ "-pix_fmt", "yuv420p",
+ "-r", String(render.fps),
+ "-an",
+];
+
+/** The cut's sound, encoded once: encodeArgs' audio half. */
+const cutAudioEncodeArgs = (render) => [
+ "-c:a", "aac",
+ "-b:a", render.audioBitrate ?? "160k",
+ "-ar", String(render.audioRate),
+ "-ac", String(render.audioChannels),
+];
+
+/** Overlay regions laid like a posts window: a short sequence at its own second. */
+const WINDOW_REGIONS = new Set(["posts", "finale"]);
+
+/**
+ * One chunk's ffmpeg argv (picture only), and the same argv in KEY form with
+ * the inputs it reads. The chunk is frames [a, b) of the cut: the segments
+ * that touch it crossfaded exactly as xfadeGraph crossfades the whole cut
+ * (each with its join; the run's ends with the seams the cut puts there),
+ * trimmed by frame number, the chrome laid over -- a whole-cut sequence from
+ * its frame a + 1, a window at its offset in the chunk's clock, only when it
+ * meets the chunk -- and the dips that meet it, in its frames. Pure.
+ *
+ * @returns {{ argv: string[], keyArgv: string[], inputs: Array<{ kind: "seg", index: number } | { kind: "seq", region: string, dir: string, range: [number, number] }>,
+ * first: number, last: number }}
+ */
+export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins = null, chrome = null, dips = null, totalFrames, outPath }) {
+ const fps = render.fps;
+ const { a, b } = span;
+ const { first, last } = spanSegments(span, starts, durs, fps);
+ const segs = segments.slice(first, last + 1);
+ const g = xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, {
+ audio: false,
+ ctx: { hasPrev: first > 0, prevJoin: joins?.[first - 1] ?? null, hasNext: last < segments.length - 1 },
+ // Offsets to the microsecond: one rounded UP past its frame's timestamp
+ // (12.367 for 12.36667) starts the dissolve a frame late and makes the
+ // run a frame longer (measured, ffmpeg 9), which the trim would then hide
+ // as a one-frame slip against the chrome.
+ offsetDigits: 6,
+ });
+ const parts = [...g.parts];
+ const s0 = Math.round(starts[first] * fps);
+ parts.push(`${g.vlab}trim=start_frame=${a - s0}:end_frame=${b - s0},setpts=PTS-STARTPTS[vw]`);
+
+ const inputs = segs.map((_, k) => ({ kind: "seg", index: first + k }));
+ const regions = [];
+ const keyRegions = [];
+ for (const r of chrome?.regions ?? []) {
+ if (WINDOW_REGIONS.has(r.name)) {
+ const off = Math.round(Number(r.offset) * fps);
+ const count = Number(r.frameCount);
+ if (!Number.isInteger(count) || count <= 0) throw new Error(`chunked encode: the ${r.name} window has no frame count`);
+ if (!(off < b && off + count > a)) continue;
+ const range = framesRead(span, { offsetFrames: off, count });
+ const at = (off - a) / fps;
+ inputs.push({ kind: "seq", region: r.name === "posts" ? `posts ${r.segment ?? ""}`.trim() : r.name, dir: r.frames, range });
+ regions.push({ ...r, offset: at });
+ keyRegions.push({ ...r, frames: `<in:${inputs.length - 1}>`, offset: at });
+ } else {
+ const range = framesRead(span, { offsetFrames: 0, count: totalFrames });
+ inputs.push({ kind: "seq", region: r.name, dir: r.frames, range });
+ regions.push({ ...r, startNumber: a + 1 });
+ keyRegions.push({ ...r, frames: `<in:${inputs.length - 1}>`, startNumber: "<start>" });
+ }
+ }
+ const first0 = segs.length;
+ const hf = regions.length ? chromeOverlayChain(render, regions, "[vw]", first0, { final: true }) : null;
+ const hk = keyRegions.length ? chromeOverlayChain(render, keyRegions, "[vw]", first0, { final: true }) : null;
+ let tail = "[vw]";
+ if (hf) {
+ parts.push(hf.chain);
+ tail = hf.outLabel;
+ }
+ // The dips that meet the chunk, moved into its frames.
+ const mine = (dips ?? [])
+ .filter((w) => w.s < b && w.until > a)
+ .map((w) => ({ ...w, s: w.s - a, last: w.last - a, until: w.until - a }));
+ const dp = dipParts(tail, mine.length ? mine : null, fps);
+ parts.push(...dp.parts);
+ if (dp.label === "[vw]") {
+ // Nothing laid over and no dip: -map cannot name a trim's output twice, so
+ // the label is used as is (it is a filter output, which -map can name).
+ }
+ const graph = parts.join(";");
+ const keyGraph = hk ? graph.replace(hf.chain, hk.chain) : graph;
+ const head = ["-nostdin", "-v", "error", "-y"];
+ const argv = [
+ ...head,
+ ...segs.flatMap((s) => ["-i", s]),
+ ...(hf ? hf.inputs : []),
+ "-filter_complex", graph,
+ "-map", dp.label,
+ ...chunkEncodeArgs(render),
+ outPath,
+ ];
+ const keyArgv = [
+ ...head,
+ ...segs.flatMap((_, k) => ["-i", `<in:${k}>`]),
+ ...(hk ? hk.inputs : []),
+ "-filter_complex", keyGraph,
+ "-map", dp.label,
+ ...chunkEncodeArgs(render),
+ ];
+ return { argv, keyArgv, inputs, first, last };
+}
+
+/**
+ * The cut's sound in one pass: every segment's audio alone (`-vn`), joined
+ * exactly as xfadeGraph joins it (each pinned to its picture's length, the
+ * mutes, holds, fades and dips on their inputs, the acrossfades), encoded
+ * once. Pure.
+ */
+export function cutAudioArgs({ segments, durs, D, render, joins = null, outPath }) {
+ const g = xfadeGraph(durs, D, joins, render, { video: false });
+ return [
+ "-nostdin", "-v", "error", "-y",
+ ...segments.flatMap((s) => ["-vn", "-i", s]),
+ "-filter_complex", g.parts.join(";"),
+ "-map", g.alab,
+ ...cutAudioEncodeArgs(render),
+ outPath,
+ ];
+}
+
+/** The chunks and the sound into the cut: concat demuxer, stream copy, faststart. */
+export function chunkMuxArgs({ listFile, audio, outPath }) {
+ return [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "concat", "-safe", "0", "-i", listFile,
+ "-i", audio,
+ "-map", "0:v:0", "-map", "1:a:0",
+ "-c", "copy",
+ "-movflags", "+faststart",
+ outPath,
+ ];
+}
+
+/** A file's video frame count from its container (no decode); null when unreadable. */
+async function videoFrames(file) {
+ 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;
+}
+
+/** Run `jobs` (async thunks) `width` at a time; the first failure is thrown once they settle. */
+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(width, jobs.length) }, worker));
+ if (failure) throw failure;
+}
+
+/** One line in `<out>/rebuild.ndjson`: what a phase reused and what it rebuilt, and why. */
+export async function logRebuild(workDir, entry) {
+ const line = JSON.stringify({ at: new Date().toISOString(), ...entry }) + "\n";
+ const { appendFile } = await import("node:fs/promises");
+ await appendFile(path.join(workDir, "rebuild.ndjson"), line, "utf8").catch(() => {});
+}
+
+/**
+ * concatWithXfade's chunked encode (chunked-encode.mjs): plan the chunks,
+ * key each by its inputs' contents, encode only the ones whose key is not on
+ * disk (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when
+ * its key matches), and join them into `outPath`. Every chunk's frame count
+ * is checked, and so is the cut's.
+ */
+async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, joins = null, workDir }) {
+ const t0 = Date.now();
+ const D = render.transition ?? 0.5;
+ const fps = render.fps;
+ const { durs, starts, total } = await cutOffsets(segments, D, fps, joins);
+ const N = Math.round(total * fps);
+ const dips = dipWindows(joins, durs, D, fps);
+ const spans = chunkSpans({
+ starts, durs, D, fps, total, max: Number(process.env.REPORT_VIDEO_CHUNK_FRAMES) || undefined,
+ avoid: (dips ?? []).map((w) => [w.s, w.until]),
+ });
+ const dir = path.join(workDir, CHUNKS_DIR);
+ await mkdir(dir, { recursive: true });
+ const memo = await HashMemo.open(path.join(workDir, HASH_MEMO_FILE));
+ const ffmpeg = await ffmpegIdentity(FFMPEG);
+ const prev = await readFile(path.join(dir, CHUNKS_RECORD), "utf8").then((t) => JSON.parse(t), () => null);
+ const prevChunks = Array.isArray(prev?.chunks) ? prev.chunks : [];
+
+ EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` });
+ const segHash = await memo.hashAll(segments);
+ segHash.forEach((h, i) => {
+ if (!h) throw new Error(`chunked encode: segment ${segments[i]} is not a file`);
+ });
+
+ const plan = [];
+ for (const span of spans) {
+ const proto = chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: "" });
+ const ids = [];
+ const layers = {};
+ for (const inp of proto.inputs) {
+ if (inp.kind === "seg") ids.push({ seg: segHash[inp.index] });
+ else {
+ const id = inp.range ? await sequenceIdentity(memo, inp.dir, inp.range) : "none";
+ ids.push({ seq: id });
+ layers[inp.region] = id;
+ }
+ }
+ const key = chunkKey({ keyArgv: proto.keyArgv, inputs: ids, ffmpeg });
+ const file = path.join(dir, `chunk-${key}.mp4`);
+ const s0 = Math.round(starts[proto.first] * fps);
+ const rec = {
+ a: span.a, b: span.b, key, file: path.basename(file),
+ anchor: `${path.basename(segments[proto.first])}@${span.a - s0}`,
+ parts: {
+ segments: segments.slice(proto.first, proto.last + 1).map((s, k) => ({ name: path.basename(s, ".mp4"), id: segHash[proto.first + k] })),
+ layers,
+ graph: createHash("sha1").update(JSON.stringify(proto.keyArgv)).digest("hex").slice(0, 16),
+ },
+ };
+ plan.push({ span, file, rec, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv });
+ }
+ await memo.save();
+
+ // Reused: on disk with the frames it should have.
+ const todo = [];
+ for (const p of plan) {
+ const got = (await exists(p.file)) ? await videoFrames(p.file) : null;
+ if (got === p.span.b - p.span.a) p.reused = true;
+ else todo.push(p);
+ }
+ const why = new Map();
+ for (const p of todo) why.set(p, whyRebuilt(p.rec, prevChunks));
+ const reusedFrames = plan.filter((p) => p.reused).reduce((n, p) => n + (p.span.b - p.span.a), 0);
+ const hms = (f) => `${(f / fps / 60).toFixed(1)} min`;
+ EMIT("note", {
+ message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused), ` +
+ `${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs()} at a time)`,
+ });
+ // Why, grouped, so a line says what changed rather than listing 80 chunks.
+ const byWhy = new Map();
+ for (const p of todo) byWhy.set(why.get(p), [...(byWhy.get(why.get(p)) ?? []), p]);
+ for (const [w, ps] of byWhy) {
+ const at = ps.slice(0, 4).map((p) => `${(p.span.a / fps).toFixed(1)}s`).join(", ") + (ps.length > 4 ? ", …" : "");
+ EMIT("note", { message: ` encode ${ps.length} chunk(s) — ${w} (at ${at})` });
+ }
+
+ // The sound: one pass, keyed by the segments' contents and its argv.
+ const audioProto = cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1);
+ const audioKey = chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg });
+ const audio = path.join(dir, `audio-${audioKey}.m4a`);
+ const audioJob = async () => {
+ if (await exists(audio)) {
+ EMIT("note", { message: "final encode: the cut's sound unchanged — reused" });
+ return;
+ }
+ const ta = Date.now();
+ const tmp = audio.replace(/\.m4a$/, ".partial.m4a");
+ await execFileP(FFMPEG, cutAudioArgs({ segments, durs, D, render, joins, outPath: tmp }), { maxBuffer: 1 << 26 });
+ await rename(tmp, audio);
+ EMIT("note", { message: `final encode: the cut's sound encoded in ${((Date.now() - ta) / 1000).toFixed(1)}s` });
+ };
+
+ let done = 0;
+ const jobs = todo.map((p) => async () => {
+ const tc = Date.now();
+ const tmp = p.file.replace(/\.mp4$/, ".partial.mp4");
+ await rm(tmp, { force: true });
+ await execFileP(FFMPEG, p.argv, { maxBuffer: 1 << 26 });
+ const got = await videoFrames(tmp);
+ if (got !== p.span.b - p.span.a) {
+ await rm(tmp, { force: true });
+ throw new Error(`chunk ${p.rec.anchor} (frames ${p.span.a}–${p.span.b}) encoded ${got} frames, expected ${p.span.b - p.span.a}`);
+ }
+ await rename(tmp, p.file);
+ done += 1;
+ EMIT("note", {
+ message: `final encode: chunk ${done}/${todo.length} (${(p.span.a / fps).toFixed(1)}–${(p.span.b / fps).toFixed(1)}s) ` +
+ `in ${((Date.now() - tc) / 1000).toFixed(1)}s`,
+ });
+ });
+ const tEnc = Date.now();
+ await runPool([audioJob, ...jobs], chunkJobs());
+ const encSeconds = (Date.now() - tEnc) / 1000;
+
+ // Joined: the concat demuxer over the chunks in order, the sound beside.
+ const listFile = path.join(dir, "concat.txt");
+ await writeFile(listFile, plan.map((p) => `file '${path.basename(p.file)}'`).join("\n") + "\n", "utf8");
+ const tmpOut = outPath.replace(/(\.[^.]+)?$/, ".partial$1");
+ await execFileP(FFMPEG, chunkMuxArgs({ listFile, audio, outPath: tmpOut }), { maxBuffer: 1 << 26 });
+ const got = await videoFrames(tmpOut);
+ if (got !== N) {
+ await rm(tmpOut, { force: true });
+ throw new Error(`the joined chunks hold ${got} frames; the cut is ${N}`);
+ }
+ await rename(tmpOut, outPath);
+
+ // The record, and nothing kept that this cut does not use.
+ await writeFile(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");
+ const keep = new Set([...plan.map((p) => path.basename(p.file)), path.basename(audio), CHUNKS_RECORD, "concat.txt"]);
+ for (const name of await readdir(dir)) if (!keep.has(name)) await rm(path.join(dir, name), { force: true });
+
+ const seconds = Number(((Date.now() - t0) / 1000).toFixed(1));
+ EMIT("note", {
+ message: `final encode: done in ${seconds}s — ${plan.length - todo.length} chunk(s) reused, ${todo.length} encoded (${encSeconds.toFixed(1)}s)`,
+ });
+ await logRebuild(workDir, {
+ phase: "encode", chunks: plan.length, reused: plan.length - todo.length, encoded: todo.length,
+ reusedSeconds: Number((reusedFrames / fps).toFixed(2)), encodedSeconds: Number(((N - reusedFrames) / fps).toFixed(2)),
+ seconds, why: Object.fromEntries([...byWhy].map(([w, ps]) => [w, ps.length])),
+ });
+}
+
/**
* Run the rail chain over an already-concatenated file.
*
@@ -4760,7 +5126,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
frames: p.frameCount, key: p.key, dir: p.frames,
seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
});
- const { window: _w, frameCount: _n, ...region } = pr;
+ const { window: _w, ...region } = pr;
regions.push(region);
}
@@ -4891,7 +5257,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
frames: p.frameCount, key: p.key, dir: p.frames,
seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
});
- const { window: _w, frameCount: _n, ...region } = fr;
+ const { window: _w, ...region } = fr;
regions.push(region);
}
return { regions, outLabel: "[hfout]" };
diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs
@@ -0,0 +1,261 @@
+// THE CHUNKED FINAL ENCODE: the cut's picture is encoded in CHUNKS, each
+// keyed by exactly what makes its pixels, and only a chunk whose key changed
+// is encoded again. The sound is one pass over the whole cut (cheap, and an
+// AAC stream that is never cut), and the two are joined by stream copy.
+//
+// Why chunks: the old final pass was one x264 `slow` run over the whole cut,
+// ~25 minutes for the 31-minute Huck cut, on every build -- an intro change
+// re-encoded every frame. A chunk is a run of the cut's frames, [a, b),
+// encoded on its own (an IDR at its first frame, a closed GOP at its last),
+// at the cut's own encoder settings, from the few segments it touches:
+// crossfaded exactly as the whole-cut graph crossfades them, trimmed to its
+// frames by frame number, the chrome frames of [a, b) laid over, the dips in
+// it drawn. Joined with the concat demuxer, `-c copy`, the chunks are one
+// stream: frame-exact (tested), every frame once, timestamps continuous.
+//
+// Where chunks start: on the cut's structure, not its clock. Chunk i begins
+// where segment i is fully in (its start plus the crossfade) and runs to the
+// same point of segment i + 1, so it holds segment i and the dissolve out of
+// it; a long one is cut every CHUNK_MAX_FRAMES from that anchor. An insert,
+// or an intro that grew, MOVES every later chunk without changing one of
+// them: a chunk's key names its inputs by content and its numbers relative
+// to its own first frame, so a moved chunk keys as it did.
+//
+// What a key covers (chunkKey): the encoder's argv with every input replaced
+// by its CONTENT -- a segment by the sha1 of its bytes, a chrome sequence by
+// the sha1s of the frames the chunk reads of it (and one frame either side)
+// -- the filter graph (crossfade offsets, trims, joins, overlay positions,
+// dips: all in the chunk's own clock), the encode settings and the ffmpeg
+// binary. A frame recaptured to the same pixels hashes the same; one pixel
+// different is a new key. Nothing is keyed by a name or a time that could
+// say "same" about different pixels.
+//
+// Plain node; every path is a parameter.
+
+import { createHash } from "node:crypto";
+import { readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+/** Bumped when what a chunk key covers changes: every chunk is encoded once more. */
+export const CHUNK_KEY_VERSION = 1;
+/** A chunk longer than this (frames) is cut from its anchor every this many frames. */
+export const CHUNK_MAX_FRAMES = 1800;
+/** A cut's tail piece shorter than this (frames) joins the piece before it. */
+export const CHUNK_MIN_TAIL = 150;
+/** Where the chunks live under the variant's out dir. */
+export const CHUNKS_DIR = "chunks";
+/** The record of the last chunked encode (spans, keys, what each was made of). */
+export const CHUNKS_RECORD = "chunks.json";
+/** The content-hash memo, beside the chunks: `dev:ino:size:mtime` -> sha1. */
+export const HASH_MEMO_FILE = ".content-hashes.json";
+
+const sha256 = (s) => createHash("sha256").update(s).digest("hex");
+
+/**
+ * The chunk spans of a cut, in its frames: `[{ a, b }]`, `b` exclusive,
+ * consecutive, covering [0, N). `starts`/`durs` are the cut's (cutOffsets:
+ * holds included), `D` the crossfade.
+ *
+ * Anchors: 0, and each segment's start plus the crossfade (where it is fully
+ * in). A span longer than `max` is cut every `max` frames from its anchor, a
+ * last piece under `minTail` joining the one before it, and never inside a
+ * range of `avoid` (`[lo, hi]` frames: a cut there moves to `hi`).
+ */
+export function chunkSpans({ starts, durs, D, fps, total, max = CHUNK_MAX_FRAMES, minTail = Math.min(CHUNK_MIN_TAIL, Math.floor(max / 4)), avoid = [] }) {
+ const N = Math.round(total * fps);
+ const Dn = Math.round(D * fps);
+ const anchors = [0];
+ for (let i = 1; i < starts.length; i += 1) {
+ const x = Math.round(starts[i] * fps) + Dn;
+ if (x > anchors[anchors.length - 1] && x < N) anchors.push(x);
+ }
+ anchors.push(N);
+ const out = [];
+ for (let k = 0; k + 1 < anchors.length; k += 1) {
+ const a0 = anchors[k];
+ const b0 = anchors[k + 1];
+ let a = a0;
+ while (b0 - a > max) {
+ let b = a + max;
+ // Never inside a dip's fade (`avoid`: [s, until) frame ranges): a chunk
+ // that began inside one would draw it with geq, not fade.
+ for (const [lo, hi] of avoid) if (b > lo && b < hi) b = hi;
+ if (b0 - b < minTail) break;
+ out.push({ a, b });
+ a = b;
+ }
+ out.push({ a, b: b0 });
+ }
+ return out;
+}
+
+/**
+ * The segments a span of frames touches: `[first, last]`, the segments whose
+ * frames in the cut ([start, start + length)) meet [a, b).
+ */
+export function spanSegments({ a, b }, starts, durs, fps) {
+ let first = -1;
+ let last = -1;
+ for (let i = 0; i < starts.length; i += 1) {
+ const s = Math.round(starts[i] * fps);
+ const e = s + Math.round(durs[i] * fps);
+ if (s < b && e > a) {
+ if (first < 0) first = i;
+ last = i;
+ }
+ }
+ if (first < 0) throw new Error(`no segment covers frames ${a}–${b}`);
+ return { first, last };
+}
+
+/**
+ * The frames of a sequence a chunk [a, b) reads, as 1-based frame numbers
+ * `[lo, hi]` of the sequence, widened by one frame each side and clipped to
+ * the sequence (`count` frames): a whole-cut layer (`offsetFrames` 0) reads
+ * a+1..b; a window laid at cut frame `offsetFrames` reads its own frames that
+ * land in the chunk. null when none do.
+ */
+export function framesRead({ a, b }, { offsetFrames = 0, count }) {
+ const lo = Math.max(1, a - offsetFrames + 1 - 1);
+ const hi = Math.min(count, b - offsetFrames + 1);
+ return lo <= hi ? [lo, hi] : null;
+}
+
+// ---- content hashes ----------------------------------------------------------
+
+/**
+ * A memo of file contents' sha1, keyed by what changes when a file does
+ * (device, inode, size, mtime): a file rebuilt through a rename is a new
+ * inode, one rewritten in place a new mtime, and a hard link of another
+ * take's file is the same inode -- hashed once for both.
+ */
+export class HashMemo {
+ constructor(file = null) {
+ this.file = file;
+ this.map = new Map();
+ this.dirty = false;
+ this.hashed = 0;
+ this.bytes = 0;
+ }
+
+ static async open(file) {
+ const m = new HashMemo(file);
+ const text = file ? await readFile(file, "utf8").catch(() => null) : null;
+ if (text) {
+ try {
+ const obj = JSON.parse(text);
+ if (obj?.v === 1 && obj.h && typeof obj.h === "object") for (const [k, v] of Object.entries(obj.h)) m.map.set(k, v);
+ } catch {
+ // A torn memo is an empty one: everything is hashed again.
+ }
+ }
+ return m;
+ }
+
+ /** The sha1 of `file`'s bytes, or null when it is not a regular file. */
+ async hash(file) {
+ const st = await stat(file).catch(() => null);
+ if (!st?.isFile()) return null;
+ const id = `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}`;
+ const had = this.map.get(id);
+ if (had) return had;
+ const h = createHash("sha1").update(await readFile(file)).digest("hex");
+ // The file may have changed while it was read: keep the hash only when
+ // its identity is still the one it was read under.
+ const after = await stat(file).catch(() => null);
+ if (after && `${after.dev}:${after.ino}:${after.size}:${after.mtimeMs}` === id) {
+ this.map.set(id, h);
+ this.dirty = true;
+ }
+ this.hashed += 1;
+ this.bytes += st.size;
+ return h;
+ }
+
+ /** Hash many files, `width` at a time; the hashes in order. */
+ async hashAll(files, width = 8) {
+ const out = new Array(files.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < files.length) {
+ const k = next;
+ next += 1;
+ out[k] = await this.hash(files[k]);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(width, files.length) }, worker));
+ return out;
+ }
+
+ /** Keep only the entries `keep` says to (`(id) => boolean`). */
+ prune(keep) {
+ for (const k of [...this.map.keys()]) {
+ if (!keep(k)) {
+ this.map.delete(k);
+ this.dirty = true;
+ }
+ }
+ }
+
+ async save() {
+ if (!this.file || !this.dirty) return;
+ const tmp = `${this.file}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify({ v: 1, h: Object.fromEntries(this.map) }), "utf8");
+ await rename(tmp, this.file);
+ this.dirty = false;
+ }
+}
+
+/** A frame sequence's file name for 1-based frame `n` (frame_%06d.png). */
+export const frameFile = (dir, n) => path.join(dir, `frame_${String(n).padStart(6, "0")}.png`);
+
+/**
+ * What a run of a sequence's frames contributes to a key: the sha1 of their
+ * hashes in order ("-" for a frame that is not there).
+ */
+export async function sequenceIdentity(memo, dir, [lo, hi]) {
+ const files = [];
+ for (let n = lo; n <= hi; n += 1) files.push(frameFile(dir, n));
+ const hs = await memo.hashAll(files);
+ return createHash("sha1").update(hs.map((h) => h ?? "-").join("\n")).digest("hex");
+}
+
+/**
+ * A chunk's key: its argv in KEY form (every input a placeholder `<in:k>`,
+ * every sequence's start frame `<start>`), each input's identity, the ffmpeg
+ * binary. See the top of the file.
+ */
+export function chunkKey({ keyArgv, inputs, ffmpeg }) {
+ return sha256(JSON.stringify({ v: CHUNK_KEY_VERSION, ffmpeg, argv: keyArgv, inputs })).slice(0, 24);
+}
+
+/**
+ * Why a chunk is encoded again, for the progress line: compared with the last
+ * build's record of the chunk made of the same segments from the same frame
+ * of the first, the inputs and the graph that differ; else "new".
+ *
+ * @param {{ parts: { segments: Array<{ name: string, id: string }>, layers: Record<string, string>, graph: string }, anchor: string }} rec
+ * @param {Array<object>} previous the last record's chunks
+ */
+export function whyRebuilt(rec, previous = []) {
+ if (!previous.length) return "first chunked build";
+ const same = previous.find((p) => p.anchor === rec.anchor);
+ if (!same) return "new span (the timeline changed here)";
+ const why = [];
+ const segNames = (x) => x.parts.segments.map((s) => s.name).join(",");
+ if (segNames(same) !== segNames(rec)) why.push("other segments");
+ else {
+ rec.parts.segments.forEach((s, k) => {
+ if (same.parts.segments[k]?.id !== s.id) why.push(`segment ${s.name} changed`);
+ });
+ }
+ const layers = new Set([...Object.keys(rec.parts.layers ?? {}), ...Object.keys(same.parts.layers ?? {})]);
+ for (const l of [...layers].sort()) {
+ if ((rec.parts.layers ?? {})[l] !== (same.parts.layers ?? {})[l]) {
+ why.push(!(l in (same.parts.layers ?? {})) ? `${l} added` : !(l in (rec.parts.layers ?? {})) ? `${l} gone` : `${l} frames changed`);
+ }
+ }
+ if (same.parts.graph !== rec.parts.graph) why.push("joins/dips/encode changed");
+ if (same.b - same.a !== rec.b - rec.a) why.push(`length ${same.b - same.a}→${rec.b - rec.a} frames`);
+ return why.length ? why.join(", ") : "key changed";
+}
diff --git a/umtool/report-to-video/chunked-encode.test.mjs b/umtool/report-to-video/chunked-encode.test.mjs
@@ -0,0 +1,309 @@
+// The chunked final encode (chunked-encode.mjs, build-video's
+// chunkedXfadeConcat): the spans a cut is cut into, what a chunk's key covers
+// (and that a MOVED chunk keys as it did while a changed input does not), and
+// real ffmpeg runs -- a chunked build of a small cut with joins, a hold, a dip,
+// a whole-cut chrome sequence and a posts window, losslessly encoded, frame for
+// frame against the single-pass graph; then a rebuild after one segment
+// changes, which re-encodes only the chunks that segment is in.
+//
+// Run with: node --test umtool/report-to-video/chunked-encode.test.mjs
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ CHUNKS_DIR, CHUNKS_RECORD, HashMemo, chunkKey, chunkSpans, framesRead, spanSegments, whyRebuilt,
+} from "./chunked-encode.mjs";
+import { chunkVideoArgs, concatWithXfade, dipWindows, setProgressMode, withCutEdits, xfadeConcatArgs } from "./build-video.mjs";
+import { scheduleFrom } from "./deck.mjs";
+
+test("chunkSpans: anchored where each segment is fully in, long spans cut from the anchor", () => {
+ // Segments of 100, 60, 400 frames at 10 fps, a 5-frame crossfade.
+ const fps = 10;
+ const durs = [10, 6, 40];
+ const { starts, total } = scheduleFrom(durs, 0.5);
+ assert.deepEqual(starts.map((s) => Math.round(s * fps)), [0, 95, 150]);
+ const spans = chunkSpans({ starts, durs, D: 0.5, fps, total, max: 1000 });
+ assert.deepEqual(spans, [{ a: 0, b: 100 }, { a: 100, b: 155 }, { a: 155, b: 550 }]);
+ // Cut every 120 from the anchor; a tail under max/4 (30) joins the piece before.
+ const cut = chunkSpans({ starts, durs, D: 0.5, fps, total, max: 120 });
+ assert.deepEqual(cut, [{ a: 0, b: 100 }, { a: 100, b: 155 }, { a: 155, b: 275 }, { a: 275, b: 395 }, { a: 395, b: 515 }, { a: 515, b: 550 }]);
+ // Consecutive and complete.
+ for (const s of [spans, cut]) {
+ assert.equal(s[0].a, 0);
+ assert.equal(s.at(-1).b, Math.round(total * fps));
+ for (let k = 1; k < s.length; k += 1) assert.equal(s[k].a, s[k - 1].b);
+ }
+ // Never inside a dip.
+ const dodged = chunkSpans({ starts, durs, D: 0.5, fps, total, max: 120, avoid: [[270, 290]] });
+ assert.deepEqual(dodged.map((x) => x.a), [0, 100, 155, 290, 410]);
+});
+
+test("chunkSpans: an earlier segment growing MOVES the later spans without reshaping them", () => {
+ const fps = 30;
+ const a = [5.5, 20, 31.4, 12, 64];
+ const b = [7.2, 20, 31.4, 12, 64]; // the intro 1.7 s longer
+ const sa = scheduleFrom(a, 0.5);
+ const sb = scheduleFrom(b, 0.5);
+ const A = chunkSpans({ ...sa, durs: a, D: 0.5, fps, max: 900 });
+ const B = chunkSpans({ ...sb, durs: b, D: 0.5, fps, max: 900 });
+ assert.equal(A.length, B.length);
+ const shift = B[1].a - A[1].a;
+ assert.equal(shift, 51);
+ for (let k = 1; k < A.length; k += 1) {
+ assert.equal(B[k].a - A[k].a, shift);
+ assert.equal(B[k].b - A[k].b, shift);
+ }
+});
+
+test("spanSegments / framesRead", () => {
+ const fps = 10;
+ const durs = [10, 6, 40];
+ const { starts } = scheduleFrom(durs, 0.5);
+ assert.deepEqual(spanSegments({ a: 0, b: 100 }, starts, durs, fps), { first: 0, last: 1 });
+ assert.deepEqual(spanSegments({ a: 100, b: 155 }, starts, durs, fps), { first: 1, last: 2 });
+ assert.deepEqual(spanSegments({ a: 160, b: 300 }, starts, durs, fps), { first: 2, last: 2 });
+ // A whole-cut layer: frames a+1..b, one more each side.
+ assert.deepEqual(framesRead({ a: 100, b: 155 }, { count: 550 }), [100, 156]);
+ assert.deepEqual(framesRead({ a: 0, b: 100 }, { count: 550 }), [1, 101]);
+ assert.deepEqual(framesRead({ a: 500, b: 550 }, { count: 550 }), [500, 550]);
+ // A window of 40 frames laid at cut frame 120: its frames 1..40 are cut 120..159.
+ assert.deepEqual(framesRead({ a: 100, b: 155 }, { offsetFrames: 120, count: 40 }), [1, 36]);
+ assert.deepEqual(framesRead({ a: 155, b: 300 }, { offsetFrames: 120, count: 40 }), [35, 40]);
+ assert.equal(framesRead({ a: 200, b: 300 }, { offsetFrames: 120, count: 40 }), null);
+});
+
+test("HashMemo: the bytes, memoised by inode; a hard link is a hit, a rewrite is not", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "chunk-memo-"));
+ try {
+ const f = path.join(dir, "a.bin");
+ writeFileSync(f, "one");
+ const memo = await HashMemo.open(path.join(dir, "memo.json"));
+ const h1 = await memo.hash(f);
+ linkSync(f, path.join(dir, "b.bin"));
+ assert.equal(await memo.hash(path.join(dir, "b.bin")), h1);
+ assert.equal(memo.hashed, 1, "the link was not read again");
+ writeFileSync(f, "two");
+ utimesSync(f, new Date(), new Date(Date.now() + 5000));
+ const h2 = await memo.hash(f);
+ assert.notEqual(h2, h1);
+ await memo.save();
+ const again = await HashMemo.open(path.join(dir, "memo.json"));
+ assert.equal(await again.hash(f), h2);
+ assert.equal(again.hashed, 0, "read back from the memo");
+ assert.equal(await memo.hash(path.join(dir, "missing")), null);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+const R30 = { width: 64, height: 36, fps: 30, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 };
+
+test("chunkVideoArgs: a chunk keys the same after the cut before it grew; its own inputs change it", () => {
+ const segs = ["/x/intro.mp4", "/x/c1.mp4", "/x/c2.mp4", "/x/c3.mp4"];
+ const regions = [{ name: "deck", frames: "/x/chrome/deck-frames", x: 0, y: 20, width: 64, height: 16 }];
+ const at = (durs) => {
+ const { starts, total } = scheduleFrom(durs, 0.5);
+ const spans = chunkSpans({ starts, durs, D: 0.5, fps: 30, total });
+ return { durs, starts, spans, N: Math.round(total * 30) };
+ };
+ const A = at([5.5, 20, 31.4, 12]);
+ const B = at([7.2, 20, 31.4, 12]);
+ const args = (c, k) => chunkVideoArgs({
+ segments: segs, durs: c.durs, starts: c.starts, span: c.spans[k], D: 0.5, render: R30,
+ chrome: { regions }, totalFrames: c.N, outPath: "/x/out.mp4",
+ });
+ for (const k of [1, 2, 3]) {
+ const a = args(A, k);
+ const b = args(B, k);
+ assert.deepEqual(b.keyArgv, a.keyArgv, `chunk ${k}: the same argv in key form`);
+ assert.notDeepEqual(b.argv, a.argv, "the real argv reads other deck frames");
+ assert.deepEqual(b.inputs.map((x) => x.kind), a.inputs.map((x) => x.kind));
+ // The deck frames it reads moved with it.
+ const da = a.inputs.find((x) => x.kind === "seq").range;
+ const db = b.inputs.find((x) => x.kind === "seq").range;
+ assert.equal(db[0] - da[0], 51);
+ assert.equal(db[1] - da[1], 51);
+ }
+ // The chunk holding the intro changed.
+ assert.notDeepEqual(args(B, 0).keyArgv, args(A, 0).keyArgv);
+ // Same key form, other contents: other keys.
+ const a1 = args(A, 1);
+ const ids = a1.inputs.map((x, k) => (x.kind === "seg" ? { seg: `s${k}` } : { seq: "d" }));
+ const k0 = chunkKey({ keyArgv: a1.keyArgv, inputs: ids, ffmpeg: "ff" });
+ assert.equal(chunkKey({ keyArgv: a1.keyArgv, inputs: structuredClone(ids), ffmpeg: "ff" }), k0);
+ assert.notEqual(chunkKey({ keyArgv: a1.keyArgv, inputs: ids.map((x) => (x.seq ? { seq: "e" } : x)), ffmpeg: "ff" }), k0, "a deck frame changed");
+ assert.notEqual(chunkKey({ keyArgv: a1.keyArgv, inputs: ids.map((x) => (x.seg === "s0" ? { seg: "t" } : x)), ffmpeg: "ff" }), k0, "a segment changed");
+ assert.notEqual(chunkKey({ keyArgv: a1.keyArgv, inputs: ids, ffmpeg: "ff2" }), k0, "another ffmpeg");
+ assert.notEqual(chunkKey({ keyArgv: args(A, 1).keyArgv.map((x) => (x === "0" ? "1" : x)), inputs: ids, ffmpeg: "ff" }), k0, "another crf");
+});
+
+test("whyRebuilt names what changed", () => {
+ const rec = (seg2, deck) => ({
+ a: 0, b: 10, anchor: "c1.mp4@15",
+ parts: { segments: [{ name: "c1", id: "1" }, { name: "c2", id: seg2 }], layers: { deck }, graph: "g" },
+ });
+ assert.equal(whyRebuilt(rec("2", "d"), []), "first chunked build");
+ assert.equal(whyRebuilt(rec("2", "d"), [rec("3", "d")]), "segment c2 changed");
+ assert.equal(whyRebuilt(rec("2", "d"), [rec("2", "e")]), "deck frames changed");
+ assert.match(whyRebuilt({ ...rec("2", "d"), anchor: "c9.mp4@0" }, [rec("2", "d")]), /new span/);
+});
+
+// ---- real ffmpeg -------------------------------------------------------------
+
+const have = spawnSync("ffmpeg", ["-version"]).status === 0;
+const COLOURS = ["red", "green", "blue", "yellow", "magenta", "cyan"];
+
+function run(argv) {
+ const r = spawnSync("ffmpeg", argv, { maxBuffer: 1 << 26 });
+ assert.equal(r.status, 0, String(r.stderr));
+}
+
+/** A segment: a moving test pattern tinted per index, a tone. */
+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=64x36:r=${fps}:d=${frames / fps + 1},trim=end_frame=${frames},colorchannelmixer=rr=${0.4 + 0.1 * i}`,
+ "-f", "lavfi", "-i", `sine=f=${300 + 100 * i}:r=48000:d=${frames / fps}`,
+ "-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;
+}
+
+/** A PNG sequence with alpha: `n` frames, each different (testsrc2's counter). */
+function sequence(dir, n, fps, w, h) {
+ mkdirSync(dir, { recursive: true });
+ run([
+ "-v", "error", "-y", "-f", "lavfi",
+ "-i", `testsrc2=s=${w}x${h}:r=${fps}:d=${n / fps + 1},format=rgba,colorchannelmixer=aa=0.6`,
+ "-frames:v", String(n), path.join(dir, "frame_%06d.png"),
+ ]);
+}
+
+/** Every frame's md5, decoded. */
+function frameMd5(file) {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-map", "0:v", "-f", "framemd5", "-"], { maxBuffer: 1 << 26 });
+ assert.equal(r.status, 0, String(r.stderr));
+ return r.stdout.toString().split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split(",").pop().trim());
+}
+
+const probeFrames = (file) => Number(spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).stdout.toString().trim());
+const audioSeconds = (file) => Number(spawnSync("ffprobe", ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=duration", "-of", "default=nw=1:nk=1", file]).stdout.toString().trim());
+
+test("a chunked build is the single-pass graph, frame for frame; a changed segment re-encodes only its chunks", { skip: !have }, async () => {
+ const fps = 10;
+ const render = { width: 64, height: 36, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0, palette: { bg: "#101820" } };
+ const dir = mkdtempSync(path.join(tmpdir(), "chunked-"));
+ const events = [];
+ setProgressMode((e) => events.push(e));
+ const env = { ...process.env };
+ process.env.REPORT_VIDEO_CHUNK_FRAMES = "24";
+ try {
+ const lens = [25, 40, 33, 30, 52];
+ const segments = lens.map((f, i) => segment(dir, i, f, fps));
+ const durs0 = lens.map((f) => f / fps);
+ // A hold on segment 1 (its last frame held 0.8 s), a dip at the end of
+ // segment 2 (into "a teaser"), the end fade on the last.
+ const joins = withCutEdits([null, { hold: 0.8, move: null }, null, null, null], 5, {
+ dips: new Map([[2, { seconds: 0.6, lastFrame: 32, black: 0.3 }]]),
+ fade: { seconds: 0.5, lastFrame: 51 },
+ });
+ const durs = durs0.map((d, i) => d + (joins?.[i]?.hold ?? 0));
+ const { starts, total } = scheduleFrom(durs, 0.5);
+ const N = Math.round(total * fps);
+ // Chrome: a whole-cut "deck" and a posts window of 30 frames at frame 40.
+ sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12);
+ sequence(path.join(dir, "chrome", "posts-s1-frames"), 30, fps, 20, 20);
+ const regions = [
+ { name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 },
+ { name: "posts", segment: "s1", frames: path.join(dir, "chrome", "posts-s1-frames"), x: 40, y: 0, width: 20, height: 20, offset: 4.0, frameCount: 30 },
+ ];
+ const chrome = { regions, outLabel: "[hfout]" };
+
+ const single = path.join(dir, "single.mp4");
+ run(xfadeConcatArgs({ segments, durs, render, outPath: single, chrome, joins }));
+ const chunked = path.join(dir, "chunked.mp4");
+ await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir });
+
+ assert.equal(probeFrames(chunked), N);
+ const want = frameMd5(single);
+ const got = frameMd5(chunked);
+ assert.equal(got.length, want.length);
+ const diff = got.map((h, f) => (h === want[f] ? null : f)).filter((f) => f != null);
+ assert.deepEqual(diff, [], "every frame of the chunked build is the single pass's");
+ assert.ok(Math.abs(audioSeconds(chunked) - total) < 0.05, `the sound runs the cut (${audioSeconds(chunked)} vs ${total})`);
+
+ const record = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ assert.ok(record.chunks.length >= 6, `cut into ${record.chunks.length} chunks`);
+ assert.ok(dipWindows(joins, durs, 0.5, fps).length === 1);
+
+ // Again: everything reused.
+ events.length = 0;
+ await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir });
+ assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "nothing encoded the second time");
+ assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? "")));
+ assert.deepEqual(frameMd5(chunked), want);
+
+ // Segment 3 re-made with other pixels (same length): only its chunks.
+ segment(dir, 5, 30, fps, "s3");
+ events.length = 0;
+ await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir });
+ const record2 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ const changed = record2.chunks.filter((c, k) => c.key !== record.chunks[k].key);
+ assert.ok(changed.length >= 1 && changed.length < record.chunks.length, `${changed.length} of ${record.chunks.length} re-encoded`);
+ for (const c of changed) assert.ok(c.parts.segments.some((s) => s.name === "s3"), `a re-encoded chunk holds s3 (${c.anchor})`);
+ for (const c of record2.chunks.filter((x) => !changed.includes(x))) assert.ok(!c.parts.segments.some((s) => s.name === "s3"));
+ assert.ok(events.some((e) => /segment s3 changed/.test(e.message ?? "")), "the note says why");
+ // And the result is the single pass over the new segments.
+ const single2 = path.join(dir, "single2.mp4");
+ run(xfadeConcatArgs({ segments, durs, render, outPath: single2, chrome, joins }));
+ assert.deepEqual(frameMd5(chunked), frameMd5(single2));
+ // A deck frame changed: only the chunks that read it.
+ const f = path.join(dir, "chrome", "deck-frames", "frame_000070.png");
+ const bytes = readFileSync(path.join(dir, "chrome", "deck-frames", "frame_000010.png"));
+ rmSync(f);
+ writeFileSync(f, bytes);
+ await concatWithXfade(segments, render, chunked, null, chrome, joins, { workDir: dir });
+ const record3 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8"));
+ const moved = record3.chunks.filter((c, k) => c.key !== record2.chunks[k].key);
+ assert.ok(moved.length >= 1 && moved.length <= 2, `${moved.length} chunk(s) read frame 70`);
+ for (const c of moved) assert.ok(c.a <= 70 && c.b >= 69, `chunk ${c.a}–${c.b} reads frame 70`);
+ const single3 = path.join(dir, "single3.mp4");
+ run(xfadeConcatArgs({ segments, durs, render, outPath: single3, chrome, joins }));
+ assert.deepEqual(frameMd5(chunked), frameMd5(single3));
+ // The chunks dir holds this cut's chunks and nothing else.
+ const files = readdirSync(path.join(dir, CHUNKS_DIR)).filter((n) => n.startsWith("chunk-"));
+ assert.equal(files.length, record3.chunks.length);
+ } finally {
+ setProgressMode("human");
+ for (const k of Object.keys(process.env)) if (!(k in env)) delete process.env[k];
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("at 30 fps the chunks hold exactly the cut's frames (offsets to the microsecond)", { skip: !have }, async () => {
+ const fps = 30;
+ const dir = mkdtempSync(path.join(tmpdir(), "chunked30-"));
+ setProgressMode(() => {});
+ process.env.REPORT_VIDEO_CHUNK_FRAMES = "40";
+ try {
+ // Lengths whose offsets round UP at three decimals (k/30 with k mod 3 = 2).
+ const lens = [62, 47, 53, 71];
+ const segments = lens.map((f, i) => segment(dir, i, f, fps));
+ const durs = lens.map((f) => f / fps);
+ const { total } = scheduleFrom(durs, 0.5);
+ const out = path.join(dir, "cut.mp4");
+ await concatWithXfade(segments, R30, out, null, null, null, { workDir: dir });
+ assert.equal(probeFrames(out), Math.round(total * fps));
+ } finally {
+ setProgressMode("human");
+ delete process.env.REPORT_VIDEO_CHUNK_FRAMES;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -22,6 +22,7 @@
"./brand-ids": "./brand-ids.mjs",
"./build-video": "./build-video.mjs",
"./check-availability": "./check-availability.mjs",
+ "./chunked-encode": "./chunked-encode.mjs",
"./claims": "./claims.mjs",
"./clip-audio": "./clip-audio.mjs",
"./clip-blur": "./clip-blur.mjs",
diff --git a/umtool/report-to-video/xfade-batch.test.mjs b/umtool/report-to-video/xfade-batch.test.mjs
@@ -173,7 +173,8 @@ test("seven segments in batches of three: the same frames as one pass", { skip:
try {
const segments = COLOURS.map((_, i) => segment(dir, i));
const durs = segments.map(() => 2);
- const render = { ...RENDER, xfadeBatch: 3 };
+ // The batched join (the chunked final encode, chunked-encode.mjs, is off).
+ const render = { ...RENDER, xfadeBatch: 3, chunkedEncode: false };
const onePath = path.join(dir, "one.mp4");
const r = spawnSync("ffmpeg", xfadeConcatArgs({ segments, durs, render, outPath: onePath }));