// PRUNING THE CHROME'S FRAMES once the cut is muxed. // // The deck, the feed, the stamps, the threads, each posts window and each // teaser render a PNG sequence into `/chrome/-frames` -- one to // two GB a take -- and the renderer can leave a `chrome/work-*` directory // behind a render it did not finish. Once the final file is muxed none of it is // read again by that cut; the cost of keeping it is only that the NEXT // `--chrome-only` reuses a render whose key did not change instead of // rendering it again. Several takes of that size filled /home (2026-10-09). // So a build prunes them after its final mux, unless `--keep-frames` // (build-video.mjs says which runs prune). // // WHAT IS TOUCHED, AND NOTHING ELSE: the DIRECTORIES `chrome/-frames` and // `chrome/work-*`. Never `segments/` -- a take re-lays its chrome over ANOTHER // take's segments by hard-linking them in, and a prune that reached them would // take the other take's footage with it -- never the compositions // (`chrome/deck/`, `chrome/posts-/`), the cards, the QRs, the schedule or // the joins' caches. A symlink named like one is not followed or removed. // // What was pruned is written down first, in `chrome/pruned.json`: each // sequence's frame count and render key, as of this prune (a sequence a later // build renders again is counted on disk; the record only answers for one that // is gone). verify-build reads a pruned sequence's count and key from there, so // a verified cut stays verifiable. // // A TAKE THAT ASKED TO KEEP ITS FRAMES (`umtool take --keep-frames`) has // `/.keep-frames/asked.json`. A later build of that out/ without // --keep-frames (a `--rebuild`, a re-run from the UI) still prunes chrome/, // but SETS ASIDE each sequence instead of removing it: renamed to // `/.keep-frames/-frames` (the default variant's; another // variant's under `.keep-frames//`), where `umtool take --from` // (takeFrom.mjs) finds it. The record is written either way. import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PRUNED_RECORD = "pruned.json"; /** Where an out/ keeps its set-aside chrome sequences: `/.keep-frames/`. */ export const KEEP_FRAMES_DIR = ".keep-frames"; /** The marker that the out/'s take asked for its frames to be kept. */ export const KEEP_FRAMES_ASKED = "asked.json"; /** The directory a variant's sequences are set aside in. */ export function keptFramesDir(outRoot, variant = "sourced") { const base = path.join(outRoot, KEEP_FRAMES_DIR); return variant === "sourced" ? base : path.join(base, variant); } /** Record that this out/'s frames are to be kept: `/.keep-frames/asked.json`. */ export async function markKeepFrames(outRoot, { now = () => new Date(), by = "take --keep-frames" } = {}) { const dir = path.join(outRoot, KEEP_FRAMES_DIR); await mkdir(dir, { recursive: true }); const tmp = tmpPathFor(path.join(dir, `.${KEEP_FRAMES_ASKED}`)); await writeFile(tmp, `${JSON.stringify({ at: now().toISOString(), by }, null, 2)}\n`, "utf8"); await rename(tmp, path.join(dir, KEEP_FRAMES_ASKED)); } /** Did this out/'s take ask for its frames to be kept? */ export async function keepFramesAsked(outRoot) { return (await lstat(path.join(outRoot, KEEP_FRAMES_DIR, KEEP_FRAMES_ASKED)).catch(() => null))?.isFile() === true; } const FRAME_RE = /^frame_\d+\.png$/; /** 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-")); } async function dirBytes(dir) { let total = 0; const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); for (const e of entries) { const p = path.join(dir, e.name); if (e.isDirectory()) total += await dirBytes(p); else total += (await lstat(p).catch(() => null))?.size ?? 0; } return total; } async function readRecord(chromeDir) { return readFile(path.join(chromeDir, PRUNED_RECORD), "utf8").then( (s) => JSON.parse(s), () => null, ); } /** * Remove `/chrome/-frames` and `chrome/work-*`, recording each * sequence's frame count and key first. Returns what went and how much. * `setAside` (a directory): each sequence is renamed into it instead of * removed (one there by the same name replaced); `work-*` still goes. * * @returns {Promise<{ sequences: string[], work: string[], bytes: number, setAside?: string | null }>} */ export async function pruneChromeFrames(variantDir, { now = () => new Date(), setAside = null } = {}) { const chromeDir = path.join(variantDir, "chrome"); const entries = (await readdir(chromeDir, { withFileTypes: true }).catch(() => [])).filter(isPrunable); const sequences = entries.filter((e) => e.name.endsWith("-frames")).map((e) => e.name).sort(); const work = entries.filter((e) => !e.name.endsWith("-frames")).map((e) => e.name).sort(); if (!sequences.length && !work.length) return { sequences, work, bytes: 0 }; const dirs = {}; let bytes = 0; for (const name of sequences) { const dir = path.join(chromeDir, name); 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 }; const tmp = tmpPathFor(path.join(chromeDir, `.${PRUNED_RECORD}`)); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); if (setAside && sequences.length) { await mkdir(setAside, { recursive: true }); for (const name of sequences) { const to = path.join(setAside, name); await rm(to, { recursive: true, force: true }); await rename(path.join(chromeDir, name), to); } } for (const name of [...(setAside ? [] : sequences), ...work]) { await rm(path.join(chromeDir, name), { recursive: true, force: true }); } return { sequences, work, bytes, setAside: setAside && sequences.length ? setAside : null }; } /** * Record `names` (sequences in `chromeDir` about to be removed by somebody * else -- `umtool prune`, lib/report/takePrune.mjs) in `chrome/pruned.json`, * MERGED over what an earlier prune recorded: each sequence's frame count and * key as of now. A name with no directory is left as it was recorded. * * @param {string} chromeDir * @param {string[]} names `-frames` directory names * @returns {Promise} the names recorded */ export async function recordPrunedSequences(chromeDir, names, { now = () => new Date() } = {}) { const prev = await readRecord(chromeDir); const dirs = { ...(prev?.dirs && typeof prev.dirs === "object" ? prev.dirs : {}) }; const recorded = []; for (const name of [...names].sort()) { if (!name.endsWith("-frames")) continue; const dir = path.join(chromeDir, name); const files = await readdir(dir).catch(() => null); if (!files) continue; 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 }; recorded.push(name); } if (!recorded.length) return recorded; const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; const tmp = tmpPathFor(path.join(chromeDir, `.${PRUNED_RECORD}`)); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); return recorded; } // The record's entry for a pruned sequence -- unless the cut was written AFTER // the prune (`since`: the final file's mtime in ms), which means a later build // that rendered no chrome (`--no-chrome`) made it, and the record is not about // the file being verified. async function recorded(dir, since) { const rec = await readRecord(path.dirname(dir)); if (!rec) return null; if (since != null && !(Date.parse(rec.prunedAt) >= since - 2000)) return null; return rec.dirs?.[path.basename(dir)] ?? null; } /** * A sequence's frame count: counted on disk, or -- when it was pruned after * the mux -- what the prune recorded. 0 when neither knows it. */ 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); } /** 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; }