// `umtool take … --from `: before the render, the other take's // built files are HARD-LINKED into this take's out/sourced/, so the build // reuses whatever of them still matches this take's cut: // // segments/{.mp4,.cut.json,…} each clip segment, reused when its key // (segment-cache.mjs) is this cut's // chrome/-frames/ each keyed chrome render (the deck, the // feed, the stamps, the finale, a posts // window, a teaser), reused when its // `.key` is this cut's (compose-chrome) // xfade-batches/batch-.mov each crossfade batch, reused when its // key (the segments' size and mtime) is // out/.keep-frames/-frames a layer kept aside from a prune (the // other take's chrome/ lost it after its // mux), linked in as chrome/-frames; // when both are there, the one whose .key // was written last // // chunks/chunk-.mp4, audio-.m4a // each chunk of the final encode, reused // 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/). And, from // the other take's out/ (not a variant's): // // ladder/chunks/.mp4|m4a each encoded rung chunk of the variant // ladder (ladder-chunks.mjs), keyed by the // master chunk it was made from and the // rung's settings; and, into this take's // own ladder/ladder.json (written, not // linked), each size-capped rung's last // good scale it has none of // // THIS take's own files win when they are newer (release fast-rerender): a // take re-run `--force --from ` 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--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), // a chrome sequence by removing the directory and rendering a new one, a batch // 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. // // Plain node; the CLI runs it with bare node. import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; 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 { LADDER_CHUNKS_DIR, LADDER_DIR, isLadderChunkFile } from "umtool-report-to-video/ladder-chunks"; import { makeLinker } from "umtool-report-to-video/link-or-copy"; import { KEEP_FRAMES_DIR, keptFramesDir } from "umtool-report-to-video/prune-frames"; import { seedLadderFit } from "umtool-report-to-video/variants"; import { takesDirOf } from "./takes.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Where a take keeps a layer aside: its `out/.keep-frames/-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; const names = (dir) => readdir(dir).catch(() => []); /** Link `src` at `dst`, replacing whatever file is there (through a rename); the same inode is left. */ async function linkFile(src, dst) { const [a, b] = await Promise.all([lstat(src), lstat(dst).catch(() => null)]); if (b && b.ino === a.ino && b.dev === a.dev) return false; const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.link`); await rm(tmp, { force: true }); await makeLinker()(src, tmp); await rename(tmp, dst); return true; } /** A frame sequence directory, linked file by file into a fresh `dst` (what was there removed). */ async function linkFrames(src, dst) { await rm(dst, { recursive: true, force: true }); await mkdir(dst, { recursive: true }); let n = 0; // A deduplicated frame may be at the filesystem's link cap: one copy stands in (link-or-copy.mjs). const linkOne = makeLinker(); for (const f of await names(src)) { const p = path.join(src, f); if (!(await isFile(p))) continue; await linkOne(p, path.join(dst, f)); n += 1; } return n; } /** * Check `--from`: the other take exists, is not this one, and has a built out/sourced/. * @returns {Promise} the other take's out/sourced */ export async function fromTakeSourced(projectDir, id, from) { if (!from) throw new Error("--from : the take whose built files to start from"); if (from === id) throw new Error(`--from ${from}: that is this take — name another take`); const other = path.join(takesDirOf(projectDir), from); if (!(await isDir(other))) throw new Error(`--from ${from}: no such take in ${path.basename(projectDir)}`); const sourced = path.join(other, "out", DEFAULT_VARIANT); if (!(await isDir(sourced))) throw new Error(`--from ${from}: the take has no out/${DEFAULT_VARIANT} (it was never rendered)`); return sourced; } /** * Hard-link take `from`'s built files into `takeOut/` -- `sourced`, * and `full` when the other take built it -- and its ladder chunks into * `takeOut/ladder/` (see the top of the file). The counts are summed over the * variants; a frame layer of the full variant is named `full/-frames`. * @returns {Promise<{ segments: number, frames: string[], batches: number, chunks: number, records: number, * ladder: number, ladderFit?: string[], variants: string[], keptOwn: string[], keptOwnFrames: string[] }>} */ export async function linkFromTake(projectDir, id, from, takeOut) { const src = await fromTakeSourced(projectDir, id, from); 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); } // The variant ladder's encoded chunks, by content key: theirs beside ours. const ladder = path.join(otherOut, LADDER_DIR, LADDER_CHUNKS_DIR); const ladderOut = path.join(takeOut, LADDER_DIR, LADDER_CHUNKS_DIR); for (const f of await names(ladder)) { if (!isLadderChunkFile(f) || !(await isFile(path.join(ladder, f)))) continue; await mkdir(ladderOut, { recursive: true }); if (!(await isFile(path.join(ladderOut, f))) && (await linkFile(path.join(ladder, f), path.join(ladderOut, f)))) out.ladder += 1; } // Its size-capped rungs' last good scales, as where this take's start: the // chunks the two cuts share then key alike on those rungs too. out.ladderFit = await seedLadderFit(otherOut, takeOut); return out; } /** * One built variant directory's files linked into another (linkVariant), for a preview or a changes reel * (takePreview.mjs): `src` a take's out/sourced or out/preview/sourced, `dst` the preview's own. `chunks: * false` leaves the final encode's chunks and their record out -- a full render's are never a preview's. * @param {{ src: string, dst: string, kept?: string | null, from: string, chunks?: boolean }} o */ export async function linkVariantDir({ src, dst, kept = null, from, chunks = true }) { if (!(await isDir(src))) return null; if (path.resolve(src) === path.resolve(dst)) return null; return linkVariant({ src, dst, kept: kept ?? keptFramesDir(path.dirname(src), path.basename(src)), from, chunks }); } /** One variant's files, `src` (the other take's out/) into `dst`; `kept` its set-aside layers. */ async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) { 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"); 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(".")) 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); 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/-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 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 }); } } 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 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. 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); } const batches = path.join(src, "xfade-batches"); const batchOut = path.join(dst, "xfade-batches"); for (const f of await names(batches)) { if (!/^batch-[0-9a-f]+\.mov$/.test(f) || !(await isFile(path.join(batches, f)))) continue; 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); for (const f of withChunks ? 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 = withChunks ? await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null) : 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)]); if (theirMemo?.v === 1 && theirMemo.h) { const merged = { v: 1, h: { ...theirMemo.h, ...(ownMemo?.v === 1 ? ownMemo.h : {}) } }; const tmp = path.join(dst, tmpPathFor(HASH_MEMO_FILE)); 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). if (await isDir(batchOut)) { const tmp = path.join(batchOut, tmpPathFor(XFADE_FROM_FILE)); await writeFile(tmp, JSON.stringify({ take: from, segments: path.resolve(segs) }) + "\n", "utf8"); await rename(tmp, path.join(batchOut, XFADE_FROM_FILE)); } return out; }