// THE CLIP SEGMENT CACHE: a full build re-encodes a clip's segment only when // something that makes its bytes changed. // // A segment is one ffmpeg run. Its KEY is that run -- the exact argv, every // input file named in it (a big file by its real path, size and mtime; a // small one, like the header's text or a caption file the build has just // written, by its contents), the cut record written beside it (the snapped // seconds, room, loudness, blur, framing, captions, montage) and the ffmpeg // binary -- hashed. Every input that changes a picture or a sound reaches // the argv: the cut seconds through `-ss`/`-to`, the snap, pads, room, mute // and audio knobs through the filter graph, the blur through its filters and // line files, the framing through the scale/pad, the captions through their // ASS file, the loudness through its gain, the encode settings through // encodeArgs, the source through its file. The record says it a second time. // // The key is written in `.cut.json` (`segKey`, with `segSeconds`, the // segment's probed length). A segment on disk whose record carries this key, // and which still probes to that length, is reused as it is: not rewritten, // so its mtime holds and the crossfade batches keyed on it hit too. A record // with no key (built before this) or another key is rebuilt. // // A rebuild encodes to a temporary file and renames it over the segment, so a // segment that is a hard link of another take's is REPLACED, never written // through. When the new bytes are the old bytes (a segment with no key yet, // re-encoded the same) the old file is kept, mtime and all. // // Plain node; no Next. Every path here is a parameter, never cwd-derived. import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bumped when what the key covers changes: every segment is rebuilt once. */ export const SEGMENT_KEY_VERSION = 1; /** A file at or under this many bytes is keyed by its contents; above, by real path, size and mtime. */ export const HASH_CONTENT_BELOW = 8 << 20; /** An absolute path inside an argv element (a filter's textfile=, an -i, a fontfile=). */ const ABS_PATH = /\/(?:[\w.@+~%-]+\/)*[\w.@+~%-]+/g; const sha256 = (s) => createHash("sha256").update(s).digest("hex"); function fileSha(file) { return new Promise((resolve, reject) => { const h = createHash("sha256"); createReadStream(file) .on("error", reject) .on("data", (b) => h.update(b)) .on("end", () => resolve(h.digest("hex"))); }); } /** What a file contributes to a key, or null when it is not a regular file. */ async function fileIdentity(file) { const st = await stat(file).catch(() => null); if (!st?.isFile()) return null; if (st.size <= HASH_CONTENT_BELOW) return `sha:${await fileSha(file)}`; const real = await realpath(file).catch(() => file); return `file:${real}|${st.size}|${st.mtimeMs}`; } /** * The argv with every input file it names replaced by what identifies it, and * the build's own out dir by ``, so the same segment of two takes (each * with its own out/) keys alike. Pure but for the files' stats. * * @param {string[]} argv the ffmpeg argv WITHOUT its output path * @param {{ outDir: string }} o */ export async function canonicalArgv(argv, { outDir }) { const ids = new Map(); const idOf = async (p) => { if (!ids.has(p)) ids.set(p, await fileIdentity(p)); return ids.get(p); }; const out = path.resolve(outDir); const result = []; for (const a of argv) { let s = String(a); // A whole element that is a (relative) file. if (!s.startsWith("/") && !s.startsWith("-") && s.includes("/")) { const id = await idOf(path.resolve(s)); if (id) { result.push(`<${id}>`); continue; } } const found = [...new Set(s.match(ABS_PATH) ?? [])].sort((x, y) => y.length - x.length); for (const p of found) { const id = await idOf(p); if (id) s = s.split(p).join(`<${id}>`); } result.push(s.split(out).join("")); } return result; } let ffmpegIdCache = new Map(); /** The ffmpeg binary's identity (its real path, size and mtime), found on PATH when bare. */ export async function ffmpegIdentity(bin, env = process.env) { if (ffmpegIdCache.has(bin)) return ffmpegIdCache.get(bin); let file = null; if (bin.includes("/")) file = path.resolve(bin); else { for (const dir of String(env.PATH ?? "").split(":").filter(Boolean)) { const f = path.join(dir, bin); if ((await stat(f).catch(() => null))?.isFile()) { file = f; break; } } } const st = file ? await stat(file).catch(() => null) : null; const real = file ? await realpath(file).catch(() => file) : null; const id = st ? `${real}|${st.size}|${st.mtimeMs}` : `bin:${bin}`; ffmpegIdCache.set(bin, id); return id; } /** The record as the key sees it: the cache's own fields left out. */ export function recordForKey(record) { const { segKey: _k, segSeconds: _s, ...rest } = record ?? {}; return rest; } /** * A segment's key (see the top of the file). * @param {{ argv: string[], record: object, outDir: string, ffmpeg: string }} o argv WITHOUT the output path */ export async function segmentKey({ argv, record, outDir, ffmpeg }) { return sha256(JSON.stringify({ v: SEGMENT_KEY_VERSION, ffmpeg: await ffmpegIdentity(ffmpeg), argv: await canonicalArgv(argv, { outDir }), record: recordForKey(record), })).slice(0, 32); } const cutRecordOf = (seg) => seg.replace(/\.mp4$/, ".cut.json"); async function replaceText(file, text) { const tmp = tmpPathFor(path.join(path.dirname(file), `.${path.basename(file)}`)); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } async function sameBytes(a, b) { const [x, y] = await Promise.all([stat(a).catch(() => null), stat(b).catch(() => null)]); if (!x?.isFile() || !y?.isFile() || x.size !== y.size) return false; return (await fileSha(a)) === (await fileSha(b)); } /** * Encode one segment, or reuse the one on disk when its key matches. * * @param {{ seg: string, argv: string[], record: object, outDir: string, fps: number, ffmpeg: string, * exec: (bin: string, argv: string[]) => Promise, * probe: (file: string) => Promise, * emit?: (ev: string, fields: object) => void, noCache?: boolean, id?: string }} o * `argv` ENDS with the output path (`seg`), as the build always ran it * @returns {Promise<{ reused: false | "key" | "bytes" | "pool", key: string, seconds: number }>} */ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmpeg, exec, probe, emit = () => {}, noCache = false, id = path.basename(seg, ".mp4") }) { if (argv[argv.length - 1] !== seg) throw new Error(`encodeSegmentCached: the argv must end with ${seg}`); const head = argv.slice(0, -1); const key = await segmentKey({ argv: head, record, outDir, ffmpeg }); const tol = 1.5 / (fps || 30); if (!noCache) { const prev = await readFile(cutRecordOf(seg), "utf8").then(JSON.parse, () => null); if (prev?.segKey === key && Number.isFinite(prev.segSeconds) && (await stat(seg).catch(() => null))?.isFile()) { const got = await probe(seg).catch(() => null); if (got != null && Math.abs(got - prev.segSeconds) <= tol) { emit("note", { message: `${id}: segment unchanged (key ${key.slice(0, 12)}) — reused` }); // (Filed in the render pool when it has not got it: built before it, or linked in by --from.) await poolPut(await poolFor(outDir), "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }); return { reused: "key", key, seconds: prev.segSeconds }; } emit("note", { message: `${id}: segment key matches but the file probes ${got ?? "unreadable"}s, not ${prev.segSeconds}s — rebuilt` }); } } // The render pool (render-pool.mjs): the same segment built by any take of any project. const pool = noCache ? null : await poolFor(outDir); if (pool && (await poolFetch(pool, "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }))) { const rec = await readFile(cutRecordOf(seg), "utf8").then(JSON.parse, () => null); const got = await probe(seg).catch(() => null); if (rec?.segKey === key && got != null && Math.abs(got - rec.segSeconds) <= tol) { emit("note", { message: `${id}: segment from the render pool (key ${key.slice(0, 12)})` }); return { reused: "pool", key, seconds: rec.segSeconds }; } emit("note", { message: `${id}: the render pool's segment does not probe as recorded — rebuilt` }); } const tmp = path.join(path.dirname(seg), `.${path.basename(seg, ".mp4")}.${process.pid}.partial.mp4`); await rm(tmp, { force: true }); try { await exec(ffmpeg, [...head, tmp]); const seconds = await probe(tmp); let reused = false; if (await sameBytes(tmp, seg)) { await rm(tmp, { force: true }); reused = "bytes"; emit("note", { message: `${id}: segment re-encoded to the same bytes — the one on disk kept` }); } else { await rename(tmp, seg); } await replaceText(cutRecordOf(seg), JSON.stringify({ ...recordForKey(record), segKey: key, segSeconds: seconds }) + "\n"); if (pool) await poolPut(pool, "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }); return { reused, key, seconds }; } finally { await rm(tmp, { force: true }); } } /** For tests: forget the ffmpeg identities found. */ export function resetSegmentCacheForTests() { ffmpegIdCache = new Map(); }