// THE VARIANT LADDER FROM THE MASTER'S CHUNKS: each rung of the encode ladder // (variants.mjs) is encoded chunk by chunk from the chunks the master itself // was joined from (chunked-encode.mjs), each rung chunk keyed by // // sha256(the master chunk's key, the rung's settings, the ffmpeg binary) // // and joined with `-c copy`, the sound beside (the master's, copied; or for a // size-capped rung, re-encoded once and cached by its own key). A master // chunk that did not change keeps its key, so its rung chunks are on disk and // only the changed chunks of each rung are encoded again. A rung whose keys // are all the ones its file was joined from last time is not joined again. // // The cache rule is one pure function -- rungChunkKey: chunk key + rung -> // key -- and one function that turns a key into a file (encodeChunkCached). // Neither knows a manifest, a take or the ladder; they are the `ladder` // module's cache rule when the video modules land. // // Is the master really made of those chunks? chunks.json says what the last // chunked build joined; the master may have been built some other way since // (a hard-cut take, REPORT_VIDEO_CHUNKED=0). masterFromChunks proves it by // CONTENT: the sha256 of the master's video packets is the sha256 of the // chunks' packets as the build's mux writes them (the concat demuxer's // h264_mp4toannexb, back through an mp4 muxer -- in-band parameter sets on // each IDR). A few seconds of reading, no decode. // // Plain node; every path is a parameter. import { execFile, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; /** Bumped when what a rung chunk key covers changes: every rung chunk is encoded once more. */ export const LADDER_KEY_VERSION = 1; /** The ladder's cache, under a build's out/ (beside variants.json). */ export const LADDER_DIR = "ladder"; /** Its encoded rung chunks and sounds: `rung-.mp4`, `audio-.m4a`. */ export const LADDER_CHUNKS_DIR = "chunks"; /** Its record: what each rung was last joined from. */ export const LADDER_RECORD = "ladder.json"; const sha256 = (s) => createHash("sha256").update(s).digest("hex"); /** Is `name` a file of the ladder's chunk cache? */ export const isLadderChunkFile = (name) => /^(rung|audio)-[0-9a-f]{24}\.(mp4|m4a)$/.test(name); /** * A rung's encode, as the settings that make its pixels: * `{ kind: "crf", height, srcHeight, crf, preset }` or * `{ kind: "abr", height, srcHeight, videoKbps, preset }`. * Only these go into a key; a name or a size cap does not. */ function rungParts(rung) { const base = { kind: rung.kind, height: rung.height, scaled: rung.height < rung.srcHeight, preset: rung.preset ?? "medium" }; if (rung.kind === "crf") return { ...base, crf: rung.crf }; if (rung.kind === "abr") return { ...base, videoKbps: rung.videoKbps }; throw new Error(`ladder: no rung kind ${rung.kind}`); } /** * THE CACHE RULE: a rung chunk's key from the master chunk's key (which * already names its inputs by content and the encoder that made it), the * rung's settings and the ffmpeg binary that encodes the rung. Pure. */ export function rungChunkKey({ chunkKey, rung, ffmpeg }) { if (!chunkKey) throw new Error("ladder: a rung chunk key needs the master chunk's key"); return sha256(JSON.stringify({ v: LADDER_KEY_VERSION, chunk: chunkKey, rung: rungParts(rung), ffmpeg })).slice(0, 24); } /** A size-capped rung's sound's key: the master's sound (by its packets' hash) at a rate and a layout. Pure. */ export function rungAudioKey({ audioHash, audio, ffmpeg }) { return sha256(JSON.stringify({ v: LADDER_KEY_VERSION, audio: audioHash, kbps: audio.kbps, channels: audio.channels, ffmpeg })).slice(0, 24); } export const rungChunkFile = (dir, key) => path.join(dir, `rung-${key}.mp4`); export const rungAudioFile = (dir, key) => path.join(dir, `audio-${key}.m4a`); /** One rung chunk's argv: the master chunk re-encoded at the rung's height and settings, picture only. Pure. */ export function rungChunkArgs({ input, out, rung }) { const p = rungParts(rung); return [ "-nostdin", "-v", "error", "-y", "-i", input, "-map", "0:v:0", ...(p.scaled ? ["-vf", `scale=-2:${rung.height}:flags=lanczos`] : []), "-c:v", "libx264", "-preset", p.preset, ...(p.kind === "crf" ? ["-crf", String(p.crf)] : ["-b:v", `${p.videoKbps}k`]), "-pix_fmt", "yuv420p", "-an", out, ]; } /** A size-capped rung's sound: the master's, AAC at the plan's rate and layout. Pure. */ export function rungAudioArgs({ source, out, audio }) { return [ "-nostdin", "-v", "error", "-y", "-i", source, "-map", "0:a:0", "-vn", "-c:a", "aac", "-b:a", `${audio.kbps}k`, "-ac", String(audio.channels), out, ]; } /** * A rung joined: its chunks by the concat demuxer, the sound (the master's * own, copied, or `audio`), the master's metadata and chapters, all `-c copy`. Pure. */ export function rungJoinArgs({ listFile, master, audio = null, out }) { return [ "-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", listFile, "-i", master, ...(audio ? ["-i", audio] : []), "-map", "0:v:0", "-map", audio ? "2:a:0" : "1:a?", "-map_metadata", "1", "-map_chapters", "1", "-c", "copy", "-movflags", "+faststart", out, ]; } /** A file's video frame count from its container (no decode); null when unreadable. */ export async function containerFrames(file, ffprobe = FFPROBE()) { const { stdout } = await execFileP(ffprobe, [ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=nb_frames", "-of", "csv=p=0", file, ]).catch(() => ({ stdout: "" })); const n = Number.parseInt(String(stdout).trim(), 10); return Number.isFinite(n) ? n : null; } /** * THE KEY -> FILE FUNCTION: the file for `key` in `dir`, encoded by * `encode(tmp)` only when it is not there with `frames` frames. Written * under a work name and renamed, so a half-made chunk is never taken for one. * * @param {{ dir: string, key: string, frames: number, encode: (tmp: string) => Promise, * countFrames?: (file: string) => Promise }} job * @returns {Promise<{ file: string, reused: boolean }>} */ export async function encodeChunkCached({ dir, key, frames, encode, countFrames = (f) => containerFrames(f) }) { const file = rungChunkFile(dir, key); if ((await stat(file).catch(() => null))?.isFile() && (await countFrames(file)) === frames) return { file, reused: true }; const tmp = path.join(dir, `.rung-${key}.${process.pid}.partial.mp4`); await rm(tmp, { force: true }); await encode(tmp); const got = await countFrames(tmp); if (got !== frames) { await rm(tmp, { force: true }); throw new Error(`ladder: rung chunk ${key} encoded ${got} frames, expected ${frames}`); } await rename(tmp, file); return { file, reused: false }; } /** Run `jobs` (async thunks) `width` at a time; the first failure thrown once they settle. */ export async function runPool(jobs, width) { let next = 0; let failure = null; const worker = async () => { while (next < jobs.length && !failure) { const k = next; next += 1; try { await jobs[k](); } catch (err) { failure ??= err; } } }; await Promise.all(Array.from({ length: Math.min(Math.max(1, width), jobs.length) }, worker)); if (failure) throw failure; } /** How many rung chunks are encoded at once: REPORT_VIDEO_CHUNK_JOBS (the build's knob), else 2. */ export function ladderJobs(env = process.env) { const n = Number(env.REPORT_VIDEO_CHUNK_JOBS); return Number.isInteger(n) && n >= 1 ? Math.min(n, 8) : 2; } // ---- is the master made of these chunks? ------------------------------------ /** `ffmpeg … -f streamhash` lines -> `{ v, a }` (the first video and audio stream's sha256). */ export function parseStreamHash(text) { const out = { v: null, a: null }; for (const line of String(text).split("\n")) { const m = /^\d+,([va]),SHA256=([0-9a-f]+)$/.exec(line.trim()); if (m && !out[m[1]]) out[m[1]] = m[2]; } return out; } /** The sha256 of a file's video and audio packets. */ export async function fileStreamHash(file, ffmpeg = FFMPEG()) { const { stdout } = await execFileP(ffmpeg, [ "-nostdin", "-v", "error", "-i", file, "-map", "0:v:0", "-map", "0:a:0?", "-c", "copy", "-f", "streamhash", "-hash", "sha256", "-", ], { maxBuffer: 1 << 20 }); return parseStreamHash(stdout); } /** * The sha256 of the video packets the build's mux makes of `listFile`'s * chunks: the concat demuxer into a fragmented mp4 on a pipe, read back. */ export function joinedStreamHash(listFile, ffmpeg = FFMPEG()) { return new Promise((resolve, reject) => { const a = spawn(ffmpeg, [ "-nostdin", "-v", "error", "-f", "concat", "-safe", "0", "-i", listFile, "-map", "0:v:0", "-c", "copy", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "-", ], { stdio: ["ignore", "pipe", "pipe"] }); const b = spawn(ffmpeg, ["-v", "error", "-i", "-", "-map", "0:v:0", "-c", "copy", "-f", "streamhash", "-hash", "sha256", "-"], { stdio: ["pipe", "pipe", "pipe"], }); a.stdout.pipe(b.stdin); b.stdin.on("error", () => {}); let out = ""; let err = ""; b.stdout.on("data", (d) => { out += d; }); a.stderr.on("data", (d) => { err += d; }); b.stderr.on("data", (d) => { err += d; }); let codeA = null; a.on("close", (c) => { codeA = c; }); a.on("error", reject); b.on("error", reject); b.on("close", (c) => { if (c !== 0 || (codeA !== null && codeA !== 0)) reject(new Error(`ladder: hashing the joined chunks failed: ${err.trim()}`)); else resolve(parseStreamHash(out).v); }); }); } /** A concat demuxer list of absolute paths. */ export function concatList(files) { return files.map((f) => `file '${path.resolve(f).replace(/'/g, "'\\''")}'`).join("\n") + "\n"; } /** A file's identity for a memo: what changes when it does (`dev:ino:size:mtime`). */ export async function fileIdentity(file) { const st = await stat(file).catch(() => null); return st?.isFile() ? `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}` : null; } /** * The chunks `master` is made of, when it is: `chunksDir`'s chunks.json, * every chunk on disk, and the master's video packets those chunks' (by * content, above). `memo` is the last answer for this master * (`{ id, record, videoHash, audioHash }`): reused when the master and the * record are the same files. `listFile`: where the chunks' concat list is * written. `ok: false`, with `why`, when the ladder cannot use them. * * @returns {Promise<{ ok: true, chunks: Array<{ a: number, b: number, key: string, file: string }>, fps: number, * frames: number, listFile: string, memo: { id: string, record: string, videoHash: string, audioHash: string | null } } * | { ok: false, why: string }>} */ export async function masterFromChunks({ master, chunksDir, listFile, memo = null, recordName = "chunks.json", ffmpeg = FFMPEG() }) { const text = await readFile(path.join(chunksDir, recordName), "utf8").catch(() => null); if (!text) return { ok: false, why: "the master has no chunk record (not a chunked build)" }; let rec; try { rec = JSON.parse(text); } catch { return { ok: false, why: "the chunk record is not JSON" }; } const chunks = Array.isArray(rec?.chunks) ? rec.chunks : []; if (!chunks.length || !(rec.fps > 0)) return { ok: false, why: "the chunk record lists no chunks" }; for (const c of chunks) { if (!(Number.isInteger(c.a) && Number.isInteger(c.b) && c.b > c.a && typeof c.key === "string" && typeof c.file === "string")) { return { ok: false, why: "the chunk record is malformed" }; } if (!(await stat(path.join(chunksDir, c.file)).catch(() => null))?.isFile()) return { ok: false, why: `chunk ${c.file} is gone` }; } const id = await fileIdentity(master); if (!id) return { ok: false, why: "no master file" }; const record = createHash("sha1").update(text).digest("hex"); // The list the hash is taken over: the record's, written fresh at `listFile` // (the build's concat.txt is written in place and may be another cut's). await writeFile(listFile, concatList(chunks.map((c) => path.join(chunksDir, c.file))), "utf8"); const ok = (m) => ({ ok: true, chunks, fps: rec.fps, frames: Number(rec.frames) || chunks[chunks.length - 1].b, listFile, memo: m }); if (memo && memo.id === id && memo.record === record && memo.videoHash) return ok(memo); const [own, joined] = await Promise.all([fileStreamHash(master, ffmpeg), joinedStreamHash(listFile, ffmpeg)]); if (!own.v || own.v !== joined) return { ok: false, why: "the master's picture is not these chunks (built another way since)" }; return ok({ id, record, videoHash: own.v, audioHash: own.a }); }