// A take's render (release 33): build-video.mjs over the take's render // manifest, into the take's own out/, through the machine's heavy slot. // // node scripts/queue-lock.mjs --heavy --estimate -- node build-video.mjs // --out takes//out --progress ndjson --skip-fetch --continue-on-error // [--no-xfade] [--no-chapters] // // --skip-fetch: a take never fetches. Its clips come from what the project // already has (out/clips-raw, linked in; the editor's corpus windows; a saved // source) -- a clip none of them covers fails the take, by name. // --continue-on-error: every clip that cannot be cut is named in one run // rather than one per run (the build then refuses to concatenate). // --no-xfade unless the take sets a transition (the `fast` preset's hard cuts); // --no-chapters for a window, which is not a deliverable. // // queue-lock admits the render by memory and runs it in a memory-capped scope // unless the caller is already capped (the live umtool unit). The render // declares its estimate (render-estimate.mjs: by the segments it crossfades and // UMTOOL_CHROME_WORKERS; UMTOOL_RENDER_ESTIMATE_MB overrides), so a capped site // build may run beside it while MemAvailable allows; an override of 0 declares // none, and it runs alone. // Inside a slot already held (HEAVY_HELD: an e2e run) it passes straight // through. In render mode (`umtool take … --priority`, renderMode.mjs) the // take's process carries the hold's RENDER_PRIORITY_TOKEN, and the render // inherits it with the rest of the environment: admitted while every other // heavy job waits, on the render's floor and cap. A copy of umtool without the checkout's scripts/ runs // build-video directly, which takes the slot itself (heavy-gate.mjs). import { execFile, spawn } from "node:child_process"; import { existsSync } from "node:fs"; import path from "node:path"; import { promisify } from "node:util"; import { readFile } from "node:fs/promises"; import { cutWindowFile, DEFAULT_VARIANT, variantPaths, xfadeBatchSize } from "umtool-report-to-video/build-video"; import { manifestEstimateMb, renderEstimateMb } from "umtool-report-to-video/render-estimate"; import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs"; const execFileP = promisify(execFile); /** How long a stopped render's group gets after TERM before KILL (ms). */ const RENDER_KILL_GRACE_MS = 8000; /** The checkout's heavy-slot CLI, when this umtool sits in the checkout. */ export function queueLockScript() { const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs"); return existsSync(/* turbopackIgnore: true */ file) ? file : null; } /** * The argv of a take's render, pure. * `estimateMb`: what the render declares to the heavy slot (null: nothing). * `cutWindow`: only those cut seconds laid and encoded, the whole cut's segments built (build-video --cut-window). * @param {{ manifestPath: string, outDir: string, full: boolean, xfade: boolean, keepFrames?: boolean, queueLock?: string | null, estimateMb?: number | null, cutWindow?: { at: number, dur: number } | null }} job */ export function renderArgv({ manifestPath, outDir, full, xfade, keepFrames = false, queueLock = queueLockScript(), estimateMb = renderEstimateMb("render"), cutWindow = null }) { const build = [ process.execPath, path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"), manifestPath, "--out", outDir, "--progress", "ndjson", "--skip-fetch", "--continue-on-error", ...(xfade ? [] : ["--no-xfade"]), ...(full ? [] : ["--no-chapters"]), ...(keepFrames ? ["--keep-frames"] : []), ...(cutWindow ? ["--cut-window", String(cutWindow.at), String(cutWindow.dur)] : []), ]; if (!queueLock) return build; const estimate = Number(estimateMb) > 0 ? ["--estimate", String(Math.round(Number(estimateMb)))] : []; return [process.execPath, queueLock, "--heavy", ...estimate, "--", ...build]; } /** * What a take's render declares to the heavy slot (render-estimate.mjs): the * render manifest's segments (a window's entries, a whole cut's) in its * batches, one when the take does not crossfade. A manifest it cannot read * declares a full batch. * * @param {{ manifestPath: string, xfade: boolean }} job * @param {Record} [env] */ export async function takeEstimateMb({ manifestPath, xfade }, env = process.env) { let manifest = null; try { manifest = JSON.parse(await readFile(/* turbopackIgnore: true */ manifestPath, "utf8")); } catch { return renderEstimateMb("render", env); } let batch; try { batch = xfadeBatchSize(manifest?.render ?? {}, env); } catch { batch = undefined; } return manifestEstimateMb(manifest, env, { xfade, batch }); } /** * Render one take. Resolves to the file build-video wrote (the default * variant's deliverable path inside the take's out/); rejects with the * entries that failed, or the exit code. * * @param {import("./takeMaker.mjs").RenderJob} job * @returns {Promise<{ file: string }>} */ export async function renderTake(job) { const argv = renderArgv({ ...job, estimateMb: job.estimateMb !== undefined ? job.estimateMb : await takeEstimateMb(job) }); job.log(`$ ${argv.join(" ")}`); if (job.signal?.aborted) throw new Error("the render was cancelled before it started"); return new Promise((resolve, reject) => { const child = spawn(argv[0], argv.slice(1), { // In the checkout, so queue-lock finds the checkout's lock. cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), stdio: ["ignore", "pipe", "pipe"], // ITS OWN PROCESS GROUP, so a cancel (takeCancel.mjs) stops the whole // render -- queue-lock, build-video and every ffmpeg under it -- and // nothing else: this process's group may be a terminal's or a script's. detached: true, }); // Stopping it: TERM to the group, KILL a grace later. A signal to THIS // process (the job runner's Stop, Ctrl-C) is passed on to the group too -- // the render no longer shares this process's group, and must not outlive it. /** @type {string | null} */ let stopped = null; const killGroup = (sig) => { try { if (child.pid) process.kill(-child.pid, sig); } catch { /* already gone */ } }; const stop = (why) => { if (stopped) return; stopped = why; killGroup("SIGTERM"); setTimeout(() => killGroup("SIGKILL"), RENDER_KILL_GRACE_MS).unref(); }; const onAbort = () => stop("cancelled"); job.signal?.addEventListener("abort", onAbort, { once: true }); /** @type {Array<[NodeJS.Signals, () => void]>} */ const forward = []; for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) { const h = () => stop(sig); forward.push([sig, h]); process.on(sig, h); } const settle = () => { job.signal?.removeEventListener("abort", onAbort); for (const [sig, h] of forward) process.off(sig, h); }; const failed = []; let buf = ""; child.stdout.on("data", (b) => { buf += b.toString(); const lines = buf.split("\n"); buf = lines.pop() ?? ""; for (const line of lines) { if (!line.trim()) continue; if (line.startsWith("{")) { try { const ev = JSON.parse(line); if (ev?.ev === "entry-failed") failed.push(`${ev.id}: ${ev.error ?? ev.message ?? "failed"}`); job.emit(ev); continue; } catch { /* a line of prose after all */ } } job.log(line); } }); child.stderr.on("data", (b) => { for (const line of b.toString().split("\n")) if (line.trim()) job.log(line); }); child.on("error", (e) => { settle(); reject(e); }); child.on("close", (code) => { settle(); if (stopped) { reject(new Error(stopped === "cancelled" ? "the render was cancelled" : `the render was stopped (${stopped})`)); return; } if (code === 0 && !failed.length) { resolve({ file: job.cutWindow ? cutWindowFile(job.outDir, job.slug, DEFAULT_VARIANT) : variantPaths(job.outDir, job.slug, DEFAULT_VARIANT).final }); return; } reject( new Error( failed.length ? `${failed.length} entr${failed.length === 1 ? "y" : "ies"} could not be cut: ${failed.join("; ")}` : `build-video exited ${code}`, ), ); }); }); } /** A file's length in seconds (ffprobe), or null. */ export async function probeSeconds(file) { try { const { stdout } = await execFileP(process.env.FFPROBE_BIN ?? "ffprobe", [ "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file, ]); const n = Number(String(stdout).trim()); return Number.isFinite(n) ? n : null; } catch { return null; } }