// 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. // // A chrome sequence that carries its FRAME KEYS (`.frame-keys`, written by // compose-chrome beside its `.key`: what each frame draws, frame-keys.mjs) is // identified by the keys of the frames a chunk reads rather than by their // bytes. Those keys are the contract the capture already reuses frames by; // and a layer captured again (its frames pruned after the last mux) draws // "a hair differently" per renderer worker -- a few pixels, a few levels -- // which by bytes made every chunk of the cut new. By keys, a recaptured deck // is the deck it was, and only a chunk whose frames DRAW something else is // encoded again. A sequence without them is keyed by its bytes, as before. // // 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"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** 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; } /** * Something computed from a file's contents (`compute(file)`, a string), * memoised beside its hash by the same identity under `tag` -- a segment's * SOUND, say, which a build keys apart from its picture. null when it is * not a regular file. */ async derived(file, tag, compute) { const st = await stat(file).catch(() => null); if (!st?.isFile()) return null; const id = `${tag}:${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}`; this.seen.add(id); const had = this.map.get(id); if (had) return had; const h = await compute(file); const after = await stat(file).catch(() => null); if (after && `${tag}:${after.dev}:${after.ino}:${after.size}:${after.mtimeMs}` === id) { this.map.set(id, h); this.dirty = true; } 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; // A tmp of its own per save: a build may save while another save of the same memo is in flight. const tmp = tmpPathFor(this.file); await writeFile(tmp, JSON.stringify({ v: 1, h: Object.fromEntries(this.map) }), "utf8"); await rename(tmp, this.file); this.dirty = false; } } /** Beside a chrome sequence's `.key`: each frame's key, frame 1 on line 1 (compose-chrome writes it). */ 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 * 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) { 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); return keys.length === count ? keys : null; } /** What a run `[lo, hi]` (1-based) of a sequence contributes to a key, by its frame keys. */ export function frameKeysIdentity(keys, [lo, hi]) { return `fk:${createHash("sha1").update(keys.slice(lo - 1, hi).join("\n")).digest("hex")}`; } /** 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 ``, * every sequence's start frame ``), 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, graph: string }, anchor: string }} rec * @param {Array} 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"; }