Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit f14437b4974ccae5ae9d83f9853b6da2c9737b80
parent c7d77e4ada9409d49e0610f7ab18d747866b5092
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 27 Oct 2026 09:45:38 -0400

Merge lane/fast-rerender: the final encode in keyed chunks, chrome frames reused by their keys, take --from keeps a take's own newer frames

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/lib/report/takeFrom.mjs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/lib/report/takeFrom.test.mjs | 41++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/takeMaker.mjs | 12+++++++++++-
Mumtool/report-to-video/README.md | 32++++++++++++++++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 459+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/chrome-deck.mjs | 17+++++++++++------
Mumtool/report-to-video/chrome-deck.test.mjs | 8+++++---
Mumtool/report-to-video/chrome-feed.mjs | 24++++++++++++++++--------
Mumtool/report-to-video/chrome-finale.mjs | 14+++++++++-----
Mumtool/report-to-video/chrome-stamp.mjs | 12+++++++-----
Aumtool/report-to-video/chunked-encode.mjs | 268+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/chunked-encode.test.mjs | 337+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/claim-knobs.test.mjs | 4++--
Mumtool/report-to-video/compose-chrome.mjs | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/deck-claims.test.mjs | 10++++++++--
Mumtool/report-to-video/deck.mjs | 31+++++++++++++++++++++++++++++++
Mumtool/report-to-video/factcheck.test.mjs | 24++++++++++++++----------
Mumtool/report-to-video/finale.test.mjs | 4++--
Aumtool/report-to-video/frame-keys.mjs | 324+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/frame-keys.test.mjs | 278+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/xfade-batch.test.mjs | 3++-
22 files changed, 2088 insertions(+), 93 deletions(-)

diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -16,6 +16,23 @@ // when both are there, the one whose .key // was written last // +// chunks/chunk-<key>.mp4, audio-<key>.m4a +// each chunk of the final encode, reused +// when its key (its inputs' CONTENTS) is +// (chunked-encode.mjs), and the content- +// hash memo, merged +// +// 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 +// segments and chrome frames of its OWN cut on disk, newer than the other +// take's; linking over them threw away a finished deck and feed (the 15:44 +// run of final-1026-best-blurred captured both again). A segment's files go +// as a group (the .mp4 and the .cut.json naming its key must come from the +// same build), decided by the newest of each side's files; a chrome layer by +// its `.key`'s mtime. The older layer is not lost: it is linked in as +// `chrome/work-from-<layer>-frames`, where the chrome render finds frames it +// can reuse (compose-chrome's frame reuse), and a prune removes it. +// // Links, never copies, and never a symlink: every one of these the build // REPLACES rather than writes -- a segment through a rename // (encodeSegmentCached), its records and texts through a rename (replaceFile), @@ -26,9 +43,10 @@ // // Plain node; the CLI runs it with bare node. -import { link, lstat, mkdir, readdir, rename, rm, writeFile } from "node:fs/promises"; +import { link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { DEFAULT_VARIANT, SEGMENT_FILE_SUFFIXES, XFADE_FROM_FILE } from "umtool-report-to-video/build-video"; +import { CHUNKS_DIR, HASH_MEMO_FILE } from "umtool-report-to-video/chunked-encode"; import { takesDirOf } from "./takes.mjs"; /** Where `--from` keeps a layer aside: the other take's `out/.keep-frames/<layer>-frames`. */ @@ -79,7 +97,7 @@ export async function fromTakeSourced(projectDir, id, from) { /** * Hard-link take `from`'s built files into `takeOut/sourced` (see the top of the file). - * @returns {Promise<{ segments: number, frames: string[], batches: number }>} + * @returns {Promise<{ segments: number, frames: string[], batches: number, chunks: number, keptOwn: string[], keptOwnFrames: string[] }>} */ export async function linkFromTake(projectDir, id, from, takeOut) { const src = await fromTakeSourced(projectDir, id, from); @@ -90,10 +108,38 @@ export async function linkFromTake(projectDir, id, from, takeOut) { const segs = path.join(src, "segments"); const segOut = path.join(dst, "segments"); await mkdir(segOut, { recursive: true }); + // By segment: its files, theirs and ours (see the top of the file). + const idOf = (f) => { + const suffix = SEGMENT_FILE_SUFFIXES.filter((x) => f.endsWith(x)).sort((x, y) => y.length - x.length)[0]; + return suffix ? f.slice(0, -suffix.length) : null; + }; + const groups = new Map(); for (const f of await names(segs)) { - if (f.startsWith(".") || !SEGMENT_FILE_SUFFIXES.some((s) => f.endsWith(s))) continue; - if (!(await isFile(path.join(segs, f)))) continue; - if (await linkFile(path.join(segs, f), path.join(segOut, f))) out.segments += 1; + if (f.startsWith(".")) continue; + const id = idOf(f); + if (!id || !(await isFile(path.join(segs, f)))) continue; + groups.set(id, [...(groups.get(id) ?? []), f]); + } + const newest = async (dir, files) => Math.max(0, ...(await Promise.all(files.map((f) => lstat(path.join(dir, f)).then((st) => st.mtimeMs, () => 0))))); + const ownNames = await names(segOut); + out.keptOwn = []; + for (const [id, theirs] of [...groups].sort((x, y) => x[0].localeCompare(y[0]))) { + const own = ownNames.filter((f) => !f.startsWith(".") && idOf(f) === id); + const ownFiles = []; + for (const f of own) if (await isFile(path.join(segOut, f))) ownFiles.push(f); + const linkedAlready = await Promise.all(ownFiles.map(async (f) => { + const [a, b] = await Promise.all([lstat(path.join(segOut, f)), lstat(path.join(segs, f)).catch(() => null)]); + return !!b && a.ino === b.ino && a.dev === b.dev; + })); + const ownBuilt = ownFiles.filter((_, k) => !linkedAlready[k]); + if (ownBuilt.length && (await newest(segOut, ownBuilt)) > (await newest(segs, theirs))) { + out.keptOwn.push(id); + continue; + } + for (const f of theirs) if (await linkFile(path.join(segs, f), path.join(segOut, f))) out.segments += 1; + // Ours that theirs does not have would sit beside their segment as if + // they were its own: gone. + for (const f of ownFiles) if (!theirs.includes(f)) await rm(path.join(segOut, f), { force: true }); } // The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside. @@ -111,8 +157,20 @@ export async function linkFromTake(projectDir, id, from, takeOut) { } } if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true }); - for (const [name, { dir }] of [...layers].sort((x, y) => x[0].localeCompare(y[0]))) { - await linkFrames(dir, path.join(dst, "chrome", name)); + out.keptOwnFrames = []; + for (const [name, { dir, at }] of [...layers].sort((x, y) => x[0].localeCompare(y[0]))) { + const mine = path.join(dst, "chrome", name); + const ownKey = await lstat(path.join(mine, ".key")).catch(() => null); + const theirKey = await lstat(path.join(dir, ".key")).catch(() => null); + const same = ownKey && theirKey && ownKey.ino === theirKey.ino && ownKey.dev === theirKey.dev; + if (ownKey?.isFile() && !same && ownKey.mtimeMs > at) { + // This take's own render is the newer: kept; theirs beside it for frame reuse. + await linkFrames(dir, path.join(dst, "chrome", `work-from-${name}`)); + out.keptOwnFrames.push(name); + continue; + } + if (ownKey?.isFile() && !same) await linkFrames(mine, path.join(dst, "chrome", `work-from-own-${name}`)); + await linkFrames(dir, mine); out.frames.push(name); } @@ -123,6 +181,25 @@ export async function linkFromTake(projectDir, id, from, takeOut) { await mkdir(batchOut, { recursive: true }); if (await linkFile(path.join(batches, f), path.join(batchOut, f))) out.batches += 1; } + // The final encode's chunks and sound, by content key: theirs beside ours. + const chunks = path.join(src, CHUNKS_DIR); + const chunksOut = path.join(dst, CHUNKS_DIR); + out.chunks = 0; + for (const f of await names(chunks)) { + if (!/^(chunk|audio)-[0-9a-f]+\.(mp4|m4a)$/.test(f) || !(await isFile(path.join(chunks, f)))) continue; + await mkdir(chunksOut, { recursive: true }); + if (!(await isFile(path.join(chunksOut, f))) && (await linkFile(path.join(chunks, f), path.join(chunksOut, f)))) out.chunks += 1; + } + // The content-hash memo: theirs merged into ours (both name files by inode). + const memoOf = (d) => readFile(path.join(d, HASH_MEMO_FILE), "utf8").then((t) => JSON.parse(t), () => null); + const [theirMemo, ownMemo] = await Promise.all([memoOf(src), memoOf(dst)]); + if (theirMemo?.v === 1 && theirMemo.h) { + const merged = { v: 1, h: { ...theirMemo.h, ...(ownMemo?.v === 1 ? ownMemo.h : {}) } }; + const tmp = path.join(dst, `${HASH_MEMO_FILE}.${process.pid}.tmp`); + await writeFile(tmp, JSON.stringify(merged), "utf8"); + await rename(tmp, path.join(dst, HASH_MEMO_FILE)); + } + // A batch the other take keyed by its own segments' paths (before keys // named files) is found through this: build-video adopts it when this // take's segments are those very files (xfadeBatchKeyV1). diff --git a/umtool/lib/report/takeFrom.test.mjs b/umtool/lib/report/takeFrom.test.mjs @@ -60,8 +60,9 @@ test("linkFromTake: segments, keyed chrome frames (kept-aside ones too) and fini try { const out = path.join(p.dir, "takes", "twin", "out"); await mkdir(path.join(out, "sourced", "segments"), { recursive: true }); - // A file of the twin's own is replaced by the link (through a rename). + // An OLDER file of the twin's own is replaced by the link (through a rename). await writeFile(path.join(out, "sourced", "segments", "s02.mp4"), "the twin's own"); + await utimes(path.join(out, "sourced", "segments", "s02.mp4"), new Date(0), new Date(0)); const got = await linkFromTake(p.dir, "twin", "blurred", out); const d = path.join(out, "sourced"); for (const f of ["s01.mp4", "s01.cut.json", "s01.attrib.txt", "s02.mp4", "s02.cut.json", "brand-intro.mp4", "brand-intro.intro.json"]) { @@ -97,6 +98,44 @@ test("linkFromTake: segments, keyed chrome frames (kept-aside ones too) and fini } }); +test("linkFromTake: this take's own NEWER build (a re-run after a stop) is kept, theirs beside it", async () => { + const p = await project(); + try { + const out = path.join(p.dir, "takes", "twin", "out"); + const d = path.join(out, "sourced"); + await mkdir(path.join(d, "segments"), { recursive: true }); + await mkdir(path.join(d, "chrome", "deck-frames"), { recursive: true }); + // The twin's own run, stopped mid-chrome: s01 and the deck rendered for + // ITS cut, after the other take's. + const later = new Date(Date.now() + 60_000); + for (const f of ["s01.mp4", "s01.cut.json"]) { + await writeFile(path.join(d, "segments", f), `twin ${f}`); + await utimes(path.join(d, "segments", f), later, later); + } + await writeFile(path.join(d, "chrome", "deck-frames", "frame_000001.png"), "twin png"); + await writeFile(path.join(d, "chrome", "deck-frames", ".key"), "twin-key\n"); + await utimes(path.join(d, "chrome", "deck-frames", ".key"), later, later); + const got = await linkFromTake(p.dir, "twin", "blurred", out); + assert.deepEqual(got.keptOwn, ["s01"]); + assert.equal(await readFile(path.join(d, "segments", "s01.mp4"), "utf8"), "twin s01.mp4"); + assert.equal(await readFile(path.join(d, "segments", "s01.cut.json"), "utf8"), "twin s01.cut.json", "the record stays with its segment"); + assert.ok(!existsSync(path.join(d, "segments", "s01.attrib.txt")), "none of theirs beside our s01"); + assert.ok(sameFile(path.join(p.src, "segments", "s02.mp4"), path.join(d, "segments", "s02.mp4")), "a segment we lack is linked"); + assert.deepEqual(got.keptOwnFrames, ["deck-frames"]); + assert.ok(!got.frames.includes("deck-frames")); + assert.equal(await readFile(path.join(d, "chrome", "deck-frames", ".key"), "utf8"), "twin-key\n", "our deck is not replaced"); + assert.ok(sameFile(path.join(p.src, "chrome", "deck-frames", "frame_000001.png"), path.join(d, "chrome", "work-from-deck-frames", "frame_000001.png")), "theirs kept for frame reuse"); + // An OLDER own layer is replaced, and kept beside as well. + await utimes(path.join(d, "chrome", "deck-frames", ".key"), new Date(0), new Date(0)); + const again = await linkFromTake(p.dir, "twin", "blurred", out); + assert.ok(again.frames.includes("deck-frames")); + assert.equal(await readFile(path.join(d, "chrome", "deck-frames", ".key"), "utf8"), "k1\n"); + assert.equal(await readFile(path.join(d, "chrome", "work-from-own-deck-frames", ".key"), "utf8"), "twin-key\n"); + } finally { + await rm(p.root, { recursive: true, force: true }); + } +}); + test("makeTake --from: linked before the render; --keep-frames reaches the build; a bad --from is refused before anything is written", async () => { const p = await project(); try { diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -551,8 +551,18 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { const got = await fromTake.linkFromTake(projectDir, spec.id, /** @type {string} */ (opts.from), takeOut); log( `${spec.id}: linked from ${opts.from}: ${got.segments} segment file(s), ` + - `${got.frames.length ? got.frames.join(", ") : "no chrome frames"}, ${got.batches} crossfade batch(es) — reused where they still match`, + `${got.frames.length ? got.frames.join(", ") : "no chrome frames"}, ${got.batches} crossfade batch(es), ` + + `${got.chunks ?? 0} encode chunk(s) — reused where they still match`, ); + // This take's own newer build, kept (takeFrom.mjs): said, so a re-run says why it did not start over. + if (got.keptOwn?.length || got.keptOwnFrames?.length) { + log( + `${spec.id}: kept this take's own newer ` + + [got.keptOwn?.length ? `${got.keptOwn.length} segment(s)` : null, got.keptOwnFrames?.length ? got.keptOwnFrames.join(", ") : null] + .filter(Boolean).join(" and ") + + ` (${opts.from}'s older ones kept beside them for reuse)`, + ); + } } // The take's manifest is written under a work name until the render is diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -1886,6 +1886,34 @@ parsing — wrapping the expression in single quotes is what protects them. those changes touch, then the last pass, and files of a stale key are removed when the next batched build starts. Past 24² segments the batches grow instead, so the last pass stays 24 inputs wide. +- **The final encode is in keyed chunks** (`chunked-encode.mjs`, lane + fast-rerender). The cut's picture is encoded as runs of frames, each from the + few segments it touches -- crossfaded exactly as the whole-cut graph does it + (a lossless test checks it frame for frame), trimmed by frame number, the + chrome frames of its span laid over, its dips drawn -- at the cut's own + encoder settings, then joined by stream copy with the sound, which is one + pass over the whole cut. A chunk starts where a segment is fully in (its start + plus the crossfade) and runs to the same point of the next, cut every 1800 + frames from there; its key is its inputs' CONTENTS (each segment's bytes, the + sha1 of every chrome frame it reads), its graph in its own clock and the + encode settings. So a re-render encodes only the chunks whose pixels can + differ, and an insert or a longer intro moves every later chunk without + changing its key. `out/<variant>/chunks/` holds them (`chunks.json` says what + each was made of); `rebuild.ndjson` beside it logs, per build, what each + phase reused and what it rebuilt and why. `REPORT_VIDEO_CHUNK_JOBS` (default + 2) encodes that many at once; `REPORT_VIDEO_CHUNKED=0` or + `render.chunkedEncode: false` goes back to the batched single pass. It needs + no crossfade batches: no chunk opens more than a few segments. +- **Chrome frames are reused by their keys** (`frame-keys.mjs`). The deck, the + stamps, the feed and the finale are cue-interpreter pages, so what a frame + draws is the page less its cue list plus every element's value at that frame + (computed as GSAP draws it). A layer whose page changed is assembled from the + frames on disk with the same key -- its last render, or the one `take --from` + linked beside it -- and only the rest are captured, in ONE render of the page + that plays just those frames. Cue times sit on a 1/240 s grid + (`deck.mjs cueTime`, stamps on whole frames) so a moment the cut moved draws + exactly what it drew. A change every frame shows (a title, the pips after an + insert) still renders the layer whole. ## Two cuts from one manifest (`--variant`) @@ -1924,8 +1952,8 @@ out/ availability.json SHARED — a fact about the manifest, not about a cut <slug>.mp4 sourced <slug>-full.mp4 full - sourced/{cards,segments,qr,chrome,xfade-batches,schedule.json} - full/{cards,segments,qr,chrome,xfade-batches,schedule.json} + sourced/{cards,segments,qr,chrome,chunks,xfade-batches,schedule.json,rebuild.ndjson} + full/{cards,segments,qr,chrome,chunks,xfade-batches,schedule.json,rebuild.ndjson} ``` `xfade-batches/` exists only for a cut long enough to be crossfaded in batches 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 { @@ -549,6 +552,7 @@ const HUMAN = { (e.total !== undefined ? `, ${Number(e.total).toFixed(3)}s` : "") + (e.duration !== undefined ? ` window ${e.from}s +${e.duration}s` : "") + (e.frames !== undefined ? `: ${e.frames} frame(s)` : "") + + (e.reused !== undefined && !e.cached ? `, ${e.reused} frame(s) reused, ${e.captured} captured` : "") + (e.seconds !== undefined ? ` in ${e.seconds}s` : "") + (e.key ? ` (key ${String(e.key).slice(0, 12)})` : "") + (e.base ? ` over ${e.base}` : ""), @@ -3307,7 +3311,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 +3901,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 +3936,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 +4140,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 +4172,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 +4203,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 +4256,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 +4542,357 @@ 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; + // Two spans that key alike are one file: encoded once. + const byKey = new Map(); + for (const p of todo) if (!byKey.has(p.rec.key)) byKey.set(p.rec.key, p); + const jobs = [...byKey.values()].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}/${byKey.size} (${(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"); + // The memo keeps what this cut is made of: a frame or segment gone is forgotten. + memo.pruneUnseen(); + await memo.save(); + 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. * @@ -4692,6 +5065,14 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re */ async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null }) { const { composeChrome } = await import("./compose-chrome.mjs"); + // Each layer's outcome, said and logged (rebuild.ndjson): cached whole, + // frames reused, or rendered. + const layers = []; + const emitChrome = (fields) => { + EMIT("chrome", fields); + if (fields.phase !== "compose") layers.push({ region: fields.region ?? "deck", segment: fields.segment, phase: fields.phase, + frames: fields.frames, reused: fields.reused, captured: fields.captured, seconds: fields.seconds }); + }; EMIT("chrome", { phase: "compose", ...(duration != null ? { from, duration } : {}) }); const t0 = Date.now(); const r = await composeChrome({ @@ -4706,8 +5087,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro `is ${want} (${(duration ?? schedule.total).toFixed(3)}s at ${render.fps} fps)`, ); } - EMIT("chrome", { - phase: r.cached ? "cached" : "render", + emitChrome({ + phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", + ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}), frames: r.frameCount, key: r.key, dir: r.frames, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)), }); @@ -4728,8 +5110,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (f.frameCount !== want) { throw new Error(`the feed's sequence is ${f.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: f.cached ? "cached" : "render", region: "feed", + emitChrome({ + phase: f.cached ? "cached" : f.reused > 0 ? "reuse" : "render", region: "feed", + ...(f.reused != null ? { reused: f.reused, captured: f.captured } : {}), frames: f.frameCount, key: f.key, dir: f.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -4755,12 +5138,13 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro `the overlay expects ${pr.frameCount} at ${pr.frames}`, ); } - EMIT("chrome", { - phase: p.cached ? "cached" : "render", region: "posts", segment: pr.segment, + emitChrome({ + phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: "posts", segment: pr.segment, + ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}), 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); } @@ -4779,8 +5163,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (st.frameCount !== want) { throw new Error(`the stamps' sequence is ${st.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: st.cached ? "cached" : "render", region: "stamp", + emitChrome({ + phase: st.cached ? "cached" : st.reused > 0 ? "reuse" : "render", region: "stamp", + ...(st.reused != null ? { reused: st.reused, captured: st.captured } : {}), frames: st.frameCount, key: st.key, dir: st.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -4801,8 +5186,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (sr.frameCount !== want) { throw new Error(`the stats region's sequence is ${sr.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: sr.cached ? "cached" : "render", region: "stats", + emitChrome({ + phase: sr.cached ? "cached" : sr.reused > 0 ? "reuse" : "render", region: "stats", + ...(sr.reused != null ? { reused: sr.reused, captured: sr.captured } : {}), frames: sr.frameCount, key: sr.key, dir: sr.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -4823,8 +5209,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (fr.frameCount !== want) { throw new Error(`the effects' sequence is ${fr.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: fr.cached ? "cached" : "render", region: "fx", + emitChrome({ + phase: fr.cached ? "cached" : fr.reused > 0 ? "reuse" : "render", region: "fx", + ...(fr.reused != null ? { reused: fr.reused, captured: fr.captured } : {}), frames: fr.frameCount, key: fr.key, dir: fr.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -4844,8 +5231,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (th.frameCount !== want) { throw new Error(`the thread rail's sequence is ${th.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: th.cached ? "cached" : "render", region: "threads", + emitChrome({ + phase: th.cached ? "cached" : th.reused > 0 ? "reuse" : "render", region: "threads", + ...(th.reused != null ? { reused: th.reused, captured: th.captured } : {}), frames: th.frameCount, key: th.key, dir: th.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -4864,8 +5252,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (fl.frameCount !== want) { throw new Error(`the flips panel's sequence is ${fl.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: fl.cached ? "cached" : "render", region: "flips", + emitChrome({ + phase: fl.cached ? "cached" : fl.reused > 0 ? "reuse" : "render", region: "flips", + ...(fl.reused != null ? { reused: fl.reused, captured: fl.captured } : {}), frames: fl.frameCount, key: fl.key, dir: fl.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -4886,14 +5275,16 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (p.frames !== fr.frames || p.frameCount !== fr.frameCount) { throw new Error(`the finale rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${fr.frameCount} at ${fr.frames}`); } - EMIT("chrome", { - phase: p.cached ? "cached" : "render", region: "finale", + emitChrome({ + phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: "finale", + ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}), 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); } + if (duration == null && layers.length) await logRebuild(outDir, { phase: "chrome", layers }); return { regions, outLabel: "[hfout]" }; } diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -38,7 +38,7 @@ import { fileURLToPath } from "node:url"; import { - claimsLayout, deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck, + claimsLayout, cueTime, cueTimeAfter, stampsOnFrames, deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck, } from "./deck.mjs"; import { claimsCues, claimsMarkup } from "./chrome-claims.mjs"; import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyLabelOf, tallyOf, tallyPopIns, VERDICT_SHAPES } from "./factcheck.mjs"; @@ -185,7 +185,9 @@ export function deckCues(schedule, render) { // ---- events, unordered; froms are filled in below ---------------------- const ev = []; - const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); + // Cue times on the sub-frame grid (deck.mjs cueTime), durations to 4 places. + const fps = Number(schedule.fps ?? render.fps ?? 30); + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: cueTime(at, fps), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); const setSeg = (i, state, at, why) => { add(keyOf(i, "seg"), at, INSTANT, state.seg, "none", why); for (const p of PARTS) add(keyOf(i, p), at, INSTANT, state[p], "none", why); @@ -272,7 +274,7 @@ export function deckCues(schedule, render) { // then pops in; it keeps its place in the row (the deck is laid for every // cell), so nothing else moves when it does. if (tally) { - const t = tallyCues(schedule.factcheck.stamps, tally, { popIn: tallyPopIns(render, tally) }); + const t = tallyCues(stampsOnFrames(schedule.factcheck.stamps, fps), tally, { popIn: tallyPopIns(render, tally) }); for (const [k, v] of Object.entries(t.init)) put(k, v); for (const e of t.events) add(e.k, e.at, e.dur, e.to, e.ease, e.why); } @@ -282,7 +284,10 @@ export function deckCues(schedule, render) { for (let k = 0; k < pips.length - 1; k += 1) { const a = arrive.get(k), b = depart.get(k); if (a === undefined || b === undefined) continue; - add("fuse", a, b - a, { scaleX: frac(k + 1), transformOrigin: "0% 50%" }, "none", `fuse ${pips[k].id}`); + // Its length from its ends on the cue grid: two segments' starts, each + // stored to the millisecond, would make it a millisecond off in a cut + // moved by a number of frames -- and every frame of its burn a new key. + add("fuse", a, cueTime(b, fps) - cueTime(a, fps), { scaleX: frac(k + 1), transformOrigin: "0% 50%" }, "none", `fuse ${pips[k].id}`); } } @@ -320,14 +325,14 @@ export function deckCues(schedule, render) { let { at, dur } = e; if (at < free) { const end = at + dur; - at = r4(free); + at = cueTimeAfter(free, fps); dur = r4(Math.max(INSTANT, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const p of Object.keys(e.to)) from[p] = cur[p]; Object.assign(cur, e.to); - freeAt.set(e.k, r4(at + dur)); + freeAt.set(e.k, at + dur); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why }); } return { init, cues, pips, slideY, choreography: ch, ...(markers.length ? { markers } : {}), ...(claims ? { claims } : {}) }; diff --git a/umtool/report-to-video/chrome-deck.test.mjs b/umtool/report-to-video/chrome-deck.test.mjs @@ -13,7 +13,7 @@ import test from "node:test"; import { fileURLToPath } from "node:url"; import { deckCues, deckHtml, GSAP_FILE, hostOf, mix, subtitleMarkup } from "./chrome-deck.mjs"; -import { deckChoreography, deckLayout } from "./deck.mjs"; +import { cueTime, deckChoreography, deckLayout } from "./deck.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -362,8 +362,10 @@ test("the fact-check tally is in the panel, so it slides with it; a cut without // The count steps as the stamp lands, and the page carries that cue. const { cues } = deckCues(stamped, RENDER); const step = cues.find((c) => c.k === "ty.CORROBORATED.n1"); - assert.equal(step.at, 18.78); - assert.ok(dataOf(html).cues.some((c) => c.k === "ty.CORROBORATED.n1" && c.at === 18.78)); + // (A stamp on the cut's frames, deck.mjs stampsOnFrames; cues on the sub-frame grid, cueTime.) + const landed = cueTime(Math.round(18.78 * 30) / 30, 30); + assert.equal(step.at, landed); + assert.ok(dataOf(html).cues.some((c) => c.k === "ty.CORROBORATED.n1" && c.at === landed)); // The title's column gives the tally its room. const narrowed = deckLayout(RENDER, { tally: ["CORROBORATED"] }); assert.ok(html.includes(`max-width: ${narrowed.text.width}px`)); diff --git a/umtool/report-to-video/chrome-feed.mjs b/umtool/report-to-video/chrome-feed.mjs @@ -33,7 +33,7 @@ // fixed name (`embedFn`, docs/quirks.md); the tests call the same function // with heights of their choosing. Every cue is a fromTo whose FROM is stated: // a render is a seek per frame, from parallel workers, in any order. -import { deckChoreography, feedGeometry, pageDuration, resolveDeck } from "./deck.mjs"; +import { CUE_GRID, deckChoreography, feedGeometry, pageDuration, resolveDeck } from "./deck.mjs"; import { mix, rgba } from "./chrome-deck.mjs"; import { embedFn, PLATFORM_LABEL, postDate, postParagraphs, postWho } from "./chrome-posts.mjs"; @@ -115,9 +115,14 @@ export function feedLayout(render) { export function feedCues({ posts, heights, column, visibility = [], startsHidden = false, slideX = 600, enterX = 600, gap = 16, push = 0.4, lag = 0.22, enter = 0.6, glowAt = 0.2, glowUp = 0.2, glowDown = 1.2, newest = 0.55, - calm = 0.8, leave = 0.45, + calm = 0.8, leave = 0.45, grid = 0, }) { const R = (v) => Math.round(v * 10000) / 10000; + // `grid` (steps a second, deck.mjs CUE_GRID × fps): every time on it, the + // posts' and the column's own first -- so a cut moved by whole frames moves + // every cue by whole steps (frame-keys.mjs). 0: four decimals, as it was. + const G = grid > 0 ? (v) => Math.round(v * grid) / grid : R; + const after = grid > 0 ? (v) => Math.ceil(v * grid - 1e-6) / grid : R; const MIN = 0.001; const n = posts.length; const init = { col: { x: startsHidden ? slideX : 0 } }; @@ -127,12 +132,12 @@ export function feedCues({ } const ev = []; - const add = (k, at, dur, to, ease, why) => ev.push({ k, at: R(at), dur: R(Math.max(MIN, dur)), to, ease, why }); + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: G(at), dur: R(Math.max(MIN, dur)), to, ease, why }); const y = new Array(n).fill(0); const visible = []; const gone = new Array(n).fill(null); for (let m = 0; m < n; m += 1) { - const t = posts[m].in; + const t = G(posts[m].in); const id = posts[m].id; const room = (heights[m] || 0) + gap; // Room at the top: every card in moves down by the new one's height, and @@ -158,7 +163,8 @@ export function feedCues({ } for (const v of visibility) { if (v.at[1] - v.at[0] <= 0 && v.i === 0) continue; // hidden from the first frame: that is init - add("col", v.at[0], v.at[1] - v.at[0], { x: v.hide ? slideX : 0 }, v.hide ? "power2.in" : "power3.out", + const a0 = G(v.at[0]); + add("col", a0, G(v.at[1]) - a0, { x: v.hide ? slideX : 0 }, v.hide ? "power2.in" : "power3.out", `${v.hide ? "hide" : "show"} @${v.i}`); } @@ -175,14 +181,14 @@ export function feedCues({ const free = freeAt[e.k] ?? -Infinity; if (at < free) { const end = at + dur; - at = R(free); + at = after(free); dur = R(Math.max(MIN, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const q of Object.keys(e.to)) from[q] = cur[q]; Object.assign(cur, e.to); - freeAt[e.k] = R(at + dur); + freeAt[e.k] = grid > 0 ? at + dur : R(at + dur); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why, i: cues.length }); } cues.sort((a, b) => a.at - b.at || a.i - b.i); @@ -358,6 +364,8 @@ export function feedHtml(schedule, render, opts = {}) { enterX: left ? -(lay.stack.width + lay.padX) : lay.stack.width + lay.padX, visibility: vis.map((v) => ({ i: v.i, hide: v.hide, at: v.at.map(r4) })), motion: FEED_MOTION, + // The cue grid (feedCues `grid`): steps a second. + grid: Number(schedule.fps ?? render.fps ?? 30) * CUE_GRID, ids: posts.map((p) => p.id), posts: posts.map((p) => ({ id: p.id, in: p.in })), }; @@ -532,7 +540,7 @@ export function feedHtml(schedule, render, opts = {}) { posts: F.posts, heights, column: F.column, visibility: F.visibility, startsHidden: F.startsHidden, slideX: F.slideX, enterX: F.enterX, gap: M.gap, push: M.push, lag: M.lag, enter: M.enter, glowAt: M.glowAt, glowUp: M.glowUp, glowDown: M.glowDown, newest: M.newest, calm: M.calm, - leave: M.leave, + leave: M.leave, grid: F.grid, }); for (const k of Object.keys(plan.init)) if (byK[k]) gsap.set(byK[k], plan.init[k]); const inner = gsap.timeline({ paused: true }); diff --git a/umtool/report-to-video/chrome-finale.mjs b/umtool/report-to-video/chrome-finale.mjs @@ -22,7 +22,7 @@ // in place. Either way the page fades out through the dissolve after the run. // // The timeline is cues, each stating its from (chrome-deck.mjs says why). -import { finaleRail, pageDuration, resolveDeck } from "./deck.mjs"; +import { cueTime, cueTimeAfter, finaleRail, pageDuration, resolveDeck } from "./deck.mjs"; import { finaleClaimsMarkup } from "./chrome-claims.mjs"; import { mix, rgba, shapeCss, subtitleMarkup } from "./chrome-deck.mjs"; import { resolveFactcheck, tallyFinals, tallyOf, tallyVerdicts, VERDICT_SHAPES } from "./factcheck.mjs"; @@ -139,7 +139,9 @@ export function finaleCues(schedule, render, L = finaleLayout(schedule, render)) const init = {}; const put = (k, v) => { init[k] = { ...(init[k] ?? {}), ...v }; }; const ev = []; - const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); + // Cue times on the sub-frame grid (deck.mjs cueTime), durations to 4 places. + const fps = Number(schedule.fps ?? render.fps ?? 30); + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: cueTime(at, fps), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); const ft = L.foot.track, bt = L.rail.track; // From a rect the footer drew to this one: a uniform scale, centres matched @@ -277,14 +279,14 @@ export function finaleCues(schedule, render, L = finaleLayout(schedule, render)) const free = freeAt.get(e.k) ?? -Infinity; if (at < free) { const end = at + dur; - at = r4(free); + at = cueTimeAfter(free, fps); dur = r4(Math.max(INSTANT, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const p of Object.keys(e.to)) from[p] = cur[p] ?? (p.startsWith("scale") || p === "opacity" || p === "autoAlpha" ? 1 : 0); Object.assign(cur, e.to); - freeAt.set(e.k, r4(at + dur)); + freeAt.set(e.k, at + dur); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why }); } return { init, cues }; @@ -446,7 +448,9 @@ export function finaleHtml(schedule, render, window, opts = {}) { : null; const data = { - from: r4(from), dur, init, + // The window's first second on the cue grid too: a frame-aligned start, + // so a moved finale's frames are seeked to exactly the moved times. + from: cueTime(from, fps), dur, init, cues: cues.map(({ why, ...c }) => c), }; const json = JSON.stringify(data).replace(/</g, "\\u003c"); diff --git a/umtool/report-to-video/chrome-stamp.mjs b/umtool/report-to-video/chrome-stamp.mjs @@ -11,7 +11,7 @@ // The timeline is cues, computed here, each stating its from -- a render is a // seek per frame, from parallel workers, in any order (chrome-deck.mjs says // why at length). The times are factcheck.mjs `stampSchedule`'s, untouched. -import { pageDuration, stampGeometry } from "./deck.mjs"; +import { cueTime, cueTimeAfter, pageDuration, stampGeometry, stampsOnFrames } from "./deck.mjs"; import { mix, rgba } from "./chrome-deck.mjs"; import { drawnStamps, resolveFactcheck, STAMP_MOTION } from "./factcheck.mjs"; @@ -47,13 +47,15 @@ export const STAMP_POSE = Object.freeze({ rest: -6, from: -14, scale: 1.7, leave */ export function stampCues(schedule, render = null) { // A claim's `stamp: false` counts in the tally and is not drawn here. - const stamps = drawnStamps(schedule.factcheck?.stamps); + const fps = Number(schedule.fps ?? render?.fps ?? 30); + const stamps = stampsOnFrames(drawnStamps(schedule.factcheck?.stamps), fps); const motion = render ? resolveFactcheck(render).stamp.motion ?? "slam" : "slam"; const P = STAMP_POSE; const m = STAMP_MOTION; const init = {}; const ev = []; - const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); + // Cue times on the sub-frame grid (deck.mjs cueTime), durations to 4 places. + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: cueTime(at, fps), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); stamps.forEach((s, j) => { const why = `stamp ${s.claim}`; const rest = { autoAlpha: 1, scale: 1, rotation: P.rest }; @@ -90,14 +92,14 @@ export function stampCues(schedule, render = null) { const free = freeAt.get(e.k) ?? 0; if (at < free) { const end = at + dur; - at = r4(free); + at = cueTimeAfter(free, fps); dur = r4(Math.max(INSTANT, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const p of Object.keys(e.to)) from[p] = cur[p]; Object.assign(cur, e.to); - freeAt.set(e.k, r4(at + dur)); + freeAt.set(e.k, at + dur); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why }); } return { init, cues }; diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs @@ -0,0 +1,268 @@ +// 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; + this.seen = new Set(); + } + + 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}`; + this.seen.add(id); + 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; + } + + /** Forget every file not hashed (or found) since the memo was opened. */ + pruneUnseen() { + this.prune((id) => this.seen.has(id)); + } + + /** 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,337 @@ +// 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 }); + } +}); + +test("two spans that key alike are encoded once and joined twice", { skip: !have }, async () => { + const fps = 10; + const render = { width: 64, height: 36, fps, transition: 0.5, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0 }; + const dir = mkdtempSync(path.join(tmpdir(), "chunked-dup-")); + const events = []; + setProgressMode((e) => events.push(e)); + try { + // The same segment four times: the middle spans are the same pixels. + const one = segment(dir, 1, 30, fps, "same"); + const segments = [0, 1, 2, 3].map((k) => { + const f = path.join(dir, `s${k}.mp4`); + writeFileSync(f, readFileSync(one)); + return f; + }); + const out = path.join(dir, "cut.mp4"); + await concatWithXfade(segments, render, out, null, null, null, { workDir: dir }); + const rec = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); + const keys = rec.chunks.map((c) => c.key); + assert.ok(new Set(keys).size < keys.length, `some spans key alike (${keys.join(" ")})`); + const encoded = events.filter((e) => /^final encode: chunk \d+\/\d+/.test(e.message ?? "")).length; + assert.equal(encoded, new Set(keys).size, "each key encoded once"); + assert.equal(probeFrames(out), Math.round(scheduleFrom([3, 3, 3, 3], 0.5).total * fps)); + } finally { + setProgressMode("human"); + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/claim-knobs.test.mjs b/umtool/report-to-video/claim-knobs.test.mjs @@ -11,7 +11,7 @@ import { CLAIM_LIMITS, drawnStamps, normalizeClaim, resolveFactcheck, STAMP_MOTION, stampSchedule, stampsDrawn, tallyCues, tallyFinals, tallySteps, validateClaims, validateFactcheck, } from "./factcheck.mjs"; -import { deckSchedule, stampGeometry } from "./deck.mjs"; +import { cueTime, deckSchedule, stampGeometry } from "./deck.mjs"; import { deckHtml } from "./chrome-deck.mjs"; import { stampCues, stampHtml } from "./chrome-stamp.mjs"; @@ -168,7 +168,7 @@ test("stamp:false: counted in the tally, not drawn; a cut whose every claim is h assert.equal(drawnStamps(sched.factcheck.stamps).length, 1); const { cues } = stampCues(sched); assert.ok(cues.every((c) => /st0|fl0/.test(c.k))); - assert.ok(cues.some((c) => c.at === 9.72 && c.k === "st0"), "the drawn one is stamp 0"); + assert.ok(cues.some((c) => c.at === cueTime(Math.round(9.72 * 30) / 30, 30) && c.k === "st0"), "the drawn one is stamp 0"); assert.equal(tallySteps(sched.factcheck.stamps).at(-1).count, 2); assert.equal(stampsDrawn(sched, RENDER), true); const none = { ...sched, factcheck: { stamps: [ST("a", "PARTLY", 5, { stamp: false })] } }; diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -31,7 +31,7 @@ // and the crossfade -- so the build writes the schedule and this reads it. // Recomputing it here would be a second implementation of segmentOffsets() and // would drift the first time the transition changed. -import { copyFile, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { copyFile, link, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; import path from "node:path"; @@ -40,7 +40,7 @@ import { ledgerTotals, dateKey } from "./ledger-totals.mjs"; import { selectVariant } from "./build-video.mjs"; import { ensureWriteDir } from "../lib/report/storage.mjs"; import { - chromeCacheKey, deckLayout, frameCount, hyperframesCommand, postWindows, resolveDeck, sha256, teaserSeconds, transitionOf, + chromeCacheKey, deckLayout, frameCount, pageDuration, hyperframesCommand, postWindows, resolveDeck, sha256, teaserSeconds, transitionOf, validateTeaser, } from "./deck.mjs"; import { deckHtml, GSAP_FILE } from "./chrome-deck.mjs"; @@ -53,6 +53,7 @@ import { flipsHtml } from "./chrome-flips.mjs"; import { statsHtml } from "./chrome-stats.mjs"; import { finaleHtml, finaleLayout } from "./chrome-finale.mjs"; import { fxGeometry } from "./deck.mjs"; +import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; const run = promisify(execFile); @@ -1054,9 +1055,9 @@ export async function composeChrome({ const hf = hyperframesCommand(process.env); let key = null; let frames = null; + const assets = []; if (keyed) { frames = frameCount(size.duration, rate); - const assets = []; for (const name of (await readdir(assetsDir)).sort()) { assets.push([name, sha256(await readFile(path.join(assetsDir, name)))]); } @@ -1092,11 +1093,28 @@ export async function composeChrome({ : path.join(base, "chrome", `${stem}.${format}`); const keyFile = path.join(target, ".key"); + // Each frame's key (frame-keys.mjs), for a whole-cut page it models: a + // render that is not cached whole captures only the frames no render on + // disk has drawn. + const fk = keyed && sequence && ((wholeCut && !windowed) || region === "finale") && !preview && FRAME_KEY_REGIONS[region] + ? frameKeys({ html, region, assets, fps: rate, frames, version: hf.version }) + : null; if (keyed && sequence) { const onDisk = await readFile(keyFile, "utf8").then((s) => s.trim(), () => null); if (onDisk === key && (await framesOnDisk(target)) === frames) { + // Cached whole. A render from before frame keys gains them here, so the + // next change can reuse its frames. + if (fk && !(await readFile(path.join(target, FRAME_KEYS_FILE), "utf8").catch(() => null))) { + await writeFrameKeys(target, fk); + } return { ...result, frames: target, cached: true }; } + if (fk) { + const r = await reuseFrames({ + base, target, stem, fk, key, html, region, rate, hf, workers, quality, assetsDir, + }); + if (r) return { ...result, frames: target, ...r }; + } // Stale frames past the new count would be overlaid as the tail of the cut. await rm(target, { recursive: true, force: true }); } @@ -1118,9 +1136,170 @@ export async function composeChrome({ if (got !== frames) { throw new Error(`the ${region} render wrote ${got} frames to ${target}, expected ${frames} (${size.duration}s at ${rate} fps)`); } + if (fk) await writeFrameKeys(target, fk); await writeFile(keyFile, key + "\n", "utf8"); } - return { ...result, frames: target }; + return { ...result, frames: target, ...(fk ? { reused: 0, captured: frames } : {}) }; +} + +// ---- frame reuse (frame-keys.mjs) -------------------------------------------- + +/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1. */ +export const FRAME_KEYS_FILE = ".frame-keys"; + +const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`; + +async function writeFrameKeys(dir, fk) { + const tmp = path.join(dir, `${FRAME_KEYS_FILE}.${process.pid}.tmp`); + await writeFile(tmp, fk.join("\n") + "\n", "utf8"); + await rename(tmp, path.join(dir, FRAME_KEYS_FILE)); +} + +/** + * Runs of a sorted list of cut frames (0-based): `[renderFrame, cutFrame, length]`, + * the render's frames in order, each run consecutive in the cut. + */ +export function frameRuns(list) { + const runs = []; + list.forEach((n, j) => { + const last = runs[runs.length - 1]; + if (last && last[1] + last[2] === n) last[2] += 1; + else runs.push([j, n, 1]); + }); + return runs; +} + +/** + * The page that renders only some of the cut's frames: its timeline is swapped, + * where the page registers it, for one that plays each run of `runs` + * (frameRuns') as a piece of the cut's timeline in turn -- the windowed + * render's own tween, once per run -- and the page declares their length. + * null when the page does not register its timeline the one way this knows. + */ +export function frameListHtml(html, region, runs, fps) { + const reg = `window.__timelines["${region}"] = tl;`; + const first = html.indexOf(reg); + if (first < 0 || html.indexOf(reg, first + 1) >= 0) return null; + const spec = FRAME_KEY_REGIONS[region]; + const dataTag = `<script id="${spec.data}" type="application/json">`; + if (html.indexOf(dataTag) < 0) return null; + const count = runs.reduce((n, r) => n + r[2], 0); + const helper = + `<script>window.__hfFrames = function (inner) {\n` + + ` const R = ${JSON.stringify(runs)}, fps = ${Number(fps)};\n` + + ` const tl = gsap.timeline({ paused: true });\n` + + ` for (const [j, n, len] of R) tl.add(inner.tweenFromTo(n / fps, (n + len) / fps, { duration: len / fps, ease: "none" }), j / fps);\n` + + ` return tl;\n` + + `};</script>\n `; + return html + .replace(reg, `window.__timelines["${region}"] = window.__hfFrames(tl);`) + .replace(dataTag, helper + dataTag) + .replace(/data-duration="[^"]*"/g, `data-duration="${pageDuration(count / fps, fps)}"`); +} + +/** + * A layer re-rendered by its frames: every frame whose key a render on disk + * has (this layer's last, or the ones `take --from` linked beside it, + * `work-from[-own]-<stem>-frames`) is that frame, hard-linked; the others are + * captured in ONE render of the frame-list page (each new key once) and the + * sequence is assembled beside, then swapped in with its `.frame-keys` and, + * last, its `.key`. null when nothing on disk has frame keys or nearly every + * frame is new (the whole render is the cheaper one then). + */ +async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, workers, quality, assetsDir }) { + const chrome = path.join(base, "chrome"); + const candidates = [target, path.join(chrome, `work-from-${stem}-frames`), path.join(chrome, `work-from-own-${stem}-frames`)]; + // Every frame on disk, by key: `occ` holds each key's frames as ids + // (source × 1e7 + frame index), ascending. + const dirs = []; + const keysOf = []; + const occ = new Map(); + const have = new Map(); + for (const dir of candidates) { + const keys = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").then((t) => t.split("\n").filter(Boolean), () => null); + if (!keys || (await framesOnDisk(dir)) !== keys.length) continue; + const d = dirs.length; + dirs.push(dir); + keysOf.push(keys); + keys.forEach((k, i) => { + if (!occ.has(k)) occ.set(k, []); + occ.get(k).push(d * 1e7 + i); + if (!have.has(k)) have.set(k, true); + }); + } + if (!dirs.length) return null; + const missing = []; + for (let i = 0; i < fk.length; i += 1) if (!have.has(fk[i])) missing.push(i); + if (missing.length > fk.length * 0.9) return null; + + // One capture per new key. + const seen = new Set(); + const capture = missing.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true))); + const capDir = path.join(chrome, `work-capture-${stem}-frames`); + const capProj = path.join(chrome, `work-capture-${stem}`); + if (capture.length) { + const page = frameListHtml(html, region, frameRuns(capture), rate); + if (!page) return null; + await rm(capProj, { recursive: true, force: true }); + await mkdir(path.join(capProj, "assets"), { recursive: true }); + for (const name of await readdir(assetsDir)) await copyFile(path.join(assetsDir, name), path.join(capProj, "assets", name)); + await writeFile(path.join(capProj, "index.html"), page, "utf8"); + await writeFile(path.join(capProj, "hyperframes.json"), HF_JSON + "\n", "utf8"); + await rm(capDir, { recursive: true, force: true }); + await runRenderer(hf.cmd, [ + ...hf.args, "render", "--format", "png-sequence", "--quality", quality, "--fps", String(rate), + ...(workers != null ? ["-w", String(workers)] : []), "--no-browser-gpu", "--output", capDir, capProj, + ]); + const got = await framesOnDisk(capDir); + if (got !== capture.length) throw new Error(`the ${region} frame capture wrote ${got} frames to ${capDir}, expected ${capture.length}`); + capture.forEach((i, j) => have.set(fk[i], path.join(capDir, frameName(j + 1)))); + } + + // Which frame on disk each frame is. One key is often drawn by many frames + // (a still stretch), and the renderer's workers draw it a hair differently + // (measured: a few pixels, a few levels), so taking any one of them for all + // would change the bytes of frames that did not change -- and every chunk + // of the final encode over them. So a run of frames follows the run it + // came from: the frame after the one the last frame took, when it is of + // the same key; else the frame of this key nearest that place. + // (`off`: where the last frame taken sat against this one, kept across a + // captured frame, so a run resumes where it left off.) + const pick = new Array(fk.length); + let off = 0; + for (let i = 0; i < fk.length; i += 1) { + const list = occ.get(fk[i]); + let g = -1; + if (list) { + const want = i + off; + const d = Math.floor(want / 1e7), n = want % 1e7; + if (want >= 0 && keysOf[d]?.[n] === fk[i]) g = want; + else { + let lo = 0, hi = list.length - 1; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (list[mid] < want) lo = mid + 1; + else hi = mid; + } + g = list[lo]; + if (lo > 0 && Math.abs(list[lo - 1] - want) <= Math.abs(g - want)) g = list[lo - 1]; + } + } + pick[i] = g >= 0 ? path.join(dirs[Math.floor(g / 1e7)], frameName((g % 1e7) + 1)) : have.get(fk[i]); + if (g >= 0) off = g - i; + } + + const next = path.join(chrome, `work-next-${stem}-frames`); + await rm(next, { recursive: true, force: true }); + await mkdir(next, { recursive: true }); + for (let i = 0; i < fk.length; i += 1) await link(pick[i], path.join(next, frameName(i + 1))); + await writeFrameKeys(next, fk); + await writeFile(path.join(next, ".key"), key + "\n", "utf8"); + const old = path.join(chrome, `work-old-${stem}-frames`); + await rm(old, { recursive: true, force: true }); + await rename(target, old).catch((e) => { if (e?.code !== "ENOENT") throw e; }); + await rename(next, target); + for (const d of [old, capDir, capProj, ...candidates.slice(1)]) await rm(d, { recursive: true, force: true }); + return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: missing.length - capture.length }; } if (import.meta.url === `file://${process.argv[1]}`) { diff --git a/umtool/report-to-video/deck-claims.test.mjs b/umtool/report-to-video/deck-claims.test.mjs @@ -333,7 +333,13 @@ test("absent claims: the schedule, the deck's page and the finale's are byte-ide const BEFORE = { schedule: "3a6c6abc6f5d4c095333dbbbe7c85aef", - deck: "4966f5f6904d7c91e8c3bd64b16763b8", - finale: "e4cb165d4e3b816c0d648240cac91eb1", + // Re-pinned on lane/fast-rerender: the deck's cue times moved onto the + // sub-frame grid (deck.mjs CUE_GRID) and nothing else -- checked on the + // Huck cut's 1,539 deck cues against main: the same elements, values, + // eases and durations, every time within 4 ms. (Was 4966f5f6904d7c91e8c3bd64b16763b8.) + deck: "d56d6f45c667dea15c0fec5675dbcc95", + // Likewise the finale's (its 181 cues on the Huck cut: times within 2 ms, + // its window's start on the grid). Was e4cb165d4e3b816c0d648240cac91eb1. + finale: "afc1b75858e0c19a73e3d9549bc1f474", built: "c6a44e98fce846811cbf87d449e6b40d", }; diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -3075,6 +3075,37 @@ export function chromeCacheKey({ html, assets = [], fps, frames, version }) { return sha256(JSON.stringify({ v: 1, html: sha256(html), assets: sorted, fps, frames, version })); } +/** + * The sub-frame grid chrome cue times sit on: CUE_GRID steps a frame. A cue + * time is a segment's start (a whole frame) plus a choreography offset; on + * this grid, a cut whose earlier segments grew by m frames moves every later + * cue by exactly 8m steps, so a moved moment draws exactly what it drew -- + * which is what lets a frame of the old render stand for it (frame-keys.mjs). + * Rounded to 4 decimals instead, the same moment moved by m frames plus up to + * 0.05 ms, and a wipe or the marker in flight drew a hair elsewhere. + */ +export const CUE_GRID = 8; +/** A cue time on the grid (nearest step). */ +export const cueTime = (v, fps) => Math.round(v * fps * CUE_GRID) / (fps * CUE_GRID); +/** A cue time on the grid, never before `v` (a clamp to when an element is free). */ +export const cueTimeAfter = (v, fps) => Math.ceil(v * fps * CUE_GRID - 1e-6) / (fps * CUE_GRID); + +/** + * The fact-check stamps with their seconds on the cut's frames. A stamp's + * seconds are its segment's start plus where in the clip its claim falls, + * stored to the millisecond -- so the same stamp in a cut moved by m frames + * is m frames plus up to a millisecond later, which on the sub-frame grid + * (cueTime) lands a step off one time in four. On whole frames, it lands on + * the same frame of its clip but once in thirty, and a stamp's look is + * unchanged to within half a frame. + */ +export const stampsOnFrames = (stamps, fps) => (stamps ?? []).map((s) => ({ + ...s, + ...(Number.isFinite(s.at) ? { at: Math.round(s.at * fps) / fps } : {}), + ...(Number.isFinite(s.landed) ? { landed: Math.round(s.landed * fps) / fps } : {}), + ...(Array.isArray(s.out) ? { out: s.out.map((v) => Math.round(v * fps) / fps) } : {}), +})); + /** Frames a render of `total` seconds at `fps` produces. */ export const frameCount = (total, fps) => Math.round(total * fps); diff --git a/umtool/report-to-video/factcheck.test.mjs b/umtool/report-to-video/factcheck.test.mjs @@ -20,6 +20,7 @@ import { import { deckGeometry, deckLayout, deckQrUrl, deckSchedule, DECK_DEFAULTS, estimateSchedule, feedGeometry, stampGeometry, validateChrome, + cueTime, } from "./deck.mjs"; import { deckCues, deckHtml } from "./chrome-deck.mjs"; import { STAMP_POSE, stampCues, stampHtml } from "./chrome-stamp.mjs"; @@ -286,20 +287,20 @@ test("tally.showAt first: a cell is hidden until its first stamp lands, pops in // Its one appearance: the pop, at the second its first stamp lands, and nothing hides it again. const own = cues.filter((c) => c.k === k); assert.equal(own.length, 1, `${k}: ${JSON.stringify(own)}`); - assert.equal(own[0].at, firstLanding(v)); + assert.equal(own[0].at, cueTime(Math.round(firstLanding(v) * 30) / 30, 30)); assert.deepEqual(own[0].from, { autoAlpha: 0, scale: TALLY_POP.from }); assert.deepEqual(own[0].to, { autoAlpha: 1, scale: 1 }); assert.equal(own[0].dur, TALLY_POP.seconds); assert.equal(own[0].ease, TALLY_POP.ease); // It arrives reading its first count, and the flash fires with it. const n1 = cues.filter((c) => c.k === `${k}.n1`); - assert.equal(n1[0].at, firstLanding(v)); + assert.equal(n1[0].at, cueTime(Math.round(firstLanding(v) * 30) / 30, 30)); assert.deepEqual(n1[0].to, { yPercent: 0, autoAlpha: 1 }); - assert.ok(cues.some((c) => c.k === `${k}.flash` && c.at === firstLanding(v) && c.to.opacity === 1)); + assert.ok(cues.some((c) => c.k === `${k}.flash` && c.at === cueTime(Math.round(firstLanding(v) * 30) / 30, 30) && c.to.opacity === 1)); assert.ok(!cues.some((c) => c.k === `${k}.n0`), "the 0 is never rolled"); } // PARTLY's second step rolls as ever: 1 out, 2 in, at its landing. - const second = stamps.filter((x) => x.verdict === "PARTLY").map((x) => x.landed).sort((a, b) => a - b)[1]; + const second = cueTime(Math.round(stamps.filter((x) => x.verdict === "PARTLY").map((x) => x.landed).sort((a, b) => a - b)[1] * 30) / 30, 30); assert.ok(cues.some((c) => c.k === "ty.PARTLY.n1" && c.at === second && c.to.autoAlpha === 0)); assert.ok(cues.some((c) => c.k === "ty.PARTLY.n2" && c.at === second && c.to.autoAlpha === 1)); // Every cue still states the from the one before it left. @@ -341,14 +342,17 @@ test("stampCues: each stamp slams in to land at its `landed`, flashes, and leave assert.deepEqual(init.st0, { autoAlpha: 0, scale: STAMP_POSE.scale, rotation: STAMP_POSE.from }); const of = (k) => cues.filter((c) => c.k === k); const [slam, leave] = of("st0"); - near(slam.at, 16, "slam starts"); - near(slam.at + slam.dur, 16.28, "lands"); + // A stamp's seconds are on the cut's frames (deck.mjs stampsOnFrames): within half a frame. + const nearF = (a, b, msg) => assert.ok(Math.abs(a - b) <= 1 / 60 + 1e-6, `${msg}: ${a} != ${b}`); + nearF(slam.at, 16, "slam starts"); + nearF(slam.at + slam.dur, 16.28, "lands"); assert.deepEqual(slam.to, { autoAlpha: 1, scale: 1, rotation: STAMP_POSE.rest }); - near(leave.at, 19, "leaves"); - near(leave.dur, 0.5, "over the dissolve"); + nearF(leave.at, 19, "leaves"); + nearF(leave.dur, 0.5, "over the dissolve"); assert.deepEqual(leave.from, { autoAlpha: 1, scale: 1 }); - near(of("fl0")[0].at, 16.28, "flash at landing"); - near(of("fl0")[1].at, 16.28 + STAMP_MOTION.flashUp, "flash down"); + nearF(of("fl0")[0].at, 16.28, "flash at landing"); + // Cue times sit on the sub-frame grid (deck.mjs cueTime): within half a step. + nearF(of("fl0")[1].at, 16.28 + STAMP_MOTION.flashUp, "flash down"); assert.equal(cues.filter((c) => c.k.startsWith("st")).length, 6); }); diff --git a/umtool/report-to-video/finale.test.mjs b/umtool/report-to-video/finale.test.mjs @@ -8,7 +8,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { deckChoreography, deckSchedule, estimateSchedule, validateChrome } from "./deck.mjs"; +import { cueTime, deckChoreography, deckSchedule, estimateSchedule, validateChrome } from "./deck.mjs"; import { deckHtml } from "./chrome-deck.mjs"; import { finaleCues, finaleHtml, finaleLayout } from "./chrome-finale.mjs"; import { @@ -192,7 +192,7 @@ test("the page: the large rail, the totals at their final counts, the stats, the assert.ok(cues.every((c) => Object.keys(c.to).every((p) => p in c.from))); const hole = cues.find((c) => c.k === "hole"); assert.equal(hole.ease, "smoothstep"); - assert.equal(hole.at, s.finale.at); + assert.equal(hole.at, cueTime(s.finale.at, 30), "on the cue grid (deck.mjs cueTime)"); assert.equal(hole.dur, FINALE_MOTION.grow); // The region: the whole frame, a window from `at` to the end. const reg = finaleRegions(r, "/tmp/x", s)[0]; diff --git a/umtool/report-to-video/frame-keys.mjs b/umtool/report-to-video/frame-keys.mjs @@ -0,0 +1,324 @@ +// CHROME FRAME KEYS: what each frame of a cue-driven chrome page draws, as a +// key, computed without a browser -- so a re-render captures only the frames +// whose key is new and takes every other from a render already on disk. +// +// The deck and the fact-check stamps are each ONE page whose script is a dumb +// interpreter of a cue list (chrome-deck.mjs explains why): `init` states +// every element's properties at t = 0, and every cue is a GSAP fromTo whose +// FROM is stated -- the value the cue before it on that element left. So what +// a frame at time t draws is a pure function of +// +// - the page itself, less the cue list (its markup, styles, fonts, assets: +// the STATIC part), and +// - each element's property values at t: init's, the last finished cue's +// `to`, or a running cue's value at its progress. +// +// A frame's key hashes both. The running values are computed the way GSAP +// renders them: its own ease functions (the vendored gsap.min.js, run in a +// sandbox), `from + (to - from) * ease(progress)`, rounded as its CSS plugin +// rounds (four decimals) -- so two frames with one key set the very same CSS. +// Times in the key are the cue's OWN (t - at), never the cut's: a moment the +// cut moved (an insert, a longer intro) keys as it did, because the cue +// times sit on the sub-frame grid (deck.mjs cueTime) and move exactly. +// +// The static part leaves out what only times the page or reaches a preview: +// the cue list and init (keyed per frame), the window (only ever the whole +// cut's [0, total]: a real window is refused), the cut's total and +// the ids list (preview messages), and every `data-duration` (each the whole +// page's; checked). Anything else in the page's data stays in. +// +// Refused -- `null`, and the layer is rendered whole as before -- when the +// page is not one this models: no data script, a `data-duration` that is not +// the page's, a window, a cue whose FROM is not what its element holds, two +// cues running on one property at once, or a property value that is neither +// a number nor a string. Conservative by construction: a frame is reused +// only when everything this knows of it is the same. +// +// Plain node; every path is a parameter. + +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import vm from "node:vm"; + +import { GSAP_FILE } from "./chrome-deck.mjs"; +import { feedCues } from "./chrome-feed.mjs"; + +/** Bumped when what a frame key covers changes: every frame is captured once more. */ +export const FRAME_KEY_VERSION = 1; + +/** The regions whose pages this models, and the data fields their key leaves out of the static part. */ +export const FRAME_KEY_REGIONS = Object.freeze({ + deck: { data: "deck-data", omit: ["init", "cues", "window", "total", "ids"] }, + stamp: { data: "stamp-data", omit: ["init", "cues", "window", "total", "ids"] }, + // The feed plans its cues IN the page, from the heights its cards measure + // (chrome-feed.mjs): keyed by its EVENTS instead (feedFrameKeys). + feed: { data: "feed-data", omit: ["window", "total", "ids", "posts", "visibility"], events: true }, + // The finale is a window of the cut by design: its frame n is cut time + // `from` + n / fps, and its one ease of its own is the page's smoothstep. + finale: { + data: "finale-data", omit: ["init", "cues", "from", "dur"], offset: "from", + eases: { smoothstep: { page: "const EASES = { smoothstep: (p) => p * p * (3 - 2 * p) };", fn: (p) => p * p * (3 - 2 * p) } }, + }, +}); + +/** + * How long after a feed event (a post in, the column hidden or shown) its + * cues can still run, at most: FEED_MOTION's longest chain is under two + * seconds. Checked per page (feedFrameKeys) against the plan itself. + */ +export const FEED_EVENT_CAP = 12; + +let gsapEase = null; +/** GSAP's own ease, by name (the vendored file, in a sandbox, once). */ +export function easeOf(name) { + if (!gsapEase) { + const sandbox = { console, setTimeout, clearTimeout }; + sandbox.self = sandbox; + vm.createContext(sandbox); + vm.runInContext(readFileSync(GSAP_FILE, "utf8"), sandbox, { filename: "gsap.min.js" }); + const g = sandbox.window?.gsap ?? sandbox.gsap; + if (!g?.parseEase) throw new Error("frame keys: the vendored GSAP did not load"); + const cache = new Map(); + gsapEase = (n) => { + if (!cache.has(n)) cache.set(n, g.parseEase(n)); + return cache.get(n); + }; + } + const f = gsapEase(name); + if (typeof f !== "function") throw new Error(`frame keys: no ease ${name}`); + return f; +} + +/** GSAP's CSS rounding (CSSPlugin: four decimals). */ +const gsapRound = (v) => Math.round(v * 10000) / 10000; + +const sha1 = (s) => createHash("sha1").update(s).digest(); + +/** The page's data script: its JSON, and the page with that JSON cut out. */ +function splitData(html, id) { + const open = `<script id="${id}" type="application/json">`; + const at = html.indexOf(open); + if (at < 0 || html.indexOf(open, at + 1) >= 0) return null; + const from = at + open.length; + const to = html.indexOf("</script>", from); + if (to < 0) return null; + let data; + try { + data = JSON.parse(html.slice(from, to)); + } catch { + return null; + } + return { data, before: html.slice(0, from), after: html.slice(to) }; +} + +/** + * The static part's key: the page less what is keyed per frame, the assets' + * hashes, the frame rate and the renderer. null when the page is not modelled. + */ +export function staticKey({ html, region, assets = [], fps, version, frames = null }) { + const spec = FRAME_KEY_REGIONS[region]; + if (!spec) return null; + const parts = splitData(html, spec.data); + if (!parts) return null; + const { data } = parts; + // A window is refused -- but not the whole cut written as one (a total off + // the 4-decimal grid makes deckHtml "window" [0, r4(total)]: the identity). + if (data.window && !(data.window.from === 0 && frames != null && Math.abs(data.window.dur - frames / fps) < 1 / fps)) return null; + if (spec.events ? !(Array.isArray(data.posts) && Array.isArray(data.visibility) && data.grid > 0) : !data.init || !Array.isArray(data.cues)) return null; + if (spec.offset && !Number.isFinite(data[spec.offset])) return null; + // A page's own eases are modelled only as the page writes them. + for (const e of Object.values(spec.eases ?? {})) if (!html.includes(e.page)) return null; + // Every data-duration is the page's own (the root and its one clip). + const durs = [...html.matchAll(/data-duration="([^"]*)"/g)].map((m) => m[1]); + if (!durs.length || durs.some((d) => d !== durs[0])) return null; + const starts = [...html.matchAll(/data-start="([^"]*)"/g)].map((m) => m[1]); + if (starts.some((s) => s !== "0")) return null; + const rest = Object.fromEntries(Object.entries(data).filter(([k]) => !spec.omit.includes(k))); + const page = (parts.before + JSON.stringify(rest) + parts.after).replace(/data-duration="[^"]*"/g, 'data-duration=""'); + const sorted = [...assets].map(([n, h]) => [String(n), String(h)]).sort((x, y) => x[0].localeCompare(y[0])); + return createHash("sha256") + .update(JSON.stringify({ v: FRAME_KEY_VERSION, region, page, assets: sorted, fps, version })) + .digest("hex"); +} + +const repr = (v) => (typeof v === "number" ? `n${gsapRound(v)}` : `s${JSON.stringify(v)}`); + +/** + * Every frame's key, `frames` frames at `fps` (frame n at n / fps), or null + * when the page is not modelled (see the top of the file). + * + * @returns {string[] | null} hex keys, frame 1 first + */ +export function frameKeys({ html, region, assets = [], fps, frames, version }) { + const sk = staticKey({ html, region, assets, fps, version, frames }); + if (!sk) return null; + if (FRAME_KEY_REGIONS[region].events) return feedFrameKeys({ html, sk, fps, frames }); + const spec = FRAME_KEY_REGIONS[region]; + const { data } = splitData(html, spec.data); + const init = data.init; + const cues = data.cues; + const t0 = spec.offset ? Number(data[spec.offset]) : 0; + const ease = (name) => spec.eases?.[name]?.fn ?? easeOf(name); + + // Slots: one per (element, property), each with its cues in time order. + const slots = new Map(); + const slot = (k, p) => { + const id = `${k}\u0000${p}`; + let s = slots.get(id); + if (!s) { + s = { id, k, p, initial: init[k] && p in init[k] ? init[k][p] : undefined, cues: [] }; + slots.set(id, s); + } + return s; + }; + for (const [k, props] of Object.entries(init)) for (const p of Object.keys(props)) slot(k, p); + cues.forEach((c, n) => { + if (!c || typeof c.k !== "string" || !(c.dur > 0) || !Number.isFinite(c.at)) throw new Error(`frame keys: cue ${n} is malformed`); + for (const p of Object.keys(c.to ?? {})) slot(c.k, p).cues.push({ ...c, n }); + }); + + // The model's checks: every FROM is what its element holds, no two cues + // run on one property at once, every value a number or a string. + const okValue = (v) => typeof v === "number" || typeof v === "string" || v === undefined; + for (const s of slots.values()) { + s.cues.sort((x, y) => x.at - y.at || x.n - y.n); + let held = s.initial; + let freeAt = -Infinity; + for (const c of s.cues) { + const from = c.from?.[s.p]; + const to = c.to[s.p]; + if (!okValue(from) || !okValue(to) || !okValue(held)) return null; + // (Nothing held -- the CSS default -- takes the from the page states for it.) + if (held !== undefined && from !== held) return null; + if (c.at < freeAt - 1e-9) return null; + held = to; + freeAt = c.at + c.dur; + } + } + + // The value of a slot at time t, as GSAP draws it. + const valueAt = (s, t) => { + let cur = null; + for (const c of s.cues) { + if (c.at <= t + 1e-9) cur = c; + else break; + } + if (!cur) return s.initial === undefined ? "u" : `i${repr(s.initial)}`; + const from = cur.from?.[s.p]; + const to = cur.to[s.p]; + const end = cur.at + cur.dur; + if (t >= end - 1e-9) return `e${repr(to)}`; + const u = Math.max(0, (t - cur.at) / cur.dur); + if (typeof from === "number" && typeof to === "number") { + return `r${gsapRound(from + (to - from) * ease(cur.ease)(u))}`; + } + // A string that does not change (a transformOrigin restated) is that string. + if (from === to) return `e${repr(to)}`; + // A string in flight: the cue and its own clock, to the microsecond. + return `x${JSON.stringify([from, to, cur.ease, cur.dur])}@${(t - cur.at).toFixed(6)}`; + }; + + // The state's hash: XOR over the slots of each slot's (id, value) hash, + // updated only where a value moves. Each slot's changes come from its own + // cue boundaries (a step) or a running cue (every frame). + const acc = Buffer.alloc(20); + const xor = (b) => { + for (let i = 0; i < 20; i += 1) acc[i] ^= b[i]; + }; + const cur = new Map(); + for (const s of slots.values()) { + const v = valueAt(s, t0); + cur.set(s.id, v); + xor(sha1(`${s.id}\u0001${v}`)); + } + // Per frame, the slots that may move: those with a cue starting by it or running at it. + const frameOf = (t) => Math.ceil((t - t0) * fps - 1e-6); + const touch = new Map(); // frame -> slots + const push = (f, s) => { + if (f < 0 || f >= frames) return; + let l = touch.get(f); + if (!l) touch.set(f, (l = new Set())); + l.add(s); + }; + for (const s of slots.values()) { + for (const c of s.cues) { + const f0 = Math.max(0, frameOf(c.at)); + const f1 = Math.min(frames - 1, frameOf(c.at + c.dur)); + for (let f = f0; f <= f1; f += 1) push(f, s); + } + } + const out = new Array(frames); + for (let f = 0; f < frames; f += 1) { + const t = t0 + f / fps; + for (const s of touch.get(f) ?? []) { + const v = valueAt(s, t); + const was = cur.get(s.id); + if (v === was) continue; + xor(sha1(`${s.id}\u0001${was}`)); + xor(sha1(`${s.id}\u0001${v}`)); + cur.set(s.id, v); + } + out[f] = createHash("sha1").update(sk).update(acc).digest("hex"); + } + return out; +} + +/** + * The feed's frame keys. Its cues are planned in the page from the heights + * its cards measure, so they are not in it; but every cue time is an event's + * time on the cue grid plus a FEED_MOTION constant (feedCues with `grid`), + * and the plan is a function of the page's static part (which fixes the + * heights) and those times. So a frame's key is the static part and, for + * each event, how many grid steps ago it was -- "not yet" when it is to + * come, "settled" once FEED_EVENT_CAP has passed. Refused (null) when the + * page's plan, run here with the shortest and the tallest cards, has a cue + * that runs past the cap after the event before it. + */ +function feedFrameKeys({ html, sk, fps, frames }) { + const { data } = splitData(html, FRAME_KEY_REGIONS.feed.data); + const g = Number(data.grid); + const per = g / fps; + if (!Number.isInteger(per) || per <= 0) return null; + const steps = (v) => Math.round(v * g); + const events = []; + data.posts.forEach((p, j) => { + if (!Number.isFinite(p?.in)) throw new Error(`frame keys: feed post ${j} has no time`); + events.push({ tag: `p${j}`, at: steps(p.in) }); + }); + data.visibility.forEach((v, j) => { + const [a0, a1] = v.at ?? []; + if (!Number.isFinite(a0) || !Number.isFinite(a1)) throw new Error(`frame keys: feed visibility ${j} has no times`); + const skipped = a1 - a0 <= 0 && v.i === 0; + events.push({ tag: `v${j}:${v.i}:${v.hide ? 1 : 0}:${steps(a1) - steps(a0)}:${skipped ? 1 : 0}`, at: steps(a0) }); + }); + const cap = FEED_EVENT_CAP * g; + + // The cap, checked against the plan itself at both extremes of card height. + const M = data.motion ?? {}; + const times = events.map((e) => e.at / g).sort((x, y) => x - y); + for (const h of [1, 1e6]) { + const plan = feedCues({ + posts: data.posts, heights: data.posts.map(() => h), column: data.column, visibility: data.visibility, + startsHidden: data.startsHidden, slideX: data.slideX, enterX: data.enterX, gap: M.gap, push: M.push, + lag: M.lag, enter: M.enter, glowAt: M.glowAt, glowUp: M.glowUp, glowDown: M.glowDown, newest: M.newest, + calm: M.calm, leave: M.leave, grid: g, + }); + for (const c of plan.cues) { + let last = -Infinity; + for (const t of times) if (t <= c.at + 1e-9) last = t; + if (!(c.at + c.dur - last < FEED_EVENT_CAP - 1)) return null; + } + } + + const out = new Array(frames); + for (let f = 0; f < frames; f += 1) { + const t = f * per; + let sig = ""; + for (const e of events) { + const d = t - e.at; + sig += `${e.tag}=${d < 0 ? "f" : d >= cap ? "s" : d};`; + } + out[f] = createHash("sha1").update(sk).update(sig).digest("hex"); + } + return out; +} diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs @@ -0,0 +1,278 @@ +// Chrome frame keys (frame-keys.mjs) and compose-chrome's frame reuse: a +// frame's key is the page less its cue list plus every element's value at +// that frame, as GSAP draws it; a cut that moved keys its moved frames as it +// did; a changed value changes exactly the frames it shows in; a page this +// does not model has no keys. Then compose-chrome with the renderer stubbed: +// a re-render after a shift captures only the new keys -- in one frame-list +// render -- and assembles the rest from the old frames. +// +// Run with: node --test umtool/report-to-video/frame-keys.test.mjs +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { deckHtml } from "./chrome-deck.mjs"; +import { easeOf, frameKeys, staticKey } from "./frame-keys.mjs"; +import { stampHtml } from "./chrome-stamp.mjs"; + +const RENDER = { + width: 1920, height: 1080, fps: 30, transition: 0.5, + palette: { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }, + chrome: { engine: "hyperframes", layout: "deck", deck: {} }, +}; +const FONTS = { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf" }; + +/** The chrome-deck fixture, its opening card `grow` seconds longer. */ +function schedule(grow = 0, titles = {}) { + const seg = (id, type, start, duration, extra = {}) => ({ + id, type, start, duration, end: start + duration, + title: titles[id] ?? "", subtitle: "", qrUrl: null, hideDeck: false, ...extra, + }); + const g = grow; + return { + version: 1, kind: "deck", estimated: true, fps: 30, transition: 0.5, total: 40 + g, multiChannel: false, + segments: [ + seg("t00", "card", 0, 5 + g, { title: "Opening", subtitle: "a card", hideDeck: true }), + seg("c01", "clip", 4.5 + g, 10, { title: titles.c01 ?? "He said", subtitle: "Ferret Rescue · Sep 5, 2024" }), + seg("c02", "clip", 14 + g, 8, { title: titles.c02 ?? "A sanctuary", subtitle: "Ferret Rescue · Sep 5, 2024" }), + seg("c03", "clip", 21.5 + g, 13, { subtitle: "Untitled source · Sep 29, 2024" }), + seg("end", "card", 34 + g, 6, { title: "Close", subtitle: "", hideDeck: true }), + ], + }; +} +const keysOf = (s, render = RENDER) => frameKeys({ + html: deckHtml(s, render, { fonts: FONTS }), region: "deck", fps: 30, frames: Math.round(s.total * 30), version: "v", +}); + +test("easeOf: GSAP's own eases", () => { + assert.equal(easeOf("none")(0.3), 0.3); + assert.ok(Math.abs(easeOf("power1.out")(0.5) - 0.75) < 1e-12); + assert.ok(easeOf("back.out(2.2)")(0.6) > 1, "an overshoot"); +}); + +test("frame keys: the moved frames of a longer opening key as they did", () => { + const A = keysOf(schedule(0)); + const B = keysOf(schedule(1 / 3)); // 10 frames longer + assert.equal(A.length, 1200); + assert.equal(B.length, 1210); + // From the end of the first handover on (6 s), every frame is the old one 10 frames on. + let same = 0; + for (let n = 180; n < A.length; n += 1) if (B[n + 10] === A[n]) same += 1; + assert.equal(same, A.length - 180); + // The opening itself is the card's, hidden deck; while it is longer nothing moves either. + assert.equal(new Set(A.slice(0, 100)).size, 1, "a still deck keys as one frame"); + // Frames that differ are not the same key by accident. + assert.notEqual(A[400], A[700]); +}); + +test("frame keys: a cut moved by frames keys as it did when its times are stored to the millisecond", () => { + // The schedule stores seconds to 3 places (deck.mjs): a move of 59 frames + // (not a multiple of 3) moves each start by 59/30 s give or take a millisecond. + const r3 = (v) => Math.round(v * 1000) / 1000; + const at = (introFrames) => { + // Clips of uneven frame counts, so their starts fall on every third of a frame. + const frames = [introFrames, 301, 242, 391, 180]; + const s = schedule(0); + let t = 0; + s.segments = s.segments.map((x, i) => { + const d = frames[i] / 30; + const seg = { ...x, start: r3(t), duration: r3(d), end: r3(t + d) }; + t += d - 0.5; + return seg; + }); + s.total = r3(t + 0.5); + return s; + }; + const A = keysOf(at(160)), B = keysOf(at(160 + 59)); + let same = 0, n = 0; + for (let f = 200; f < A.length; f += 1) { n += 1; if (B[f + 59] === A[f]) same += 1; } + assert.equal(same, n, `${n - same} moved frames keyed differently`); +}); + +test("frame keys: a changed title changes every frame (it is in the page); a changed value only where it shows", () => { + const A = keysOf(schedule(0)); + const T = keysOf(schedule(0, { c02: "Another sanctuary" })); + assert.ok(A.every((k, n) => k !== T[n]), "the page's text is part of every frame's key"); + // The tally steps at its stamp's landing: frames before it are the same, after it not. + const stamped = (landed) => { + const s = schedule(0); + return { + ...s, + segments: s.segments.map((x) => (x.id === "c02" ? { ...x, claim: { id: "k1", verdict: "CORROBORATED" } } : x)), + factcheck: { stamps: [{ claim: "k1", verdict: "CORROBORATED", segment: "c02", at: landed - 0.3, landed, out: [21.5, 22] }] }, + }; + }; + const P = keysOf(stamped(18)); + const Q = keysOf(stamped(19)); + const differ = P.map((k, n) => (k !== Q[n] ? n : null)).filter((n) => n != null); + assert.ok(differ.length > 0); + assert.ok(differ[0] >= 18 * 30 - 1, `nothing differs before the earlier landing (first at ${differ[0]})`); + assert.ok(differ.at(-1) <= 20 * 30, `the counts agree again once both have landed (last at ${differ.at(-1)})`); +}); + +test("frame keys: refused for a page this does not model", () => { + const s = schedule(0); + // A window. + assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS, from: 5, duration: 10 }), region: "deck", fps: 30, frames: 300, version: "v" }), null); + // A region it does not know. + assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS }), region: "feed", fps: 30, frames: 1200, version: "v" }), null); + // A cue whose from is not what its element holds. + const html = deckHtml(s, RENDER, { fonts: FONTS }); + const broken = html.replace(/"from":\{"xPercent":0\}/, '"from":{"xPercent":7}'); + assert.notEqual(broken, html); + assert.equal(frameKeys({ html: broken, region: "deck", fps: 30, frames: 1200, version: "v" }), null); + // The assets, the frame rate and the renderer are in the key. + const k = (o) => staticKey({ html, region: "deck", assets: [["a.png", "1"]], fps: 30, version: "v", ...o }); + assert.notEqual(k({ assets: [["a.png", "2"]] }), k({})); + assert.notEqual(k({ version: "w" }), k({})); + assert.notEqual(k({ fps: 25 }), k({})); +}); + +// ---- compose-chrome's frame reuse, the renderer stubbed -------------------------- + +const STUB = `#!/usr/bin/env node +// A renderer that writes, for each frame, the cut frame it shows and the page's cue list's hash. +import { createHash } from "node:crypto"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +const a = process.argv.slice(2); +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const data = /<script id="[a-z]+-data" type="application\\/json">([\\s\\S]*?)<\\/script>/.exec(html)[1]; +const tag = createHash("md5").update(JSON.stringify(JSON.parse(data).cues)).digest("hex").slice(0, 8); +const runs = /const R = (\\[[^;]*\\]), fps/.exec(html); +const R = runs ? JSON.parse(runs[1]) : null; +const n = Math.round(dur * fps); +mkdirSync(out, { recursive: true }); +for (let j = 0; j < n; j += 1) { + let cut = j; + if (R) { const r = R.find(([j0, , len]) => j >= j0 && j < j0 + len); cut = r[1] + (j - r[0]); } + writeFileSync(out + "/frame_" + String(j + 1).padStart(6, "0") + ".png", tag + ":" + cut); +} +writeFileSync(out + "/../renders.log", (R ? "list " : "whole ") + n + "\\n", { flag: "a" }); +`; + +test("compose-chrome: a shifted stamp layer captures only its new keys, in one render, and reuses the rest", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "frame-reuse-")); + const env = process.env.HYPERFRAMES_BIN; + try { + const stub = path.join(dir, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const font = path.join(dir, "face.ttf"); + writeFileSync(font, "face"); + const render = { ...RENDER, fontRegular: font, fontBold: font }; + const mp = path.join(dir, "video.manifest.json"); + writeFileSync(mp, JSON.stringify({ slug: "f", render, timeline: [] })); + const out = path.join(dir, "out", "sourced"); + mkdirSync(out, { recursive: true }); + const stamps = (g, late = 0) => { + const s = schedule(g); + return { + ...s, + segments: s.segments.map((x) => (x.id === "c02" ? { ...x, claim: { id: "k1", verdict: "PARTLY" } } : x.id === "c03" ? { ...x, claim: { id: "k2", verdict: "CONTRADICTED" } } : x)), + factcheck: { + stamps: [ + { claim: "k1", verdict: "PARTLY", segment: "c02", at: 16 + g, landed: 16.28 + g, out: [21.5 + g, 22 + g] }, + { claim: "k2", verdict: "CONTRADICTED", segment: "c03", at: 25 + g + late, landed: 25.28 + g + late, out: [34 + g, 34.5 + g] }, + ], + }, + }; + }; + const { composeChrome, FRAME_KEYS_FILE } = await import("./compose-chrome.mjs"); + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(stamps(0))); + const first = await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 }); + assert.equal(first.cached, false); + const framesDir = first.frames; + const keys0 = readFileSync(path.join(framesDir, FRAME_KEYS_FILE), "utf8").trim().split("\n"); + const oldTag = readFileSync(path.join(framesDir, "frame_000001.png"), "utf8").split(":")[0]; + assert.equal(keys0.length, 1200); + + // Ten frames longer at the top, and the second stamp landing while the + // first is still up: only the frames with both on screen -- a state no + // frame of the old render drew -- are captured. + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(stamps(1 / 3, -5))); + const second = await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 }); + assert.equal(second.cached, false); + assert.equal(second.frameCount, 1210); + assert.ok(second.reused >= 1100, `${second.reused} reused`); + assert.ok(second.captured > 0 && second.captured <= 60, `${second.captured} captured`); + const keys1 = readFileSync(path.join(framesDir, FRAME_KEYS_FILE), "utf8").trim().split("\n"); + assert.equal(keys1.length, 1210); + const files = readdirSync(framesDir).filter((f) => /^frame_\d+\.png$/.test(f)).sort(); + assert.equal(files.length, 1210); + // Each frame is the old render's frame of the same key, or a fresh capture of this very frame. + files.forEach((f, i) => { + const [tag, cut] = readFileSync(path.join(framesDir, f), "utf8").split(":"); + if (tag === oldTag) assert.equal(keys0[Number(cut)], keys1[i], `frame ${i + 1} reuses old frame ${Number(cut) + 1}, of its key`); + else assert.equal(keys1[Number(cut)], keys1[i], `frame ${i + 1} is the capture of a frame of its key`); + }); + // A still stretch keeps its own frames: the end of the cut, moved 10 + // frames, is the old end frame for frame -- not one frame of its key + // standing in for all (the renderer's workers draw a still a hair apart). + for (let i = 1150; i < 1210; i += 1) { + const [, cut] = readFileSync(path.join(framesDir, files[i]), "utf8").split(":"); + assert.equal(Number(cut), i - 10, `frame ${i + 1} is old frame ${i - 9}`); + } + const log = readFileSync(path.join(out, "chrome", "renders.log"), "utf8").trim().split("\n"); + assert.deepEqual(log[0], "whole 1200"); + assert.match(log[1], /^list \d+$/, "one frame-list render"); + assert.equal(log.length, 2); + // Its scratch is gone; the .key is this page's: the third run is cached whole. + assert.ok(!readdirSync(path.join(out, "chrome")).some((n) => n.startsWith("work-"))); + assert.equal((await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 })).cached, true); + + // A take started --from another keeps the other's frames beside its own + // (takeFrom.mjs: chrome/work-from-<layer>-frames): reused from there too. + const { renameSync } = await import("node:fs"); + renameSync(framesDir, path.join(out, "chrome", "work-from-stamp-frames")); + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(stamps(0))); + const third = await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 }); + assert.equal(third.frameCount, 1200); + assert.ok(third.reused >= 1000 && third.captured < 100, `${third.reused} reused from the other take's, ${third.captured} captured`); + assert.ok(!readdirSync(path.join(out, "chrome")).includes("work-from-stamp-frames"), "the borrowed frames are let go"); + } finally { + if (env === undefined) delete process.env.HYPERFRAMES_BIN; + else process.env.HYPERFRAMES_BIN = env; + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("stampHtml registers its timeline the one way the frame list replaces", () => { + const html = stampHtml({ total: 10, fps: 30, factcheck: { stamps: [{ claim: "a", verdict: "PARTLY", at: 2, landed: 2.28, out: [5, 5.5] }] } }, RENDER, {}); + assert.equal(html.split('window.__timelines["stamp"] = tl;').length, 2); + assert.equal(deckHtml(schedule(0), RENDER, { fonts: FONTS }).split('window.__timelines["deck"] = tl;').length, 2); +}); + +test("feed frame keys: by its events; a moved post keys as it did, a changed one where it shows", async () => { + const { feedHtml } = await import("./chrome-feed.mjs"); + const { deckSchedule } = await import("./deck.mjs"); + const FEED = { ...RENDER, chrome: { engine: "hyperframes", layout: "deck", deck: { posts: { layout: "feed" } } } }; + const CLIPS = [ + { id: "c1", type: "clip", video: "a", start: 0, end: 10, date: "2024-09-05" }, + { id: "c2", type: "clip", video: "b", start: 0, end: 20, date: "2024-10-01" }, + { id: "k1", type: "card", seconds: 4 }, + { id: "c3", type: "clip", video: "c", start: 0, end: 6, date: "2025-12-08" }, + ]; + const POST = (id, date) => ({ id, platform: "bluesky", author: "P", handle: "p.live", date, text: `words of ${id}`, url: `https://bsky.app/profile/p.live/post/${id}` }); + const POSTS = [POST("a", "2024-10-19"), POST("b", "2024-11-27"), POST("c", "2024-12-01"), POST("z", "2026-01-22")]; + const keys = (durs) => { + const s = deckSchedule({ entries: CLIPS, durs, D: 0.5, render: FEED, provenance: { siteOrigin: "https://x.test", channelSlug: "c" }, posts: POSTS }); + const html = feedHtml(s, FEED, { fonts: FONTS }); + return { s, k: frameKeys({ html, region: "feed", fps: 30, frames: Math.round(s.total * 30), version: "v" }) }; + }; + const A = keys([10, 20, 4, 6]); + const B = keys([10 + 1 / 3, 20, 4, 6]); + assert.ok(A.k && B.k, "the feed is modelled"); + const firstIn = A.s.posts?.[0]?.in ?? 9.5; + let same = 0, n = 0; + for (let f = Math.ceil((firstIn + 1) * 30); f < A.k.length; f += 1) { n += 1; if (B.k[f + 10] === A.k[f]) same += 1; } + assert.equal(same, n, "every moved frame keys as it did"); + // The second clip 1 s longer: frames before its posts' times are the same, later ones moved. + const C = keys([10, 21, 4, 6]); + assert.equal(C.k[200], A.k[200]); +}); 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 }));