Archilyzer · Source

archilyzer

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

commit ded904e15918be306ed893afb98f02b89cf9cf4d
parent 31d3e5499638781f95f996e71aac813b51f8acfb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 28 Oct 2026 23:00:53 -0400

umtool take --from reuses fully: the chunk record, the full variant, frames a kept take asked for

linkFromTake (lib/report/takeFrom.mjs) now links, per variant (sourced, and
full when the other take built one): the segments, the keyed chrome frames
(from chrome/ or the variant's .keep-frames/), the crossfade batches, the
encode chunks and -- new -- the chunk record chunks/chunks.json, unless this
take's own is newer, so a --from build says what changed against the other
take's chunks rather than "first chunked build". The build writes chunks.json
through a rename now (it may be a hard link of another take's).

`umtool take --keep-frames` marks the take: out/.keep-frames/asked.json
(markKeepFrames, prune-frames.mjs). build-video's pruneFrames, on a later build
of that out/ without --keep-frames, sets each chrome sequence aside in
out/.keep-frames/ (a non-default variant's in .keep-frames/<variant>/) instead
of removing it -- where takeFrom already looked -- and records it in
chrome/pruned.json the same.

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

Diffstat:
Mumtool/lib/report/takeCli.mjs | 13++++++++-----
Mumtool/lib/report/takeFrom.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mumtool/lib/report/takeFrom.test.mjs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 12++++++++++--
Mumtool/report-to-video/build-video.mjs | 20+++++++++++++-------
Mumtool/report-to-video/prune-frames.mjs | 52+++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/prune-frames.test.mjs | 42+++++++++++++++++++++++++++++++++++++++++-
7 files changed, 224 insertions(+), 34 deletions(-)

diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -45,11 +45,14 @@ export const TAKE_USAGE = [ `cut. Default window: --at ${DEFAULT_WINDOW.at} --dur ${DEFAULT_WINDOW.dur}. Nothing is fetched. --quick encodes`, "the render with x264 veryfast (the render only: the take's manifest, what a pick uses, keeps its own).", "--effect NAME is one of `umtool takes effects <project>` (an overlay effect's patch, before --patch's).", - "--from TAKE hard-links that take's built clip segments, chrome frames and crossfade batches into this", - "take's out/ first; the render then reuses each one whose key still matches this cut and rebuilds the rest", - "(an uncensored twin of a blurred take rebuilds only the blurred clip). The other take's files are never", - "changed. --keep-frames keeps this take's chrome frames after the mux (1-3 GB a layer for a full cut), so", - "a later --from can reuse them; without it they are pruned, and a --from twin captures the chrome again.", + "--from TAKE hard-links that take's built clip segments, chrome frames, crossfade batches, encode chunks", + "(and their record), its full variant's too, and its variant-ladder chunks into this take's out/ first; the", + "render then reuses each one whose key still matches this cut and rebuilds the rest (an uncensored twin of", + "a blurred take rebuilds only the blurred clip). The other take's files are never changed. --keep-frames", + "keeps this take's chrome frames after the mux (1-3 GB a layer for a full cut), so a later --from can reuse", + "them, and marks the take (out/.keep-frames/asked.json): a later build of it without the flag sets its", + "frames aside in out/.keep-frames/ instead of pruning them. Without it they are pruned, and a --from twin", + "captures the chrome again.", ].join("\n"); export const TAKES_USAGE = [ diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -21,6 +21,13 @@ // when its key (its inputs' CONTENTS) is // (chunked-encode.mjs), and the content- // hash memo, merged +// chunks/chunks.json the other take's record of its chunks, +// when this take has none or an older one: +// the build's "why re-encoded" compares +// against it rather than "first build" +// +// All of that for the `sourced` variant, and for the `full` variant too when +// the other take built one (out/full/, its own .keep-frames/full/). // // 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 @@ -37,7 +44,8 @@ // REPLACES rather than writes -- a segment through a rename // (encodeSegmentCached), its records and texts through a rename (replaceFile), // a chrome sequence by removing the directory and rendering a new one, a batch -// through a rename after the stale ones are removed -- so a rebuild here never +// through a rename after the stale ones are removed, the chunk record through a +// rename (replaceFile) -- so a rebuild here never // changes a byte of the other take's. Nothing else is linked: the chrome // compositions (chrome/deck/index.html …) are written in place each run. // @@ -45,12 +53,13 @@ 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 { DEFAULT_VARIANT, SEGMENT_FILE_SUFFIXES, VARIANTS, XFADE_FROM_FILE } from "umtool-report-to-video/build-video"; +import { CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE } from "umtool-report-to-video/chunked-encode"; +import { KEEP_FRAMES_DIR, keptFramesDir } from "umtool-report-to-video/prune-frames"; import { takesDirOf } from "./takes.mjs"; -/** Where `--from` keeps a layer aside: the other take's `out/.keep-frames/<layer>-frames`. */ -export const KEEP_FRAMES_DIR = ".keep-frames"; +/** Where a take keeps a layer aside: its `out/.keep-frames/<layer>-frames` (prune-frames.mjs). */ +export { KEEP_FRAMES_DIR }; const isFile = async (p) => (await lstat(p).catch(() => null))?.isFile() === true; const isDir = async (p) => (await lstat(p).catch(() => null))?.isDirectory() === true; @@ -96,14 +105,37 @@ 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, chunks: number, keptOwn: string[], keptOwnFrames: string[] }>} + * Hard-link take `from`'s built files into `takeOut/<variant>` -- `sourced`, + * and `full` when the other take built it (see the top of the file). The counts are summed over the + * variants; a frame layer of the full variant is named `full/<layer>-frames`. + * @returns {Promise<{ segments: number, frames: string[], batches: number, chunks: number, records: number, + * ladder: number, variants: string[], keptOwn: string[], keptOwnFrames: string[] }>} */ export async function linkFromTake(projectDir, id, from, takeOut) { const src = await fromTakeSourced(projectDir, id, from); - const dst = path.join(takeOut, DEFAULT_VARIANT); - if (path.resolve(src) === path.resolve(dst)) throw new Error(`--from ${from}: that is this take's own out/`); - const out = { segments: 0, frames: [], batches: 0 }; + const otherOut = path.dirname(src); + if (path.resolve(src) === path.resolve(path.join(takeOut, DEFAULT_VARIANT))) throw new Error(`--from ${from}: that is this take's own out/`); + const out = { segments: 0, frames: [], batches: 0, chunks: 0, records: 0, ladder: 0, variants: [], keptOwn: [], keptOwnFrames: [] }; + for (const variant of VARIANTS) { + const vSrc = path.join(otherOut, variant); + if (variant !== DEFAULT_VARIANT && !(await isDir(vSrc))) continue; + const got = await linkVariant({ src: vSrc, dst: path.join(takeOut, variant), kept: keptFramesDir(otherOut, variant), from }); + const tag = (x) => (variant === DEFAULT_VARIANT ? x : `${variant}/${x}`); + out.segments += got.segments; + out.batches += got.batches; + out.chunks += got.chunks; + out.records += got.records; + out.frames.push(...got.frames.map(tag)); + out.keptOwn.push(...got.keptOwn.map(tag)); + out.keptOwnFrames.push(...got.keptOwnFrames.map(tag)); + out.variants.push(variant); + } + return out; +} + +/** One variant's files, `src` (the other take's out/<variant>) into `dst`; `kept` its set-aside layers. */ +async function linkVariant({ src, dst, kept, from }) { + const out = { segments: 0, frames: [], batches: 0, chunks: 0, records: 0, keptOwn: [], keptOwnFrames: [] }; const segs = path.join(src, "segments"); const segOut = path.join(dst, "segments"); @@ -122,7 +154,6 @@ export async function linkFromTake(projectDir, id, from, takeOut) { } 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 = []; @@ -144,7 +175,6 @@ export async function linkFromTake(projectDir, id, from, takeOut) { // The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside. const chrome = path.join(src, "chrome"); - const kept = path.join(path.dirname(src), KEEP_FRAMES_DIR); // 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]) { @@ -157,7 +187,6 @@ export async function linkFromTake(projectDir, id, from, takeOut) { } } if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true }); - 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); @@ -184,12 +213,20 @@ export async function linkFromTake(projectDir, id, from, takeOut) { // 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; } + // Their record of the chunks, unless ours is newer: what "why re-encoded" compares with. + const theirRecord = await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null); + if (theirRecord?.isFile()) { + const ownRecord = await lstat(path.join(chunksOut, CHUNKS_RECORD)).catch(() => null); + if (!ownRecord?.isFile() || ownRecord.mtimeMs < theirRecord.mtimeMs) { + await mkdir(chunksOut, { recursive: true }); + if (await linkFile(path.join(chunks, CHUNKS_RECORD), path.join(chunksOut, CHUNKS_RECORD))) out.records += 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)]); diff --git a/umtool/lib/report/takeFrom.test.mjs b/umtool/lib/report/takeFrom.test.mjs @@ -136,6 +136,57 @@ test("linkFromTake: this take's own NEWER build (a re-run after a stop) is kept, } }); +test("linkFromTake: the chunk record (unless ours is newer) and the full variant", async () => { + const p = await project(); + try { + // The other take's chunks and their record, and a built full variant with a set-aside layer. + await mkdir(path.join(p.src, "chunks"), { recursive: true }); + await writeFile(path.join(p.src, "chunks", "chunk-0a1b.mp4"), "chunk"); + await writeFile(path.join(p.src, "chunks", "chunks.json"), '{"version":1,"chunks":[]}\n'); + await writeFile(path.join(p.src, "chunks", "concat.txt"), "file 'chunk-0a1b.mp4'\n"); + const other = path.dirname(p.src); + const full = path.join(other, "full"); + await mkdir(path.join(full, "segments"), { recursive: true }); + await mkdir(path.join(full, "chunks"), { recursive: true }); + await writeFile(path.join(full, "segments", "s01.mp4"), "full s01"); + await writeFile(path.join(full, "segments", "s01.cut.json"), "{}"); + await writeFile(path.join(full, "chunks", "chunk-ffee.mp4"), "full chunk"); + await writeFile(path.join(full, "chunks", "chunks.json"), "{}\n"); + const keptFull = path.join(other, ".keep-frames", "full", "deck-frames"); + await mkdir(keptFull, { recursive: true }); + await writeFile(path.join(keptFull, "frame_000001.png"), "full deck"); + await writeFile(path.join(keptFull, ".key"), "kf\n"); + + const out = path.join(p.dir, "takes", "twin", "out"); + const got = await linkFromTake(p.dir, "twin", "blurred", out); + assert.deepEqual(got.variants, ["sourced", "full"]); + assert.equal(got.records, 2); + assert.equal(got.chunks, 2); + assert.ok(sameFile(path.join(p.src, "chunks", "chunks.json"), path.join(out, "sourced", "chunks", "chunks.json"))); + assert.ok(!existsSync(path.join(out, "sourced", "chunks", "concat.txt")), "the concat list is written in place by the build: not linked"); + assert.ok(sameFile(path.join(full, "segments", "s01.mp4"), path.join(out, "full", "segments", "s01.mp4"))); + assert.ok(sameFile(path.join(full, "chunks", "chunk-ffee.mp4"), path.join(out, "full", "chunks", "chunk-ffee.mp4"))); + assert.ok(got.frames.includes("full/deck-frames"), got.frames.join(", ")); + assert.equal(await readFile(path.join(out, "full", "chrome", "deck-frames", ".key"), "utf8"), "kf\n"); + assert.equal(await readFile(path.join(out, "sourced", "chrome", "deck-frames", "frame_000001.png"), "utf8"), "png", "sourced's deck is sourced's"); + + // Our own NEWER record is kept. + const ours = path.join(out, "sourced", "chunks", "chunks.json"); + await rm(ours); + await writeFile(ours, '{"version":1,"ours":true}\n'); + const later = new Date(Date.now() + 60_000); + await utimes(ours, later, later); + const again = await linkFromTake(p.dir, "twin", "blurred", out); + assert.equal(again.records, 0); + assert.match(await readFile(ours, "utf8"), /"ours":true/); + // No full variant on the other side: only sourced. + await rm(full, { recursive: true }); + assert.deepEqual((await linkFromTake(p.dir, "twin", "blurred", out)).variants, ["sourced"]); + } 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 { @@ -149,6 +200,9 @@ test("makeTake --from: linked before the render; --keep-frames reaches the build const opts = { render, probe: async () => 1, styles: {} }; await makeTake(p.dir, { id: "twin", label: "Twin", patch: { render: { blur: "off" } }, window: "full" }, { ...opts, from: "blurred", keepFrames: true }); assert.deepEqual(seen, [{ keepFrames: true, linked: true }]); + // --keep-frames marks the take: a later build of it sets its frames aside. + assert.ok(existsSync(path.join(p.dir, "takes", "twin", "out", ".keep-frames", "asked.json"))); + assert.ok(!existsSync(path.join(p.dir, "takes", "blurred", "out", ".keep-frames", "asked.json")), "the other take is not marked"); for (const [from, re] of [["twin", /that is this take/], ["nope", /no such take/]]) { await assert.rejects(makeTake(p.dir, { id: "twin", label: "Twin", window: "full" }, { ...opts, force: true, from }), re); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -48,6 +48,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { mergePatch } from "umtool-report-to-video/montage-styles"; import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings"; +import { markKeepFrames } from "umtool-report-to-video/prune-frames"; import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs"; import { replaceManifest } from "./manifest.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -480,7 +481,9 @@ export async function linkSharedOut(projectDir, takeOut) { * `from`: another take whose built segments, chrome renders and crossfade * batches are hard-linked in before the render (takeFrom.mjs), so the build * reuses whatever still matches. `keepFrames`: the build keeps its chrome - * frames after the mux (build-video --keep-frames), for a later `from`. + * frames after the mux (build-video --keep-frames), for a later `from`, and + * the take is marked (out/.keep-frames/asked.json) so a later build of it + * sets its frames aside rather than pruning them (prune-frames.mjs). */ export async function makeTake(projectDir, rawSpec, opts = {}) { const spec = checkSpec(rawSpec); @@ -547,12 +550,17 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { await (opts.ensureOut ?? ((d) => mkdir(d, { recursive: true })))(takeOut); const linked = await linkSharedOut(projectDir, takeOut); if (linked.length) log(`${spec.id}: reusing the project's ${linked.join(" and ")}`); + // Asked once, kept: a later build of this take without --keep-frames sets + // its chrome frames aside in out/.keep-frames/ rather than pruning them. + if (opts.keepFrames === true) await markKeepFrames(takeOut, { now }); if (fromTake) { 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), ` + - `${got.chunks ?? 0} encode chunk(s) — reused where they still match`, + `${got.chunks ?? 0} encode chunk(s)${got.records ? ` and ${got.records} chunk record(s)` : ""}` + + `${got.ladder ? `, ${got.ladder} ladder chunk(s)` : ""}` + + `${(got.variants?.length ?? 1) > 1 ? ` (variants ${got.variants.join(", ")})` : ""} — 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) { diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -205,7 +205,7 @@ import { snap } from "./snap.mjs"; 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 { 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, framesRead, sequenceIdentity, spanSegments, whyRebuilt, @@ -4871,11 +4871,12 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo } await rename(tmpOut, outPath); - // The record, and nothing kept that this cut does not use. - await writeFile(path.join(dir, CHUNKS_RECORD), JSON.stringify({ + // The record, and nothing kept that this cut does not use. Through a rename: + // `take --from` hard-links another take's record here (takeFrom.mjs). + await replaceFile(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"); + }, null, 2) + "\n"); // The memo keeps what this cut is made of: a frame or segment gone is forgotten. memo.pruneUnseen(); await memo.save(); @@ -6146,14 +6147,19 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // a segment. Not under the legacy chart band (`hyper`), whose frames are an // input made outside the build, nor after `--no-chrome`, which rendered no // chrome and leaves the last render's frames for a `--chrome-only`. + // A take that asked to keep its frames (`<out>/.keep-frames/asked.json`, + // umtool take --keep-frames) has them SET ASIDE in `<out>/.keep-frames/` + // instead, for a later `take --from` (prune-frames.mjs). const pruneFrames = async () => { if (opts.keepFrames || hyper || (deck && opts.noChrome)) return; - const p = await pruneChromeFrames(outDir); + const aside = (await keepFramesAsked(outRoot)) ? keptFramesDir(outRoot, variant) : null; + const p = await pruneChromeFrames(outDir, { setAside: aside }); if (p.sequences.length || p.work.length) { EMIT("note", { message: - `pruned ${p.sequences.length} frame sequence(s)` + - (p.work.length ? ` and ${p.work.length} renderer work dir(s)` : "") + + `${p.setAside ? "set aside" : "pruned"} ${p.sequences.length} frame sequence(s)` + + (p.setAside ? ` in ${path.relative(outRoot, p.setAside)}/ (this take asked to keep its frames)` : "") + + (p.work.length ? ` and ${p.setAside ? "removed " : ""}${p.work.length} renderer work dir(s)` : "") + `, ${(p.bytes / (1 << 20)).toFixed(0)} MiB (chrome/pruned.json records them; --keep-frames keeps them)`, }); } diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -22,11 +22,43 @@ // 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 +// `<out>/.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 +// `<out>/.keep-frames/<name>-frames` (the default variant's; another +// variant's under `.keep-frames/<variant>/`), where `umtool take --from` +// (takeFrom.mjs) finds it. The record is written either way. -import { lstat, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; export const PRUNED_RECORD = "pruned.json"; +/** Where an out/ keeps its set-aside chrome sequences: `<out>/.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: `<out>/.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 = path.join(dir, `.${KEEP_FRAMES_ASKED}.${process.pid}.tmp`); + 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$/; /** Is this `chrome/` entry one a prune removes? A real directory, named for it. */ @@ -55,10 +87,12 @@ async function readRecord(chromeDir) { /** * Remove `<variantDir>/chrome/<name>-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 }>} + * @returns {Promise<{ sequences: string[], work: string[], bytes: number, setAside?: string | null }>} */ -export async function pruneChromeFrames(variantDir, { now = () => new Date() } = {}) { +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(); @@ -78,10 +112,18 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date() } = const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); - for (const name of [...sequences, ...work]) { + 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 }; + return { sequences, work, bytes, setAside: setAside && sequences.length ? setAside : null }; } // The record's entry for a pruned sequence -- unless the cut was written AFTER diff --git a/umtool/report-to-video/prune-frames.test.mjs b/umtool/report-to-video/prune-frames.test.mjs @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; -import { PRUNED_RECORD, frameKeyOf, framesOf, pruneChromeFrames } from "./prune-frames.mjs"; +import { KEEP_FRAMES_DIR, PRUNED_RECORD, frameKeyOf, framesOf, keepFramesAsked, keptFramesDir, markKeepFrames, pruneChromeFrames } from "./prune-frames.mjs"; import { verifyBuild, verifyTeasers } from "./verify-build.mjs"; import { buildVideo, setProgressMode } from "./build-video.mjs"; import { frameCount, teaserSeconds } from "./deck.mjs"; @@ -83,6 +83,35 @@ test("pruneChromeFrames removes chrome/*-frames and chrome/work-* only, and reco } }); +test("pruneChromeFrames setAside: the sequences renamed into it (one there replaced), work dirs removed, recorded the same", async () => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-aside-")); + try { + const outRoot = path.join(root, "out"); + const v = path.join(outRoot, "sourced"); + const chrome = path.join(v, "chrome"); + frames(path.join(chrome, "deck-frames"), 4, "deck-new"); + mkdirSync(path.join(chrome, "work-1"), { recursive: true }); + assert.equal(await keepFramesAsked(outRoot), false); + await markKeepFrames(outRoot, { now: () => new Date("2026-10-28T00:00:00Z") }); + assert.equal(await keepFramesAsked(outRoot), true); + assert.equal(JSON.parse(readFileSync(path.join(outRoot, KEEP_FRAMES_DIR, "asked.json"), "utf8")).at, "2026-10-28T00:00:00.000Z"); + const aside = keptFramesDir(outRoot, "sourced"); + assert.equal(aside, path.join(outRoot, KEEP_FRAMES_DIR)); + assert.equal(keptFramesDir(outRoot, "full"), path.join(outRoot, KEEP_FRAMES_DIR, "full")); + frames(path.join(aside, "deck-frames"), 9, "deck-old"); + const r = await pruneChromeFrames(v, { setAside: aside }); + assert.deepEqual(r.sequences, ["deck-frames"]); + assert.equal(r.setAside, aside); + assert.ok(!existsSync(path.join(chrome, "deck-frames")) && !existsSync(path.join(chrome, "work-1"))); + assert.equal(readFileSync(path.join(aside, "deck-frames", ".key"), "utf8"), "deck-new\n"); + assert.equal(readdirSync(path.join(aside, "deck-frames")).length, 5, "the older one replaced, not merged"); + assert.deepEqual(JSON.parse(readFileSync(path.join(chrome, PRUNED_RECORD), "utf8")).dirs, { "deck-frames": { frames: 4, key: "deck-new" } }); + assert.ok(existsSync(path.join(outRoot, KEEP_FRAMES_DIR, "asked.json")), "the marker stays"); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + test("framesOf / frameKeyOf: on disk first; a pruned sequence from the record -- unless the cut is newer than the prune", async () => { const root = mkdtempSync(path.join(tmpdir(), "rtv-prune-read-")); try { @@ -195,6 +224,17 @@ for (let i = 1; i <= Math.round(dur * fps); i += 1) copyFileSync(one, out + "/fr assert.equal(rec.dirs["teaser-t1-frames"].frames, want); // The segment is the one the first build made (its record matched). assert.equal(statSync(path.join(v, "segments", "t1.mp4")).ino, seg.ino); + + // A take that asked to keep its frames: the next build sets them aside. + await markKeepFrames(path.join(root, "out")); + rmSync(path.join(v, "segments", "t1.mp4")); + events.length = 0; + await buildVideo({ manifestPath, opts: {} }); + assert.equal(existsSync(framesDir), false); + const aside = path.join(root, "out", KEEP_FRAMES_DIR, "teaser-t1-frames"); + assert.equal(readdirSync(aside).filter((f) => /^frame_\d+\.png$/.test(f)).length, want); + assert.ok(events.some((e) => e.ev === "note" && /^set aside 1 frame sequence\(s\) in \.keep-frames\/ \(this take asked to keep its frames\)/.test(e.message)), + events.filter((e) => e.ev === "note").map((e) => e.message).join("\n")); } finally { setProgressMode("human"); }