Archilyzer · Source

archilyzer

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

commit 2187ae28455faebfbc710830461457a7c3eb7a47
parent 2922a46d8eb4383527a72c680be35f920473df69
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 14:48:59 -0500

umtool: the deck is drawn only where a chunk to encode reads it -- a take --from a pruned one captures the touched post's frames, not the whole cut's again (mid-6: 11,996 captures, 90 s)

- planChunks: chunkedConcat's plan without encoding (spans, keys, which are
  on disk); framesNeeded: given a sequence's frame keys before its frames,
  the frames the chunks to encode read.
- deckWant: when the deck's shell is the cut's one overlay layer and the
  encode is chunked (hard cuts or crossfades), the build hands the deck's
  capture a `want`; UMTOOL_CHROME_LAZY=0 draws every frame.
- compose-chrome reuseFrames `need`: frames neither on disk nor of a
  captured key nor wanted are left out -- a SPARSE sequence: `.frame-keys`
  whole, `.sparse` ({ key, frames, absent }) in place of `.key`, never cached
  whole, its frames reused by key (a sparse candidate offers what it has).
- prune-frames framesOf/frameKeyOf and the prune record read a sparse
  sequence's length and key from `.sparse` (verify-build passes); takeFrom
  links a sparse layer like a keyed one; chunkedConcat refuses a chunk to
  encode that reads a frame not drawn.
- hardcut-deck.test.mjs: a stubbed deck over three stills -- the same cut
  again draws nothing and encodes nothing; one still a second longer encodes
  its chunk alone and draws the deck only over it.

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

Diffstat:
Mumtool/docs/report-video.md | 5+++--
Mumtool/lib/report/takeFrom.mjs | 11+++++++----
Mumtool/report-to-video/README.md | 11+++++++++++
Mumtool/report-to-video/build-video.mjs | 87++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/chunked-encode.mjs | 15+++++++++++++--
Mumtool/report-to-video/compose-chrome.mjs | 38+++++++++++++++++++++++++++-----------
Mumtool/report-to-video/frame-keys.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/hardcut-deck.test.mjs | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/prune-frames.mjs | 12+++++++++---
9 files changed, 337 insertions(+), 31 deletions(-)

diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1874,8 +1874,9 @@ its final picture is encoded in keyed CHUNKS, one segment's run each (report-to- `chunked-encode.mjs`): a chunk is encoded again only when its segment or the deck frames over it changed. A post that grew or shrank moves every later chunk without changing it -- the deck's frames after it are the same frames, later -- so `--from` the take before re-encodes only the touched -post's chunks. The deck's frames themselves are keyed by what they draw, so a twin of a pruned take -captures them again (about 90 s for a 31-minute cut) and still reuses every chunk. The cut's sound +post's chunks. The deck's frames themselves are keyed by what they draw, and a take draws only the +ones its chunks to encode read: a twin of a pruned take captures the touched post's frames, not the +whole cut's again (about 90 s for a 31-minute cut). `UMTOOL_CHROME_LAZY=0` draws them all. The cut's sound is one pass (about 90 s, begun beside the capture), reused when no segment's sound changed (a caption or a knob that moves no word keeps it). diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -199,14 +199,17 @@ async function linkVariant({ src, dst, kept, from }) { for (const f of ownFiles) if (!theirs.includes(f)) await rm(path.join(segOut, f), { force: true }); } - // The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside. + // The keyed renders: chrome/<layer>-frames, with its .key (or, a sparse + // one -- only the frames its build's chunks read -- its .sparse), else the + // one kept aside. + const marker = async (d) => (await lstat(path.join(d, ".key")).catch(() => null)) ?? (await lstat(path.join(d, ".sparse")).catch(() => null)); const chrome = path.join(src, "chrome"); // Both there: the one whose .key was written last (the other is an older cut's). const layers = new Map(); for (const dir of [chrome, kept]) { for (const f of await names(dir)) { if (!f.endsWith("-frames")) continue; - const key = await lstat(path.join(dir, f, ".key")).catch(() => null); + const key = await marker(path.join(dir, f)); if (!key?.isFile()) continue; const had = layers.get(f); if (!had || key.mtimeMs > had.at) layers.set(f, { dir: path.join(dir, f), at: key.mtimeMs }); @@ -215,8 +218,8 @@ async function linkVariant({ src, dst, kept, from }) { if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true }); for (const [name, { dir, at }] of [...layers].sort((x, y) => x[0].localeCompare(y[0]))) { const mine = path.join(dst, "chrome", name); - const ownKey = await lstat(path.join(mine, ".key")).catch(() => null); - const theirKey = await lstat(path.join(dir, ".key")).catch(() => null); + const ownKey = await marker(mine); + const theirKey = await marker(dir); const same = ownKey && theirKey && ownKey.ino === theirKey.ino && ownKey.dev === theirKey.dev; if (ownKey?.isFile() && !same && ownKey.mtimeMs > at) { // This take's own render is the newer: kept; theirs beside it for frame reuse. diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -1969,6 +1969,17 @@ parsing — wrapping the expression in single quotes is what protects them. picture, end to end, encoded once -- begun beside the deck's capture, and keyed by each segment's SOUND, its audio packets: a fix to a post's picture alone keeps the cut's sound). +- **The deck is drawn only where a chunk to encode reads it** (`deckWant`, + compose-chrome's `want`): when the deck's shell is the cut's one overlay + layer and the encode is chunked, the build plans its chunks from the deck's + frame keys BEFORE the capture (`planChunks`, `framesNeeded`) and the capture + draws only the frames the chunks to encode read. A take `--from` one whose + frames were pruned no longer captures the whole cut again (mid-6: 11,996 + captures, 90 s) to re-encode one post's chunk. The sequence is then SPARSE: + its `.frame-keys` whole, a `.sparse` (`{ key, frames, absent }`) in place of + its `.key`, never "cached whole"; what it has is reused by key, verify-build + and the prune record read its length from `.sparse`, `take --from` links it + like any keyed layer. `UMTOOL_CHROME_LAZY=0` draws every frame. - **A chunk's chrome layers key by their frame keys** when a sequence carries `.frame-keys` (every keyed layer does): what its frames DRAW, not their bytes. A layer captured again after a prune draws "a hair differently" per renderer diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -238,7 +238,7 @@ import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mj import { keepFramesAsked, keptFramesDir, pruneChromeFrames } from "./prune-frames.mjs"; import { encodeSegmentCached, ffmpegIdentity } from "./segment-cache.mjs"; import { - CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, chunkKey, chunkSpans, frameKeysIdentity, framesRead, readFrameKeys, sequenceIdentity, spanSegments, whyRebuilt, + CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, SPARSE_FILE, chunkKey, chunkSpans, frameFile, frameKeysIdentity, framesRead, readFrameKeys, sequenceIdentity, spanSegments, whyRebuilt, } from "./chunked-encode.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. @@ -5212,8 +5212,14 @@ export async function logRebuild(workDir, entry) { * is joined) -- which before this re-encoded the whole cut in one overlay * pass on every build, ~12 minutes for a 31-minute cut. */ -export async function chunkedConcat({ segments, render, outPath, chrome = null, joins = null, workDir, hardCut = false }) { - const t0 = Date.now(); +/** + * The chunked encode's plan, without encoding a frame: every chunk's span, + * key, record and argv, and which of them are on disk (`reused`) and which + * are `todo`. chunkedConcat runs it; so does a build that asks, before the + * deck is captured, which deck frames its chunks to encode will read + * (`frameKeys`: a sequence's frame keys known before its frames are). + */ +export async function planChunks({ segments, render, chrome = null, joins = null, workDir, hardCut = false, frameKeys = null, quiet = false }) { const D = hardCut ? 0 : render.transition ?? 0.5; const fps = render.fps; const { durs, starts, total } = await cutOffsets(segments, D, fps, joins); @@ -5230,7 +5236,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, const prev = await readFile(path.join(dir, CHUNKS_RECORD), "utf8").then((t) => JSON.parse(t), () => null); const prevChunks = Array.isArray(prev?.chunks) ? prev.chunks : []; - EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` }); + if (!quiet) EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` }); const segHash = await memo.hashAll(segments); segHash.forEach((h, i) => { if (!h) throw new Error(`chunked encode: segment ${segments[i]} is not a file`); @@ -5238,7 +5244,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, // Each chrome sequence's frame keys, when it carries them (chunked-encode.mjs): // a chunk then keys by what its frames draw, not by their bytes. - const frameKeysByDir = new Map(); + const frameKeysByDir = new Map(frameKeys ?? []); for (const r of chrome?.regions ?? []) { const count = WINDOW_REGIONS.has(r.name) ? Number(r.frameCount) : N; if (!frameKeysByDir.has(r.frames)) frameKeysByDir.set(r.frames, await readFrameKeys(r.frames, count)); @@ -5269,7 +5275,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, graph: createHash("sha1").update(JSON.stringify(proto.keyArgv)).digest("hex").slice(0, 16), }, }; - plan.push({ span, file, rec, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv }); + plan.push({ span, file, rec, inputs: proto.inputs, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv }); } await memo.save(); @@ -5280,6 +5286,62 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, if (got === p.span.b - p.span.a) p.reused = true; else todo.push(p); } + return { D, fps, durs, starts, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash }; +} + +/** + * The deck's `want` (compose-chrome): draw only the frames the chunked + * encode will read -- a fix `--from` a take whose frames were pruned captures + * the touched post's frames, not the whole cut's (mid-6: 11,996 captures, + * 90 s). Only when the deck's shell is the cut's one overlay layer (another + * layer's frames are in the same chunks' keys, and are captured beside it), + * and the encode is chunked. `UMTOOL_CHROME_LAZY=0` draws every frame. + */ +export function deckWant({ schedule, render, outDir, segments, joins = null, hardCut, env = process.env }) { + if (env.UMTOOL_CHROME_LAZY === "0" || !chunkedEncodeOn(render, env)) return null; + const on = deckOverlays().filter((m) => m.on(schedule, render)); + if (on.length !== 1 || on[0].region !== "deck" || on[0].kind !== "overlay-whole") return null; + const regions = on[0].regions(schedule, { render, outDir }); + const framesDir = regions[0].frames; + return (fk) => framesNeeded({ framesDir, fk, segments, render, chrome: { regions, outLabel: "[hfout]" }, joins, workDir: outDir, hardCut }); +} + +/** + * The frames of chrome sequence `framesDir` the chunks to encode read + * (0-based), when its frame keys are `fk`: what a build asks the capture to + * draw (compose-chrome `want`). Every other frame is in a chunk on disk. + */ +export async function framesNeeded({ framesDir, fk, ...job }) { + const { todo, plan } = await planChunks({ ...job, frameKeys: new Map([[framesDir, fk]]), quiet: true }); + const need = new Set(); + for (const p of todo) { + for (const inp of p.inputs) { + if (inp.kind !== "seq" || inp.dir !== framesDir || !inp.range) continue; + for (let n = inp.range[0]; n <= inp.range[1]; n += 1) need.add(n - 1); + } + } + EMIT("note", { message: `chrome: ${todo.length} of ${plan.length} chunk(s) to encode read ${need.size} of ${fk.length} ${path.basename(framesDir)} frames — only those are drawn` }); + return need; +} + +export async function chunkedConcat({ segments, render, outPath, chrome = null, joins = null, workDir, hardCut = false }) { + const t0 = Date.now(); + const { D, fps, durs, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash } = await planChunks({ segments, render, chrome, joins, workDir, hardCut }); + // A chunk to encode reads every frame it lays: a sparse sequence's absent + // frames are only ever in chunks on disk (framesNeeded), checked here. + const sparse = new Map(); + for (const p of todo) { + for (const inp of p.inputs) { + if (inp.kind !== "seq" || !inp.range) continue; + if (!sparse.has(inp.dir)) sparse.set(inp.dir, await exists(path.join(inp.dir, SPARSE_FILE))); + if (!sparse.get(inp.dir)) continue; + for (let n = inp.range[0]; n <= inp.range[1]; n += 1) { + if (!(await exists(frameFile(inp.dir, n)))) { + throw new Error(`chunked encode: chunk ${p.rec.anchor} reads ${frameFile(inp.dir, n)}, which was not drawn (a sparse ${inp.region} sequence)`); + } + } + } + } const why = new Map(); for (const p of todo) why.set(p, whyRebuilt(p.rec, prevChunks)); const reusedFrames = plan.filter((p) => p.reused).reduce((n, p) => n + (p.span.b - p.span.a), 0); @@ -5544,7 +5606,7 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re * feed's, each posts window's, the stamps', the stats'. * Dynamic import: compose-chrome imports this file. */ -async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null }) { +async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null, drawOnly = null }) { const { composeChrome } = await import("./compose-chrome.mjs"); // Each layer's outcome, said and logged (rebuild.ndjson): cached whole, // frames reused, or rendered. @@ -5585,6 +5647,8 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro const r = await composeChrome({ manifestPath, outDir, variant, region: mod.region, doRender: true, fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence", ...win, + // The deck's frames the chunked encode will read, and only those (deckWant). + ...(mod.region === "deck" && drawOnly && duration == null ? { want: drawOnly } : {}), }); if (r.frameCount !== want) { throw new Error( @@ -5597,6 +5661,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro emitChrome({ phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", ...named, ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}), + ...(r.absent ? { absent: r.absent } : {}), frames: r.frameCount, key: r.key, dir: r.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -6898,7 +6963,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly return { out, failures: [] }; } - const plan = await renderDeck({ manifestPath, render, outDir, variant, schedule }); + const plan = await renderDeck({ + manifestPath, render, outDir, variant, schedule, drawOnly: deckWant({ schedule, render, outDir, segments: segs, joins, hardCut: D === 0 }), + }); EMIT("chrome", { phase: "overlay" }); EMIT("concat", { mode: D === 0 ? "hardcut" : "xfade", n: segs.length }); if (D === 0 && chunkedEncodeOn(render)) { @@ -7030,7 +7097,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // skips the render when its key and frame count match). `--no-chrome` keeps // the deck's framing and leaves the panel off -- a fast look at the picture. if (deck && !opts.noChrome) { - chromePlan = await renderDeck({ manifestPath, render, outDir, variant, schedule }); + // Lazily (deckWant) when the cut's chunked encode is the deck's only reader. + const want = !railPlan && (D === 0 || chunkedEncodeOn(render)) ? deckWant({ schedule, render, outDir, segments, joins, hardCut: D === 0 }) : null; + chromePlan = await renderDeck({ manifestPath, render, outDir, variant, schedule, drawOnly: want }); EMIT("chrome", { phase: "overlay" }); } diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs @@ -249,11 +249,22 @@ export class HashMemo { export const FRAME_KEYS_FILE = ".frame-keys"; /** + * Beside a SPARSE chrome sequence's `.frame-keys`, in place of its `.key`: + * `{ key, frames, absent }`. compose-chrome writes one when a build asked it + * to capture only the frames its chunks to encode read (`want`): the other + * frames' keys are known and their chunks are on disk, so they are not drawn. + * A sparse sequence is never "cached whole"; what it has is reused by key. + */ +export const SPARSE_FILE = ".sparse"; + +/** * A sequence's frame keys, when it has them for exactly `count` frames and is - * complete (its `.key` is written last); else null, and it is keyed by bytes. + * finished (its `.key` -- or a sparse one's `.sparse` -- is written last); + * else null, and it is keyed by bytes. */ export async function readFrameKeys(dir, count) { - if (!(await stat(path.join(dir, ".key")).catch(() => null))?.isFile()) return null; + const done = async (f) => (await stat(path.join(dir, f)).catch(() => null))?.isFile() === true; + if (!(await done(".key")) && !(await done(SPARSE_FILE))) return null; const text = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").catch(() => null); if (!text) return null; const keys = text.split("\n").filter(Boolean); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -44,7 +44,7 @@ import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, t import { GSAP_FILE } from "./chrome-deck.mjs"; import { fxGeometry, threadShotOf } from "./deck.mjs"; import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; -import { FRAME_KEYS_FILE } from "./chunked-encode.mjs"; +import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs"; import { regionCaching, regionModule } from "./modules/index.mjs"; const run = promisify(execFile); @@ -868,7 +868,7 @@ export async function composeChrome({ schedule = null, preview = false, doRender = false, fps = null, workers = null, quality = "high", format = "png-sequence", still = null, png = null, from = 0, duration = null, window = null, segment = null, transition = null, - lease = null, + lease = null, want = null, }) { // The variant's view, and its own out directory. Handed the whole manifest // the band would draw claims this cut never makes, and the deck would name @@ -1018,8 +1018,11 @@ export async function composeChrome({ return { ...result, frames: target, cached: true }; } if (fk) { + // The frames the build will read (`want`, build-video's chunk plan): + // only those are captured; the rest are left out (a SPARSE sequence). + const need = want ? await want(fk) : null; const r = await reuseFrames({ - base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(), + base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(), need, }); if (r) return { ...result, frames: target, ...r }; } @@ -1146,7 +1149,7 @@ export function frameDedupOn(env = process.env) { * is the cheaper one then), or, with `dedup` off, when nothing on disk has * frame keys. */ -async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true }) { +async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true, need = null }) { const chrome = path.join(base, "chrome"); const candidates = [target, path.join(chrome, `work-from-${stem}-frames`), path.join(chrome, `work-from-own-${stem}-frames`)]; // Every frame on disk, by key: `occ` holds each key's frames as ids @@ -1157,11 +1160,17 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf const have = new Map(); for (const dir of candidates) { const keys = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").then((t) => t.split("\n").filter(Boolean), () => null); - if (!keys || (await framesOnDisk(dir)) !== keys.length) continue; + if (!keys) continue; + // A sparse sequence (`.sparse`) offers the frames it has; any other, all or none. + const sparse = (await stat(path.join(dir, SPARSE_FILE)).catch(() => null))?.isFile() === true; + const present = sparse ? new Set((await readdir(dir)).filter((f) => /^frame_\d+\.png$/.test(f))) : null; + if (!sparse && (await framesOnDisk(dir)) !== keys.length) continue; const d = dirs.length; dirs.push(dir); - keysOf.push(keys); + // (A frame a sparse sequence lacks keys as nothing: never matched.) + keysOf.push(present ? keys.map((k, i) => (present.has(frameName(i + 1)) ? k : null)) : keys); keys.forEach((k, i) => { + if (present && !present.has(frameName(i + 1))) return; if (!occ.has(k)) occ.set(k, []); occ.get(k).push(d * 1e7 + i); if (!have.has(k)) have.set(k, true); @@ -1170,11 +1179,14 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf if (!dirs.length && !dedup) return null; const missing = []; for (let i = 0; i < fk.length; i += 1) if (!have.has(fk[i])) missing.push(i); + // `need` (a Set of 0-based frames): only those are drawn; a frame on no + // disk and not needed is left out, and the sequence is SPARSE. + const wanted = need ? missing.filter((i) => need.has(i)) : missing; // One capture per new key. const seen = new Set(); - const capture = missing.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true))); - if (capture.length > fk.length * 0.9) return null; + const capture = wanted.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true))); + if (!need && capture.length > fk.length * 0.9) return null; const capDir = path.join(chrome, `work-capture-${stem}-frames`); const capProj = path.join(chrome, `work-capture-${stem}`); if (capture.length) { @@ -1228,6 +1240,9 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf if (g >= 0) off = g - i; } + // Left out: a frame no disk has and nothing captured draws (a frame of a + // captured key is that capture, wanted or not). + const absent = pick.filter((src) => !src); const next = path.join(chrome, `work-next-${stem}-frames`); await rm(next, { recursive: true, force: true }); await mkdir(next, { recursive: true }); @@ -1235,16 +1250,17 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf // A frame deduplicated onto one inode may be at the filesystem's link cap: one copy stands in (link-or-copy.mjs). const linkOne = makeLinker(); for (let i = 0; i < fk.length; i += 512) { - await Promise.all(pick.slice(i, i + 512).map((src, j) => linkOne(src, path.join(next, frameName(i + j + 1))))); + await Promise.all(pick.slice(i, i + 512).map((src, j) => (src ? linkOne(src, path.join(next, frameName(i + j + 1))) : null))); } await writeFrameKeys(next, fk); - await writeFile(path.join(next, ".key"), key + "\n", "utf8"); + if (absent.length) await writeFile(path.join(next, SPARSE_FILE), JSON.stringify({ key, frames: fk.length, absent: absent.length }) + "\n", "utf8"); + else await writeFile(path.join(next, ".key"), key + "\n", "utf8"); const old = path.join(chrome, `work-old-${stem}-frames`); await rm(old, { recursive: true, force: true }); await rename(target, old).catch((e) => { if (e?.code !== "ENOENT") throw e; }); await rename(next, target); for (const d of [old, capDir, capProj, ...candidates.slice(1)]) await rm(d, { recursive: true, force: true }); - return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: missing.length - capture.length }; + return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: wanted.length - capture.length, ...(absent.length ? { absent: absent.length } : {}) }; } if (import.meta.url === `file://${process.argv[1]}`) { diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs @@ -424,3 +424,62 @@ test("compose-chrome with the deck's items: a changed title captures only the fr rmSync(dir, { recursive: true, force: true }); } }); + +test("compose-chrome `want`: only the frames asked for are drawn (a SPARSE sequence), and what it has is reused by key", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "frame-want-")); + const env = process.env.HYPERFRAMES_BIN; + try { + const stub = path.join(dir, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const font = path.join(dir, "face.ttf"); + writeFileSync(font, "face"); + const render = { ...RENDER, fontRegular: font, fontBold: font }; + const mp = path.join(dir, "video.manifest.json"); + writeFileSync(mp, JSON.stringify({ slug: "f", render, timeline: [] })); + const out = path.join(dir, "out", "sourced"); + mkdirSync(out, { recursive: true }); + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(schedule(0))); + const { composeChrome, FRAME_KEYS_FILE } = await import("./compose-chrome.mjs"); + const { framesOf, frameKeyOf } = await import("./prune-frames.mjs"); + const { readFrameKeys, SPARSE_FILE } = await import("./chunked-encode.mjs"); + const range = (a, b) => new Set(Array.from({ length: b - a }, (_, k) => a + k)); + const frameFiles = (d) => readdirSync(d).filter((f) => /^frame_\d+\.png$/.test(f)); + let asked = null; + + // Nothing on disk, frames 100..199 wanted: those are drawn, nothing else. + const first = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30, want: async (fk) => ((asked = fk.length), range(100, 200)) }); + assert.equal(asked, 1200, "want is handed every frame's key"); + const seq = first.frames; + const drawn = new Set(frameFiles(seq)); + for (const i of range(100, 200)) assert.ok(drawn.has(`frame_${String(i + 1).padStart(6, "0")}.png`), `frame ${i + 1} drawn`); + assert.ok(drawn.size < 1200 && first.absent === 1200 - drawn.size, `${drawn.size} drawn (a frame of a captured key is that capture), ${first.absent} left out`); + assert.ok(readdirSync(seq).includes(SPARSE_FILE) && !readdirSync(seq).includes(".key"), "sparse: a .sparse, never a .key"); + assert.equal(await framesOf(seq), 1200, "as long as the cut, for verify-build and the prune record"); + assert.equal(await frameKeyOf(seq), first.key); + assert.equal((await readFrameKeys(seq, 1200))?.length, 1200, "its frame keys stand for its chunks"); + const keys = readFileSync(path.join(seq, FRAME_KEYS_FILE), "utf8").trim().split("\n"); + for (const f of drawn) { + const i = Number(f.slice(6, 12)) - 1; + const [, cut] = readFileSync(path.join(seq, f), "utf8").split(":"); + assert.equal(keys[Number(cut)], keys[i], `frame ${i + 1} draws its key`); + } + + // Asked again for 150..299: 150..199 are on disk; only new keys are captured. + const second = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30, want: async () => range(150, 300) }); + for (const i of range(150, 300)) assert.ok(frameFiles(seq).includes(`frame_${String(i + 1).padStart(6, "0")}.png`), `frame ${i + 1} drawn`); + assert.ok(second.reused >= 50, `${second.reused} reused from the sparse sequence`); + + // Without `want`: the whole sequence, a .key and no .sparse; cached whole after. + const third = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 }); + assert.equal(frameFiles(seq).length, 1200); + assert.ok(readdirSync(seq).includes(".key") && !readdirSync(seq).includes(SPARSE_FILE)); + assert.ok(third.reused > 0); + assert.equal((await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 })).cached, true); + } finally { + if (env === undefined) delete process.env.HYPERFRAMES_BIN; + else process.env.HYPERFRAMES_BIN = env; + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/hardcut-deck.test.mjs b/umtool/report-to-video/hardcut-deck.test.mjs @@ -0,0 +1,130 @@ +// A take's render: the deck over HARD CUTS (`transition: 0`), built in keyed +// chunks (build-video chunkedConcat), the deck's frames drawn only where a +// chunk to encode reads them (deckWant / compose-chrome `want`): +// +// - the first build encodes every chunk and draws every frame, then prunes them; +// - the same cut again draws NO frame and encodes no chunk -- the deck's +// frame keys say every chunk on disk is still the cut's -- and verify-build +// still reads the deck as whole; +// - one still made a second longer: its chunk alone is encoded, the deck's +// frames drawn only over it, the chunk after it moved and reused. +// +// Real encodes, kept tiny; the deck's renderer is a stub that logs how many +// frames each render drew. Skipped without ffmpeg/ffprobe. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; +import { buildVideo, setProgressMode } from "./build-video.mjs"; +import { CHUNKS_DIR, CHUNKS_RECORD } from "./chunked-encode.mjs"; +import { PRUNED_RECORD } from "./prune-frames.mjs"; +import { verifyBuild } from "./verify-build.mjs"; + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const RENDER = { + width: 1920, height: 1080, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2, + palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + chrome: { engine: "hyperframes", layout: "deck", deck: {} }, +}; + +const STUB = `#!/usr/bin/env node +import { spawnSync } from "node:child_process"; +import { appendFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs"; +const a = process.argv.slice(2); +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const w = Number((/data-width="(\\d+)"/.exec(html) ?? [0, 640])[1]); +const h = Number((/data-height="(\\d+)"/.exec(html) ?? [0, 360])[1]); +mkdirSync(out, { recursive: true }); +const one = out + "/.one.png"; +spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x112233:size=" + w + "x" + h, "-frames:v", "1", one]); +const n = Math.round(dur * fps); +for (let i = 1; i <= n; i += 1) copyFileSync(one, out + "/frame_" + String(i).padStart(6, "0") + ".png"); +appendFileSync(process.env.HF_LOG, n + "\\n"); +`; + +test("a hard-cut deck build: keyed chunks, and the deck drawn only where a chunk to encode reads it", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-hcdeck-")); + const env = { bin: process.env.HYPERFRAMES_BIN, log: process.env.HF_LOG }; + t.after(() => { + for (const [k, v] of [["HYPERFRAMES_BIN", env.bin], ["HF_LOG", env.log]]) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + setProgressMode("human"); + rmSync(root, { recursive: true, force: true }); + }); + const stub = path.join(root, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const log = path.join(root, "renders.log"); + process.env.HF_LOG = log; + const drawn = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(Number) : []); + + mkdirSync(path.join(root, "stills"), { recursive: true }); + for (const [n, c] of [["one", "334455"], ["two", "554433"], ["three", "445533"]]) { + const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x${c}:size=320x180`, "-frames:v", "1", path.join(root, "stills", `${n}.png`)]); + assert.equal(r.status, 0, String(r.stderr)); + } + const manifestPath = path.join(root, "video.manifest.json"); + const write = (seconds2) => writeFileSync(manifestPath, JSON.stringify({ + slug: "hc", title: "Hard cuts", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, render: RENDER, + timeline: [ + { id: "i1", type: "image", src: "stills/one.png", seconds: 2 }, + { id: "i2", type: "image", src: "stills/two.png", seconds: seconds2 }, + { id: "i3", type: "image", src: "stills/three.png", seconds: 2 }, + ], + })); + const v = path.join(root, "out", "sourced"); + const notes = []; + const events = []; + setProgressMode((e) => { + events.push(e); + if (e.ev === "note") notes.push(e.message); + }); + const record = () => JSON.parse(readFileSync(path.join(v, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); + + // First: every chunk encoded, every frame drawn, the frames pruned after. + write(2); + await buildVideo({ manifestPath, opts: {} }); + const rec1 = record(); + assert.equal(rec1.frames, 60); + assert.deepEqual(rec1.chunks.map((c) => c.anchor), ["i1.mp4@0", "i2.mp4@0", "i3.mp4@0"], "one chunk a segment"); + assert.equal(drawn().reduce((a, b) => a + b, 0) > 0, true); + assert.ok(!existsSync(path.join(v, "chrome", "deck-frames")), "pruned after the mux"); + assert.equal((await verifyBuild(manifestPath, {})).problems.length, 0); + + // The same cut: no chunk encoded, no deck frame drawn. + const before = drawn().length; + notes.length = 0; + await buildVideo({ manifestPath, opts: {} }); + assert.ok(notes.some((m) => /^final encode: 3\/3 chunk\(s\) unchanged/.test(m)), notes.join("\n")); + assert.ok(notes.some((m) => /0 of 3 chunk\(s\) to encode read 0 of 60 deck-frames frames/.test(m)), notes.join("\n")); + assert.equal(drawn().length, before, "the renderer was not run"); + assert.equal(JSON.parse(readFileSync(path.join(v, "chrome", PRUNED_RECORD), "utf8")).dirs["deck-frames"].frames, 60, "the sparse deck recorded as the cut's length"); + assert.deepEqual((await verifyBuild(manifestPath, {})).problems, []); + + // i2 a second longer: its chunk alone, the deck drawn only over it. + notes.length = 0; + write(3); + await buildVideo({ manifestPath, opts: {} }); + const rec3 = record(); + assert.equal(rec3.frames, 70); + const encoded = rec3.chunks.filter((c) => !rec1.chunks.some((o) => o.key === c.key)).map((c) => c.anchor); + assert.deepEqual(encoded, ["i2.mp4@0"], "only the grown still's chunk"); + const read = notes.find((m) => /chunk\(s\) to encode read/.test(m)); + assert.match(read, /1 of 3 chunk\(s\) to encode read (\d+) of 70/); + assert.ok(Number(/read (\d+) of/.exec(read)[1]) <= 32, read); + assert.ok(drawn().slice(before).every((n) => n <= 32), `drawn ${drawn().slice(before)}`); + assert.deepEqual((await verifyBuild(manifestPath, {})).problems, []); +}); diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -61,6 +61,11 @@ export async function keepFramesAsked(outRoot) { } const FRAME_RE = /^frame_\d+\.png$/; +/** A sparse sequence's `.sparse` (`{ key, frames, absent }`), or null. */ +async function sparseRecord(dir) { + return readFile(path.join(dir, ".sparse"), "utf8").then((s) => JSON.parse(s), () => null); +} + /** Is this `chrome/` entry one a prune removes? A real directory, named for it. */ export function isPrunable(dirent) { return dirent.isDirectory() && (dirent.name.endsWith("-frames") || dirent.name.startsWith("work-")); @@ -103,9 +108,7 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date(), se let bytes = 0; for (const name of sequences) { const dir = path.join(chromeDir, name); - const files = await readdir(dir).catch(() => []); - const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); - dirs[name] = { frames: files.filter((f) => FRAME_RE.test(f)).length, key }; + dirs[name] = { frames: await framesOf(dir), key: await frameKeyOf(dir) }; } for (const name of [...sequences, ...work]) bytes += await dirBytes(path.join(chromeDir, name)); const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; @@ -174,6 +177,8 @@ async function recorded(dir, since) { */ export async function framesOf(dir, { since = null } = {}) { const files = await readdir(dir).catch(() => null); + // A SPARSE sequence (chunked-encode.mjs SPARSE_FILE) is as long as its record says. + if (files?.includes(".sparse")) return Number((await sparseRecord(dir))?.frames ?? 0); if (files) return files.filter((f) => FRAME_RE.test(f)).length; return Number((await recorded(dir, since))?.frames ?? 0); } @@ -181,6 +186,7 @@ export async function framesOf(dir, { since = null } = {}) { /** A sequence's render key: its `.key`, or the one the prune recorded; null when neither. */ export async function frameKeyOf(dir, { since = null } = {}) { const files = await readdir(dir).catch(() => null); + if (files?.includes(".sparse")) return (await sparseRecord(dir))?.key ?? null; if (files) return readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); return (await recorded(dir, since))?.key ?? null; }