#!/usr/bin/env node // Quality variants of a finished cut: the encode ladder for sharing it // elsewhere -- the build's own file, smaller re-encodes at a height and a // quality, and ones made to fit under a size (a chat app's upload limit). // // render.variants: [{ name: "master" }, // { name: "1080p", height: 1080, crf: 22 }, // { name: "720p", height: 720, crf: 23 }, // { name: "fit24", maxMiB: 24 }] (the default) // // Each is `/..mp4` beside the cut, `master` excepted: // it IS the build's `.mp4`, not a copy. `/variants.json` // says what was made: `{ at, source, items: [{ name, path, width, height, // bytes, kbps }] }`. // // A `maxMiB` variant is x264 at the largest of 1080/720/480 (no larger than // the cut) whose picture keeps at least 100 kb/s per 480p's worth of pixels; // its sound AAC 48 kb/s mono when the whole is under 300 kb/s, else 96 kb/s // stereo; and it is encoded again 6 % lower while it lands over (x264 // overshoots: 24.3 MiB at a 23.1 target, measured). // // FROM THE MASTER'S CHUNKS (ladder-chunks.mjs): when the cut is a chunked // build whose chunks are still on disk (out/sourced/chunks/, proved to be the // master's picture by content), each rung is encoded chunk by chunk -- a rung // chunk keyed by the master chunk's key, the rung's settings and ffmpeg, kept // in out/ladder/chunks/ -- and joined with `-c copy`; a master chunk that did // not change costs nothing on any rung, and a rung whose chunks are all the // ones its file was joined from is not touched. A size-capped rung is then // per-chunk ABR at the plan's bitrate (one pass; lowered by what it overshot // while it lands over), its sound encoded once and cached, and the scale that // last landed under the cap is kept in // out/ladder/ladder.json, so the next run starts there (same keys: nothing // encoded). Otherwise -- no chunks, or a master built another way -- each // rung is encoded from the whole cut as before (a size-capped one two-pass). // // A crf rung at the master's own height IS the master: hard-linked, never // re-encoded (a re-encode at the same size only loses picture). // // node umtool/report-to-video/variants.mjs [--slug s] [--only name,…] [--source file] [--whole] // // The CLI takes the machine's heavy slot (heavy-gate.mjs), declaring the // ladder's memory estimate (render-estimate.mjs); encodeVariants itself does // not -- umtool's job runner holds it for the UI. import { execFile } from "node:child_process"; import { copyFile, link, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; import { renderEstimateMb } from "./render-estimate.mjs"; import { CHUNKS_DIR } from "./chunked-encode.mjs"; import { LADDER_CHUNKS_DIR, LADDER_DIR, LADDER_RECORD, concatList, containerFrames, encodeChunkCached, fileIdentity, isLadderChunkFile, ladderJobs, masterFromChunks, rungAudioArgs, rungAudioFile, rungAudioKey, rungChunkArgs, rungChunkFile, rungChunkKey, rungJoinArgs, runPool, } from "./ladder-chunks.mjs"; import { ffmpegIdentity } from "./segment-cache.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; /** The ladder when `render.variants` is absent. */ export const DEFAULT_VARIANTS = Object.freeze([ Object.freeze({ name: "master" }), Object.freeze({ name: "1080p", height: 1080, crf: 22 }), Object.freeze({ name: "720p", height: 720, crf: 23 }), Object.freeze({ name: "fit24", maxMiB: 24 }), ]); export const VARIANTS_FILE = "variants.json"; /** The heights a size-capped variant picks from, largest first. */ export const FIT_HEIGHTS = Object.freeze([1080, 720, 480]); /** A size-capped variant's picture floor: kb/s per 480p's worth of pixels. */ export const FIT_FLOOR_KBPS = 100; /** Re-encode this much lower each time a size-capped variant lands over. */ export const FIT_RETRY_STEP = 0.06; const NAME_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; /** Names a cut variant's final already takes beside the cut (`..mp4`). */ const RESERVED = new Set(["sourced", "article", "preview", "prerail", "partial"]); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const numIn = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; /** * Every reason a `render.variants` list cannot be made, as sentences (empty: * it can). `undefined` is the default ladder. * * @returns {string[]} */ export function validateVariants(list, where = "render.variants") { if (list === undefined) return []; if (!Array.isArray(list)) return [`${where} must be a list of { name, height?, crf?, maxMiB?, preset? }`]; const errors = []; if (list.length > 12) errors.push(`${where} has ${list.length} variants (at most 12)`); const seen = new Set(); list.forEach((v, i) => { const at = `${where}[${i}]`; if (!isObj(v)) { errors.push(`${at} must be { name, height?, crf?, maxMiB?, preset? }`); return; } for (const k of Object.keys(v)) { if (!["name", "height", "crf", "maxMiB", "preset"].includes(k)) errors.push(`${at}.${k} is not a variant setting (name, height, crf, maxMiB, preset)`); } if (typeof v.name !== "string" || !NAME_RE.test(v.name)) { errors.push(`${at}.name must be lower-case letters, digits or dashes (at most 24)`); } else if (RESERVED.has(v.name)) { errors.push(`${at}.name "${v.name}" is taken (${[...RESERVED].join(", ")})`); } else if (seen.has(v.name)) errors.push(`${at}.name "${v.name}" is used twice`); else seen.add(v.name); if (v.name === "master" && Object.keys(v).length > 1) errors.push(`${at}: master is the build's own file -- it takes no settings`); if (v.height !== undefined && !(Number.isInteger(v.height) && v.height % 2 === 0 && numIn(v.height, 144, 2160))) { errors.push(`${at}.height must be an even whole number of pixels from 144 to 2160`); } if (v.crf !== undefined && !(Number.isInteger(v.crf) && numIn(v.crf, 0, 51))) errors.push(`${at}.crf must be a whole number from 0 to 51`); if (v.maxMiB !== undefined && !numIn(v.maxMiB, 0.01, 4096)) errors.push(`${at}.maxMiB must be from 0.01 to 4096`); if (v.maxMiB !== undefined && v.crf !== undefined) errors.push(`${at}: a maxMiB variant is sized by its bitrate -- it takes no crf`); const presets = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"]; if (v.preset !== undefined && !presets.includes(v.preset)) errors.push(`${at}.preset must be one of ${presets.join(", ")}`); }); return errors; } /** The ladder for a render: `render.variants`, else DEFAULT_VARIANTS. */ export function variantsOf(render) { return Array.isArray(render?.variants) ? render.variants : DEFAULT_VARIANTS; } /** A file's duration (s), picture size and bytes. */ export async function probeOut(file) { const { stdout } = await execFileP(FFPROBE(), [ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:format=duration", "-of", "json", file, ]); const doc = JSON.parse(stdout); const v = doc.streams?.[0] ?? {}; const st = await stat(file); return { duration: Number(doc.format?.duration), width: Number(v.width), height: Number(v.height), bytes: st.size }; } /** * A size-capped variant's plan: its height, picture and sound bitrates (kb/s) * for `maxMiB` over `seconds` of a cut `srcHeight` tall. `scale` < 1 is a * retry's: the picture's share lowered by that much. */ export function fitPlan({ maxMiB, seconds, srcHeight, maxHeight = null, scale = 1 }) { const totalKbps = (maxMiB * 1024 * 1024 * 8) / seconds / 1000; const audio = totalKbps < 300 ? { kbps: 48, channels: 1 } : { kbps: 96, channels: 2 }; // A container's own bytes: about 2 % of the whole at these rates. const videoKbps = Math.max(1, Math.floor((totalKbps * 0.98 - audio.kbps) * scale)); const cap = Math.min(srcHeight, maxHeight ?? Infinity); const heights = FIT_HEIGHTS.filter((h) => h <= cap); const options = heights.length ? heights : [cap - (cap % 2)]; const floor = (h) => FIT_FLOOR_KBPS * (h / 480) ** 2; const height = options.find((h) => videoKbps >= floor(h)) ?? options[options.length - 1]; return { height, videoKbps, audio, totalKbps }; } const scaleArgs = (height, srcHeight) => (height < srcHeight ? ["-vf", `scale=-2:${height}:flags=lanczos`] : []); /** One crf variant's argv: picture re-encoded at its height and quality; the sound copied. */ export function crfArgs({ source, out, height, srcHeight, crf, preset = "medium" }) { return [ "-nostdin", "-v", "error", "-y", "-i", source, "-map", "0:v:0", "-map", "0:a?", "-map_metadata", "0", "-map_chapters", "0", ...scaleArgs(height, srcHeight), "-c:v", "libx264", "-preset", preset, "-crf", String(crf), "-pix_fmt", "yuv420p", "-c:a", "copy", "-movflags", "+faststart", out, ]; } /** A two-pass variant's argv for `pass` (1 or 2). */ export function fitArgs({ source, out, plan, srcHeight, pass, logBase, preset = "medium" }) { const common = [ "-nostdin", "-v", "error", "-y", "-i", source, ...scaleArgs(plan.height, srcHeight), "-c:v", "libx264", "-preset", preset, "-b:v", `${plan.videoKbps}k`, "-pix_fmt", "yuv420p", "-pass", String(pass), "-passlogfile", logBase, ]; if (pass === 1) return [...common, "-map", "0:v:0", "-an", "-f", "null", "-"]; return [ ...common, "-map", "0:v:0", "-map", "0:a?", "-map_metadata", "0", "-map_chapters", "0", "-c:a", "aac", "-b:a", `${plan.audio.kbps}k`, "-ac", String(plan.audio.channels), "-movflags", "+faststart", out, ]; } const itemOf = (name, file, p, encode = null) => ({ name, path: file, width: p.width, height: p.height, bytes: p.bytes, kbps: Number.isFinite(p.duration) && p.duration > 0 ? Math.round((p.bytes * 8) / p.duration / 1000) : null, ...(encode ? { encode } : {}), }); /** The variant the build's own chunks are in: the default variant's (build-video's DEFAULT_VARIANT). */ const MASTER_VARIANT = "sourced"; /** `file` at `dst` as a hard link (through a rename), a copy across filesystems. */ async function linkInto(file, dst) { const [a, b] = await Promise.all([lstat(file), lstat(dst).catch(() => null)]); if (b && a.ino === b.ino && a.dev === b.dev) return; const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.link`); await rm(tmp, { force: true }); try { await link(file, tmp); } catch (err) { if (/** @type {any} */ (err)?.code !== "EXDEV") throw err; await copyFile(file, tmp); } await rename(tmp, dst); } const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); const sameList = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => x === b[i]); /** * The ladder over the master's chunks (see the top of the file), or null when * the master is not a chunked build whose chunks are on disk. */ async function openLadder({ outDir, src, work, slug, onLog }) { const dir = path.join(outDir, LADDER_DIR); const cdir = path.join(dir, LADDER_CHUNKS_DIR); const recFile = path.join(dir, LADDER_RECORD); await mkdir(cdir, { recursive: true }); const prev = await readJson(recFile); const rec = prev?.version === 1 && isObj(prev.rungs) ? prev : { version: 1, master: null, rungs: {} }; const chunksDir = path.join(outDir, MASTER_VARIANT, CHUNKS_DIR); const m = await masterFromChunks({ master: src, chunksDir, listFile: path.join(work, "master-concat.txt"), memo: rec.master }); if (!m.ok) { onLog(`variants: each rung from the whole cut — ${m.why}`); return null; } rec.master = m.memo; const ffmpeg = await ffmpegIdentity(FFMPEG()); onLog(`variants: from the master's ${m.chunks.length} chunk(s) (${MASTER_VARIANT}/${CHUNKS_DIR}/)`); /** * One rung over the chunks: each rung chunk on disk or encoded, the sound, * joined into a work file -- or nothing at all when the rung's file was * joined from exactly these (`skipped`). */ const run = async ({ name, rung, out, audio = null }) => { const t0 = Date.now(); const unique = new Map(); const keys = m.chunks.map((c) => { const key = rungChunkKey({ chunkKey: c.key, rung, ffmpeg }); if (!unique.has(key)) unique.set(key, { key, input: path.join(chunksDir, c.file), frames: c.b - c.a }); return key; }); const audioKey = audio && m.memo.audioHash ? rungAudioKey({ audioHash: m.memo.audioHash, audio, ffmpeg }) : null; const was = rec.rungs[name]; const outId = await fileIdentity(out); if (was && outId && was.file === outId && was.master === m.memo.id && sameList(was.keys, keys) && was.audio === (audioKey ?? "copy")) { return { skipped: true, keys, audioKey, chunks: unique.size, encoded: 0, reused: unique.size, seconds: 0 }; } let encoded = 0; const jobs = [...unique.values()].map((j) => async () => { const r = await encodeChunkCached({ dir: cdir, key: j.key, frames: j.frames, encode: (tmp) => execFileP(FFMPEG(), rungChunkArgs({ input: j.input, out: tmp, rung }), { maxBuffer: 1 << 26 }), }); if (!r.reused) encoded += 1; }); let audioFile = null; if (audioKey) { audioFile = rungAudioFile(cdir, audioKey); const file = audioFile; jobs.unshift(async () => { if ((await stat(file).catch(() => null))?.isFile()) return; const tmp = path.join(cdir, `.${path.basename(file)}.${process.pid}.partial.m4a`); await execFileP(FFMPEG(), rungAudioArgs({ source: src, out: tmp, audio }), { maxBuffer: 1 << 26 }); await rename(tmp, file); }); } onLog(`variant ${name}: ${unique.size} rung chunk(s) of ${keys.length}, ${ladderJobs()} at a time…`); await runPool(jobs, ladderJobs()); const listFile = path.join(work, `${slug}.${name}.concat.txt`); await writeFile(listFile, concatList(keys.map((k) => rungChunkFile(cdir, k))), "utf8"); const tmp = path.join(work, `${slug}.${name}.partial.mp4`); await execFileP(FFMPEG(), rungJoinArgs({ listFile, master: src, audio: audioFile, out: tmp }), { maxBuffer: 1 << 26 }); const got = await containerFrames(tmp); if (got !== m.frames) throw new Error(`variant ${name}: the joined rung holds ${got} frames; the cut is ${m.frames}`); return { skipped: false, tmp, keys, audioKey, chunks: unique.size, encoded, reused: unique.size - encoded, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)) }; }; /** What a rung's file was joined from, once it is in place. */ const remember = async (name, out, r, extra = {}) => { rec.rungs[name] = { keys: r.keys, audio: r.audioKey ?? "copy", master: m.memo.id, file: await fileIdentity(out), ...extra }; }; /** The record written; rung chunks no rung of `ladder` names, gone. */ const save = async (ladder) => { for (const n of Object.keys(rec.rungs)) if (!ladder.some((v) => v.name === n)) delete rec.rungs[n]; const keep = new Set(); for (const r of Object.values(rec.rungs)) { for (const k of r.keys ?? []) keep.add(path.basename(rungChunkFile(cdir, k))); if (r.audio && r.audio !== "copy") keep.add(path.basename(rungAudioFile(cdir, r.audio))); } for (const f of await readdir(cdir).catch(() => [])) { if ((isLadderChunkFile(f) && !keep.has(f)) || /\.partial\.(mp4|m4a)$/.test(f)) await rm(path.join(cdir, f), { force: true }); } const tmp = tmpPathFor(path.join(dir, `.${LADDER_RECORD}`)); await writeFile(tmp, JSON.stringify(rec, null, 2) + "\n", "utf8"); await rename(tmp, recFile); }; return { run, remember, save, rec }; } /** * Seed `toOut`'s ladder record with `fromOut`'s size-capped rungs' last good * scales (`take --from`, takeFrom.mjs): a rung this out/ has no scale for * starts where the other take's landed, so the chunks the two cuts share key * alike and are not encoded again. Never overwrites a scale of this out/'s * own. Returns the rung names seeded. * * @param {string} fromOut * @param {string} toOut * @returns {Promise} */ export async function seedLadderFit(fromOut, toOut) { const theirs = await readJson(path.join(fromOut, LADDER_DIR, LADDER_RECORD)); if (theirs?.version !== 1 || !isObj(theirs.rungs)) return []; const file = path.join(toOut, LADDER_DIR, LADDER_RECORD); const own = await readJson(file); const rec = own?.version === 1 && isObj(own.rungs) ? own : { version: 1, master: null, rungs: {} }; const seeded = []; for (const [name, r] of Object.entries(theirs.rungs)) { const fit = isObj(r) ? r.fit : null; if (!isObj(fit) || !isObj(fit.basis) || !(fit.scale > 0 && fit.scale <= 1)) continue; if (isObj(rec.rungs[name]?.fit)) continue; rec.rungs[name] = { ...(isObj(rec.rungs[name]) ? rec.rungs[name] : { keys: [], audio: null, master: null, file: null }), fit: { basis: fit.basis, scale: fit.scale } }; seeded.push(name); } if (!seeded.length) return []; await mkdir(path.dirname(file), { recursive: true }); const tmp = path.join(path.dirname(file), `.${LADDER_RECORD}.${process.pid}.seed`); await writeFile(tmp, JSON.stringify(rec, null, 2) + "\n", "utf8"); await rename(tmp, file); return seeded; } const encodeOf = (r) => ({ from: "chunks", chunks: r.chunks, encoded: r.encoded, reused: r.reused, seconds: r.seconds, ...(r.skipped ? { unchanged: true } : {}) }); /** * Make the variants of `/.mp4` (or `source`). `variants` is the * ladder (validated here); `only` names the ones to make now -- the others' * rows in variants.json are kept. Each is written under a temporary name and * renamed, so a half-made file is never taken for one. `chunked: false` * encodes every rung from the whole cut even when the master's chunks are there. * * @param {string} outDir * @param {{ slug: string, variants?: object[], only?: string[] | null, source?: string | null, * onLog?: (line: string) => void, chunked?: boolean }} opts * @returns {Promise<{ at: string, source: string, items: Array<{ name: string, path: string, * width: number, height: number, bytes: number, kbps: number | null, encode?: Record }> }>} */ export async function encodeVariants(outDir, { slug, variants = DEFAULT_VARIANTS, only = null, source = null, onLog = () => {}, chunked = true } = {}) { const errors = validateVariants(variants); if (errors.length) throw new Error(errors.join("; ")); if (!slug) throw new Error("variants: no slug"); const src = source ?? path.join(outDir, `${slug}.mp4`); const sp = await probeOut(src).catch(() => null); if (!sp) throw new Error(`variants: no cut at ${src} -- build it first`); if (only?.length) { const unknown = only.filter((n) => !variants.some((v) => v.name === n)); if (unknown.length) throw new Error(`variants: no variant named ${unknown.join(", ")} (${variants.map((v) => v.name).join(", ")})`); } const todo = variants.filter((v) => !only?.length || only.includes(v.name)); const made = []; const work = path.join(outDir, ".variants"); await mkdir(work, { recursive: true }); const needsEncode = todo.some((v) => v.name !== "master" && !(v.maxMiB === undefined && Math.min(v.height ?? sp.height, sp.height) === sp.height)); let ladder = null; try { if (chunked && needsEncode) ladder = await openLadder({ outDir, src, work, slug, onLog }); for (const v of todo) { if (v.name === "master") { made.push(itemOf("master", src, sp)); onLog(`variant master: ${path.basename(src)} (${(sp.bytes / 2 ** 20).toFixed(1)} MiB)`); continue; } const out = path.join(outDir, `${slug}.${v.name}.mp4`); const tmp = path.join(work, `${slug}.${v.name}.partial.mp4`); let encode = { from: "whole" }; const t0 = Date.now(); if (v.maxMiB === undefined) { const height = Math.min(v.height ?? sp.height, sp.height); if (height === sp.height) { // The master's own height: the master itself. await linkInto(src, out); const p = await probeOut(out); made.push(itemOf(v.name, out, p, { from: "master", linked: true })); onLog(`variant ${v.name}: ${height}p is the master's height — ${path.basename(out)} is the master (linked, not re-encoded)`); continue; } if (ladder) { const rung = { kind: "crf", height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset }; onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}, by chunk…`); const r = await ladder.run({ name: v.name, rung, out }); if (!r.skipped) await rename(r.tmp, out); await ladder.remember(v.name, out, r); encode = encodeOf(r); } else { onLog(`variant ${v.name}: ${height}p, crf ${v.crf ?? 23}…`); await execFileP(FFMPEG(), crfArgs({ source: src, out: tmp, height, srcHeight: sp.height, crf: v.crf ?? 23, preset: v.preset }), { maxBuffer: 1 << 26 }); await rename(tmp, out); } } else if (ladder) { const limit = v.maxMiB * 2 ** 20; const basis = { maxMiB: v.maxMiB, seconds: sp.duration, srcHeight: sp.height, maxHeight: v.height ?? null }; const was = ladder.rec.rungs[v.name]?.fit; // Where the last run landed under the cap: the same keys, nothing encoded. let scale = was && JSON.stringify(was.basis) === JSON.stringify(basis) && was.scale > 0 && was.scale <= 1 ? was.scale : 1; const sums = { chunks: 0, encoded: 0, reused: 0, seconds: 0, tries: 0 }; for (let tries = 0; ; tries += 1) { const plan = fitPlan({ ...basis, scale }); const rung = { kind: "abr", height: plan.height, srcHeight: sp.height, videoKbps: plan.videoKbps, preset: v.preset }; onLog(`variant ${v.name}: ${plan.height}p, ${plan.videoKbps} kb/s picture + ${plan.audio.kbps} kb/s ${plan.audio.channels === 1 ? "mono" : "stereo"}, by chunk (scale ${Number(scale.toFixed(4))})…`); const r = await ladder.run({ name: v.name, rung, out, audio: plan.audio }); sums.tries = tries + 1; sums.chunks = r.chunks; sums.encoded += r.encoded; sums.reused = r.reused; sums.seconds += r.seconds; if (r.skipped) { encode = { ...encodeOf(r), scale }; break; } const got = (await stat(r.tmp)).size; const last = tries >= 3; if (got <= limit || last) { if (got > limit) onLog(`variant ${v.name}: still ${(got / 2 ** 20).toFixed(2)} MiB over ${v.maxMiB} after ${tries + 1} tries — kept`); await rename(r.tmp, out); await ladder.remember(v.name, out, r, { fit: { basis, scale } }); encode = { from: "chunks", ...sums, seconds: Number(sums.seconds.toFixed(1)), scale }; break; } await rm(r.tmp, { force: true }); // One-pass ABR over short chunks overshoots more than two passes over // the whole: lower by what it overshot (3 % more), at least the step. const next = scale * Math.min(1 - FIT_RETRY_STEP, (limit / got) * 0.97); onLog(`variant ${v.name}: ${(got / 2 ** 20).toFixed(2)} MiB is over ${v.maxMiB} — again ${Math.round((1 - next / scale) * 100)} % lower`); scale = next; } } else { const limit = v.maxMiB * 2 ** 20; let scale = 1; for (let tries = 0; ; tries += 1) { const plan = fitPlan({ maxMiB: v.maxMiB, seconds: sp.duration, srcHeight: sp.height, maxHeight: v.height ?? null, scale }); onLog(`variant ${v.name}: ${plan.height}p, ${plan.videoKbps} kb/s picture + ${plan.audio.kbps} kb/s ${plan.audio.channels === 1 ? "mono" : "stereo"}, two passes…`); const logBase = path.join(work, `${slug}.${v.name}.pass`); for (const pass of [1, 2]) { await execFileP(FFMPEG(), fitArgs({ source: src, out: tmp, plan, srcHeight: sp.height, pass, logBase, preset: v.preset }), { maxBuffer: 1 << 26, cwd: work }); } const got = (await stat(tmp)).size; if (got <= limit) break; if (tries >= 3) { onLog(`variant ${v.name}: still ${(got / 2 ** 20).toFixed(2)} MiB over ${v.maxMiB} after ${tries + 1} tries — kept`); break; } scale *= 1 - FIT_RETRY_STEP; onLog(`variant ${v.name}: ${(got / 2 ** 20).toFixed(2)} MiB is over ${v.maxMiB} — again ${Math.round(FIT_RETRY_STEP * 100)} % lower`); } await rename(tmp, out); } if (encode.from === "whole") encode = { from: "whole", seconds: Number(((Date.now() - t0) / 1000).toFixed(1)) }; const p = await probeOut(out); made.push(itemOf(v.name, out, p, encode)); const how = encode.from === "chunks" ? encode.unchanged ? " — unchanged (every rung chunk the one it was joined from), not touched" : ` — ${encode.encoded} rung chunk(s) encoded, ${encode.reused} reused, in ${encode.seconds}s` : ""; onLog(`variant ${v.name}: ${path.basename(out)} ${p.width}x${p.height}, ${(p.bytes / 2 ** 20).toFixed(2)} MiB${how}`); } if (ladder) await ladder.save(variants); } finally { await rm(work, { recursive: true, force: true }); } // The record: this run's rows over any earlier ones of the same source, in ladder order. let prev = null; try { prev = JSON.parse(await readFile(path.join(outDir, VARIANTS_FILE), "utf8")); } catch { prev = null; } const keep = prev?.source === src && Array.isArray(prev.items) ? prev.items.filter((it) => !made.some((m) => m.name === it.name)) : []; const rank = (n) => { const i = variants.findIndex((v) => v.name === n); return i < 0 ? variants.length : i; }; const items = [...keep.filter((it) => variants.some((v) => v.name === it.name)), ...made].sort((a, b) => rank(a.name) - rank(b.name)); const doc = { at: new Date().toISOString(), source: src, items }; await writeFile(path.join(outDir, VARIANTS_FILE), JSON.stringify(doc, null, 2) + "\n"); return doc; } // ---- the CLI --------------------------------------------------------------- /** argv after the script: ` [--slug s] [--only a,b] [--source file] [--whole]` (--whole: never from the chunks). */ export function parseVariantArgs(argv) { const out = { outDir: null, slug: null, only: null, source: null, chunked: true }; for (let i = 0; i < argv.length; i += 1) { const a = argv[i]; if (a === "--slug") out.slug = argv[++i] ?? null; else if (a === "--only") out.only = String(argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean); else if (a === "--source") out.source = argv[++i] ?? null; else if (a === "--whole") out.chunked = false; else if (a.startsWith("--")) throw new Error(`variants: unknown option ${a}`); else if (!out.outDir) out.outDir = a; else throw new Error(`variants: one take out dir, got ${a} too`); } if (!out.outDir) throw new Error("usage: variants.mjs [--slug s] [--only name,…] [--source file] [--whole]"); return out; } async function main() { const args = parseVariantArgs(process.argv.slice(2)); const outDir = path.resolve(args.outDir); // The take's manifest is beside its out dir: its slug and its ladder. let manifest = null; try { manifest = JSON.parse(await readFile(path.join(path.dirname(outDir), "video.manifest.json"), "utf8")); } catch { manifest = null; } const slug = args.slug ?? manifest?.slug; if (!slug) throw new Error(`variants: no --slug and no video.manifest.json beside ${outDir}`); const variants = variantsOf(manifest?.render); const run = () => encodeVariants(outDir, { slug, variants, only: args.only, source: args.source ? path.resolve(args.source) : null, chunked: args.chunked, onLog: (line) => process.stderr.write(`${line}\n`), }); // By a URL made from the script's own path at run time, as build-video's // CLI loads it: never a module the umtool app's bundle traces. const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href; const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); // It declares the ladder's estimate, so a capped build may run beside it. const doc = await withRenderSlot(["variants", outDir], run, { estimateMb: renderEstimateMb("ladder") }); process.stdout.write(JSON.stringify(doc, null, 2) + "\n"); } if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { main().catch((err) => { process.stderr.write(`${err?.message ?? err}\n`); process.exit(1); }); }