// THE TAKE MAKER (release 33): a take is the project's manifest with one // change applied, rendered beside it, so two ways of cutting the same part can // be watched side by side (takes.mjs is the contract it writes). // // makeTake(projectDir, spec) one take: copy the manifest, apply the // style's patch then the take's own (RFC 7386 // merge patches), render, write take.json // makeTakes(projectDir, recipe) a recipe's takes, one after another // pickTake(project, takeId) "Use this take": the take's manifest over // the project's, through the manifest writer // // What a take is made of, on disk: // // takes//video.manifest.json the WHOLE patched manifest -- what a pick // copies over the project's // takes//preview.mp4 the render (the window, or the full cut) // takes//out/.mp4 the same file, a HARD LINK, where a build // leaves its cut: `umtool variants --take` // and Deliver make the ladder of it (where // the link cannot be made -- out/ on another // filesystem -- they read the preview) // takes//out/ the take's own render scratch; its // clips-raw/ and narration/ are LINKS to the // project's out/ (the fetched media is // reused, never copied, never fetched) // takes//take.json written LAST, only when the preview // exists: until then the directory is a // work dir, which the listing ignores // // THE WINDOW. `{ at, dur }` renders the entries of the cut that the window // [at, at + dur] touches -- timed by the project's last deck schedule when // there is one, else by the manifest's own lengths -- as a cut of their own: // a fast build of just those entries. Not build-video's `--chrome-preview` // (it needs every segment already built in the take's out/, and the project's // segments, linked in, would show the old cut for any change that re-cuts a // clip) and not `--preview` (the rail's, over a cached concat). Every take of a // group made with the same window covers the same entries, whatever its patch // does to their lengths. `"full"` renders the whole cut, fast. // // THE RENDER is injected (tests pass a stub); the real one is takeRender.mjs: // build-video.mjs through the heavy slot (scripts/queue-lock.mjs --heavy). // // Plain ESM: the CLI (`umtool take`) runs it with bare node, and the app's // pages import the parts they show (the styles, the staleness check). import { resolvePresetLayers } from "umtool-report-to-video/presets"; import { createHash } from "node:crypto"; import { link, lstat, mkdir, readFile, readdir, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { mergePatch } from "umtool-report-to-video/montage-styles"; import { postItemSeconds } from "umtool-report-to-video/post-item"; import { videoSeconds } from "umtool-report-to-video/video-entry"; import { gappedLength, renderGaps } from "umtool-report-to-video/gaps"; import { cutSlurState } from "umtool-report-to-video/post-slurs"; import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings"; import { markKeepFrames } from "umtool-report-to-video/prune-frames"; import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs"; import { REPORTS_ROOT } from "../paths.mjs"; import { replaceManifest } from "./manifest.mjs"; import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { autoPickTake, frozenBaseText, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, BASE_FILE, DRAFT_FILE, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST = "video.manifest.json"; export const PREVIEW = "preview.mp4"; /** The recipe `umtool takes make` reads when none is named. */ export const RECIPE_FILE = "recipe.json"; /** The recipe "Make all styles" writes (its own name: a hand-written recipe.json is never overwritten). */ export const ALL_STYLES_RECIPE = "all-styles.recipe.json"; export const DEFAULT_GROUP = "takes"; export const DEFAULT_WINDOW = { at: 0, dur: 60 }; /** * A QUICK render: what the render manifest gets on top of the take, never the * take's own manifest -- so a pick never carries an audition's encode setting * into the deliverable. Every take of a group made quick is encoded alike. */ export const QUICK_RENDER = Object.freeze({ render: Object.freeze({ preset: "veryfast" }) }); /** The project's out/ entries a take's out/ links to: the fetched media and the synthesized voices. */ export const SHARED_OUT = ["clips-raw", "narration"]; /** Where a take's render manifest sits while it renders: beside the project's, so its relative paths hold. */ export const renderManifestPath = (projectDir, id) => path.join(projectDir, `.take-${id}.render.json`); const serialise = (m) => JSON.stringify(m, null, 2) + "\n"; export const hashText = (text) => createHash("sha256").update(text).digest("hex"); /** @param {unknown} v @returns {v is Record} */ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v))); // --------------------------------------------------------------------------- // The words for what a merge patch changes. // --------------------------------------------------------------------------- // mergePatch is lane M3's (report-to-video/montage-styles.mjs): the same // RFC 7386 the styles are written for -- objects merge, `null` removes a key, // anything else (an array included) replaces the value whole -- one // implementation, re-exported here for the take maker's callers. export { mergePatch }; /** * Every leaf a merge patch sets, as a dotted path: a non-object value, a * `null` (a removal) or an empty object. `{ render: { montage: { cut: "flash" } } }` * → `[["render.montage.cut", "flash"]]`. * * @param {unknown} patch * @param {string} [prefix] * @returns {Array<[string, unknown]>} */ export function patchLeaves(patch, prefix = "") { if (!isObj(patch)) return prefix ? [[prefix, patch]] : []; const keys = Object.keys(patch); if (!keys.length) return prefix ? [[prefix, {}]] : []; return keys.flatMap((k) => patchLeaves(patch[k], prefix ? `${prefix}.${k}` : k)); } /** The value at a dotted path, or undefined. */ export function getPath(obj, dotted) { let cur = obj; for (const k of dotted.split(".")) { if (!isObj(cur) && !Array.isArray(cur)) return undefined; cur = /** @type {any} */ (cur)[k]; } return cur; } /** A value in a change line: short and plain. */ export function fmtValue(v) { if (v === undefined || v === null) return "none"; if (typeof v === "string") return v; if (typeof v === "number" || typeof v === "boolean") return String(v); const json = JSON.stringify(v); if (json.length <= 60) return json; return Array.isArray(v) ? `${v.length} items` : `${Object.keys(v).length} settings`; } /** * One plain line per leaf the patches change, in the order the patches name * them (a later patch's line replaces an earlier one's for the same path): * `render.montage.cut: flash`, `render.crf: 34 (was 30)`, * `render.montage: removed`. A leaf whose value comes out the same as before * is not a change and has no line. * * @param {unknown} before the manifest the patches were applied to * @param {unknown} after the manifest they made * @param {unknown[]} patches * @returns {string[]} */ export function changeLines(before, after, patches) { const lines = new Map(); for (const p of patches) { for (const [dotted] of patchLeaves(p)) { const was = getPath(before, dotted); const now = getPath(after, dotted); lines.delete(dotted); if (JSON.stringify(was) === JSON.stringify(now)) continue; if (now === undefined) { lines.set(dotted, `${dotted}: removed`); continue; } const scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v); const tail = was !== undefined && scalar(was) && scalar(now) ? ` (was ${fmtValue(was)})` : ""; lines.set(dotted, `${dotted}: ${fmtValue(now)}${tail}`); } } return [...lines.values()]; } /** * `--set render.montage.cut=flash` as a patch. The value is JSON when it * parses (`3`, `true`, `null`, `{"mode":"snap"}`), else the string itself. * * @param {string[]} sets * @returns {Record} */ export function patchFromSets(sets) { /** @type {Record} */ const out = {}; for (const s of sets) { const eq = s.indexOf("="); if (eq <= 0) throw new Error(`--set takes path=value, not ${JSON.stringify(s)}`); const keys = s.slice(0, eq).split("."); if (keys.some((k) => !k)) throw new Error(`--set: ${JSON.stringify(s.slice(0, eq))} is not a dotted path`); const raw = s.slice(eq + 1); let value; try { value = JSON.parse(raw); } catch { value = raw; } let cur = out; for (const k of keys.slice(0, -1)) { if (!isObj(cur[k])) cur[k] = {}; cur = cur[k]; } cur[keys[keys.length - 1]] = value; } return out; } // --------------------------------------------------------------------------- // The styles (lane M3's report-to-video/montage-styles.mjs). // --------------------------------------------------------------------------- /** * Where the styles are read from: report-to-video/montage-styles.mjs, unless * E2E_UMTOOL_MONTAGE_STYLES names a module of the same shape (the e2e's stub). */ export function montageStylesFile(env = process.env) { return env.E2E_UMTOOL_MONTAGE_STYLES || path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "montage-styles.mjs"); } /** * The named montage styles: `{ name: { label, summary, patch } }`, loaded at * run time. A missing module is no styles, not an error (`error` says why); * an entry that is not the shape is dropped and named in `skipped`. * * @param {{ file?: string }} [opts] * @returns {Promise<{ styles: Record }>, error: string | null, skipped: string[] }>} */ export async function loadMontageStyles({ file = montageStylesFile() } = {}) { let mod; try { const href = pathToFileURL(file).href; mod = await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ href); } catch (err) { const code = /** @type {any} */ (err)?.code; const missing = code === "ERR_MODULE_NOT_FOUND" && String(/** @type {any} */ (err)?.message ?? "").includes(path.basename(file)); return { styles: {}, error: missing ? null : `the montage styles did not load: ${err instanceof Error ? err.message : err}`, skipped: [] }; } const raw = mod?.MONTAGE_STYLES; /** @type {Record }>} */ const styles = {}; const skipped = []; if (isObj(raw)) { for (const [name, s] of Object.entries(raw)) { if (isObj(s) && typeof s.label === "string" && isObj(s.patch)) { styles[name] = { label: s.label, summary: typeof s.summary === "string" ? s.summary : "", patch: clone(s.patch) }; } else skipped.push(name); } } return { styles, error: raw === undefined ? "montage-styles.mjs exports no MONTAGE_STYLES" : null, skipped }; } // --------------------------------------------------------------------------- // The window. // --------------------------------------------------------------------------- /** * An entry's length by the manifest's own numbers: a clip's cut less its gaps (gaps.mjs: the seconds it plays, as * the build and Play the cut count it -- not the cut's span, which put a window past a gapped clip that many seconds * early), a post item's rule (post-item.mjs), else `seconds`, else 4 s. Under `render.montage` (the cut's `render`) * a clip cuts to its phrase and applies no gaps (gaps.mjs renderGaps): its whole cut. * * @param {Record} e * @param {Record | null} [render] */ export function estimatedSeconds(e, render = null) { if (e?.type === "post") return postItemSeconds(e); // A video entry (video-entry.mjs): its span and its hold (a take's hard cuts: no lead). if (e?.type === "video") return videoSeconds(e, 0); if (e?.type === "clip") { const a = Number(e.cutStart ?? e.start); const b = Number(e.cutEnd ?? e.end); if (Number.isFinite(a) && Number.isFinite(b) && b > a) return gappedLength(a, b, renderGaps(e, render ?? {})); } const s = Number(e?.seconds); return Number.isFinite(s) && s > 0 ? s : 4; } /** The entries the default cut plays (build-video's selectVariant, sourced): untagged, or tagged sourced. */ export const sourcedEntries = (timeline) => (Array.isArray(timeline) ? timeline : []).filter((e) => isObj(e) && (!e.variant || e.variant === "sourced")); /** * The entries a window of the cut touches, in order. * * Timed by `schedule` (the deck's out/sourced/schedule.json: `segments[{ id, * start, duration }]`) when it names every entry, else by estimatedSeconds * laid end to end. At least one entry: a window past the end gets the last. * A schedule built before clips were inserted misses them, so a cut edited * since its last build is timed by the estimates; `missing` names the entries * the schedule did not time (all of them when there is none). * * @param {Array>} timeline * @param {{ at: number, dur: number }} win * @param {{ segments?: Array<{ id: string, start: number, duration: number }> } | null} [schedule] * @param {Record | null} [render] the cut's render (estimatedSeconds: a montage applies no gaps) * @returns {{ ids: string[], basis: "schedule" | "estimate", total: number, missing: string[] }} */ export function windowEntries(timeline, win, schedule = null, render = null) { const entries = sourcedEntries(timeline); if (!entries.length) throw new Error("the manifest's timeline is empty"); const segs = new Map((Array.isArray(schedule?.segments) ? schedule.segments : []).filter(isObj).map((s) => [s.id, s])); const missing = entries .filter((e) => { const s = segs.get(e.id); return !(s && Number.isFinite(Number(s.start)) && Number.isFinite(Number(s.duration))); }) .map((e) => e.id); const useSchedule = missing.length === 0; let t = 0; const spans = entries.map((e) => { if (useSchedule) { const s = /** @type {any} */ (segs.get(e.id)); return { id: e.id, from: Number(s.start), to: Number(s.start) + Number(s.duration) }; } const span = { id: e.id, from: t, to: t + estimatedSeconds(e, render) }; t = span.to; return span; }); const total = Math.max(...spans.map((s) => s.to)); const from = win.at; const to = win.at + win.dur; let ids = spans.filter((s) => s.from < to && s.to > from).map((s) => s.id); if (!ids.length) ids = [spans[spans.length - 1].id]; return { ids, basis: useSchedule ? "schedule" : "estimate", total, missing }; } /** * The take log's line about what timed the window: the deck's schedule (and * whether it is older than the manifest -- a re-trim since the last build * moves the window's edges), or the estimates and why. * * @param {{ ids: string[], basis: string, missing: string[] }} covered * @param {{ schedule: boolean, scheduleOlder: boolean }} facts */ export function windowBasisLine(covered, { schedule, scheduleOlder }) { const n = covered.ids.length; const what = `the window covers ${n} entr${n === 1 ? "y" : "ies"} (${covered.ids.join(", ")})`; if (covered.basis === "schedule") { return `${what}, timed by out/sourced/schedule.json${scheduleOlder ? " — older than the manifest: a clip re-cut since the last build may move the window's edges" : ""}`; } if (!schedule) return `${what}, timed by the manifest's own lengths (estimates): there is no out/sourced/schedule.json — build the cut for exact times`; const few = covered.missing.slice(0, 6).join(", ") + (covered.missing.length > 6 ? `, +${covered.missing.length - 6} more` : ""); return `${what}, timed by the manifest's own lengths (estimates): out/sourced/schedule.json${scheduleOlder ? " is older than the manifest and" : ""} does not time ${few} — rebuild the cut for exact times`; } /** * The window's ids with the entries a take's patch ADDS among them. The window * is timed against the project's own timeline (windowEntries), which has never * heard of a clip only the patch carries, so such a clip was never in a * windowed take. One the patch puts right after a covered entry (or after * another such added one) is kept, in the take's order; one beside nothing the * window covers stays out, as it would for any clip outside the window. * * @param {Array>} takeTimeline * @param {Array>} baseTimeline * @param {string[]} ids * @returns {string[]} */ export function withPatchEntries(takeTimeline, baseTimeline, ids) { const inBase = new Set(sourcedEntries(baseTimeline).map((e) => e.id)); const keep = new Set(ids); const out = []; let prevKept = false; for (const e of sourcedEntries(takeTimeline)) { const added = !inBase.has(e.id); const kept = keep.has(e.id) || (added && prevKept); if (kept) out.push(e.id); prevKept = kept; } // Ids the take no longer holds are left for the caller's `present` check. for (const id of ids) if (!out.includes(id)) out.push(id); return out; } /** * The manifest a window renders: `manifest` with only `ids` in its timeline * (the sourced ones), and everything that names a clip outside it dropped -- * the build refuses a reference to a clip its timeline does not hold: * * - a post whose `attachTo` is outside; * - a deck marker (`render.chrome.deck.markers`) whose `after` is outside; * - a deck claim check (`render.chrome.deck.claims`): a count claim whose * `at` is outside. A goalpost whose steps STRADDLE the window's edge is * CLIPPED to the steps inside it -- the window keeps a straddling clip * (windowEntries), so it keeps the part of the claim that clip carries; * a goalpost with no step inside is dropped. * - an effect's clip list (`render.chrome.fx`): `kineticQuote.clips`, `redact.clips` and `glitch.clips` keep the * clips inside (a glitch's only with a clip right before it: it tears at that cut), `thenNow.pairs` the pairs * with both ends inside; an effect left with none is off in the window. * * The kept ones need no re-timing: each names a clip by id, and its `t` is a * source second of that clip, which the window renders whole. */ export function windowManifest(manifest, ids) { const keep = new Set(ids); const m = clone(manifest); m.timeline = sourcedEntries(m.timeline).filter((e) => keep.has(e.id)); if (Array.isArray(m.posts)) m.posts = m.posts.filter((p) => !p?.attachTo || keep.has(p.attachTo)); const deck = m.render?.chrome?.deck; if (isObj(deck)) { const inside = (id) => typeof id === "string" && keep.has(id.trim()); if (Array.isArray(deck.markers)) deck.markers = deck.markers.filter((mk) => !isObj(mk) || inside(mk.after)); if (Array.isArray(deck.claims)) { deck.claims = deck.claims.flatMap((c) => { if (!isObj(c)) return [c]; if (c.kind === "goalpost" && Array.isArray(c.steps)) { const steps = c.steps.filter((st) => !isObj(st) || inside(st.at)); return steps.length ? [{ ...c, steps }] : []; } if (c.at !== undefined) return inside(c.at) ? [c] : []; return [c]; }); } } // The effects that name clips (fx.mjs validateFxEntries refuses a name the cut does not hold -- rev9-a9, 12 Nov: // `take --preview --at … --dur …` was refused with "render.chrome.fx.glitch.clips names k06, which is not a clip // of the cut"). A list keeps the clips inside; an effect left naming none is off in the window (an empty list is // not one fx.mjs takes). The glitch tears at the cut INTO a clip, so a named clip stays only with a clip right // before it in the window; a then/now pair needs both its ends. const fx = m.render?.chrome?.fx; if (isObj(fx)) { const at = new Map(m.timeline.map((e, i) => [e?.id, i])); const isClip = (id) => typeof id === "string" && m.timeline[at.get(id)]?.type === "clip"; for (const k of ["kineticQuote", "redact"]) { if (!isObj(fx[k]) || !Array.isArray(fx[k].clips)) continue; const clips = fx[k].clips.filter(isClip); if (clips.length) fx[k].clips = clips; else delete fx[k]; } // Only a glitch on "clips" reads its list (fx.mjs); in another mode the list is not looked at, so it is left // alone -- and the glitch with it. if (isObj(fx.glitch) && fx.glitch.on === "clips" && Array.isArray(fx.glitch.clips)) { const clips = fx.glitch.clips.filter((id) => isClip(id) && m.timeline[at.get(id) - 1]?.type === "clip"); if (clips.length) fx.glitch.clips = clips; else delete fx.glitch; } if (isObj(fx.thenNow) && Array.isArray(fx.thenNow.pairs)) { const pairs = fx.thenNow.pairs.filter((p) => !isObj(p) || (isClip(p.then) && isClip(p.now))); if (pairs.length) fx.thenNow.pairs = pairs; else delete fx.thenNow; } if (!Object.keys(fx).length) delete m.render.chrome.fx; } return m; } /** A window from the CLI's or a form's words: "full", or at/dur in seconds. */ export function normalizeWindow(w) { if (w === undefined || w === null || w === "") return { ...DEFAULT_WINDOW }; const v = parseWindow(w); if (!v) throw new Error('a window is "full" or { at ≥ 0, dur > 0 } in seconds'); return v; } // --------------------------------------------------------------------------- // Making a take. // --------------------------------------------------------------------------- /** * @typedef {{ * id: string, label: string, group?: string, kind?: string, summary?: string, * style?: string | null, patch?: Record | null, * window?: "full" | { at: number, dur: number } | null, order?: number, quick?: boolean, * }} TakeSpec * * @typedef {{ * manifestPath: string, outDir: string, slug: string, full: boolean, xfade: boolean, * keepFrames?: boolean, estimateMb?: number | null, cutWindow?: { at: number, dur: number } | null, * emit: (ev: Record) => void, log: (line: string) => void, * signal?: AbortSignal, * }} RenderJob * `signal`: a cancel (takeCancel.mjs) -- the render stops its process group and rejects. * @typedef {(job: RenderJob) => Promise<{ file: string }>} RenderFn */ /** A take spec, checked. Returns the spec with its defaults; throws what is wrong. */ export function checkSpec(spec) { if (!isObj(spec)) throw new Error("a take is an object"); if (!isTakeId(spec.id)) throw new Error(`id must be lower-case letters, digits and dashes (${JSON.stringify(spec.id ?? null)})`); const label = typeof spec.label === "string" ? spec.label.trim() : ""; if (!label) throw new Error(`${spec.id}: a take needs a label`); const group = typeof spec.group === "string" && spec.group.trim() ? spec.group.trim() : DEFAULT_GROUP; if (spec.kind !== undefined && spec.kind !== null && !TAKE_KINDS.includes(spec.kind)) { throw new Error(`${spec.id}: kind must be one of ${TAKE_KINDS.join(", ")}`); } if (spec.style !== undefined && spec.style !== null && (typeof spec.style !== "string" || !spec.style.trim())) { throw new Error(`${spec.id}: style is a style's name`); } if (spec.patch !== undefined && spec.patch !== null && !isObj(spec.patch)) throw new Error(`${spec.id}: patch must be a JSON object`); return { id: spec.id, label, group, kind: spec.kind ?? null, summary: typeof spec.summary === "string" ? spec.summary.trim() : "", style: typeof spec.style === "string" ? spec.style.trim() : null, patch: isObj(spec.patch) ? spec.patch : null, window: spec.window === "full" ? "full" : normalizeWindow(spec.window), order: typeof spec.order === "number" && Number.isFinite(spec.order) ? spec.order : null, quick: spec.quick === true, }; } async function readJson(file) { try { return JSON.parse(await readFile(file, "utf8")); } catch { return null; } } const exists = (p) => lstat(p).then(() => true, () => false); /** * Link the project's shared out/ entries into the take's out/ (absolute links * to the PROJECT's path, so a media root re-pointed under it keeps working). * One that is already there -- a link or a real directory -- is left alone. */ export async function linkSharedOut(projectDir, takeOut) { const linked = []; for (const name of SHARED_OUT) { const src = path.join(projectDir, "out", name); const dst = path.join(takeOut, name); if (!(await stat(src).then((s) => s.isDirectory(), () => false))) continue; if (await exists(dst)) { // An EMPTY real directory (a build that failed before its first fetch made it) holds nothing: the link replaces it. const empty = await lstat(dst).then((st) => st.isDirectory() && !st.isSymbolicLink(), () => false) && (await readdir(dst).catch(() => [null])).length === 0; if (!empty) continue; await rmdir(dst); } await symlink(src, dst); linked.push(name); } return linked; } /** * Make one take (see the top of the file). Skipped -- `{ skipped: true }` -- * when take.json exists and `force` is not set. * * @param {string} projectDir * @param {TakeSpec} rawSpec * @param {{ force?: boolean, render?: RenderFn, probe?: (file: string) => Promise, * styles?: Record }>, * emit?: (ev: Record) => void, log?: (line: string) => void, * ensureOut?: (dir: string) => Promise, now?: () => Date, clock?: () => number, * from?: string | null, keepFrames?: boolean }} [opts] * `from`: another take whose built segments, chrome renders and crossfade * batches are hard-linked in before the render (takeFrom.mjs), so the build * reuses whatever still matches. `keepFrames`: the build keeps its chrome * frames after the mux (build-video --keep-frames), for a later `from`, and * the take is marked (out/.keep-frames/asked.json) so a later build of it * sets its frames aside rather than pruning them (prune-frames.mjs). * `pruneAfter: false`: no prune after the take is made (see below). * * While it builds, the take holds a build lock (`takes//.building.json`, * naming `from`), so nothing prunes its work or its base's. Once it is made, * the project's takes are pruned by its policy, this one kept, and what that * freed is said in the log (takePrune.mjs; UMTOOL_PRUNE_AFTER_BUILD=0 or * `"afterBuild": false` in takes/prune.json turns it off). */ export async function makeTake(projectDir, rawSpec, opts = {}) { const prune = await import("./takePrune.mjs"); const cancel = await import("./takeCancel.mjs"); // EVERY RENDER RECORDS ITSELF (renderRecord.mjs): takes//render.json and // the full render.log, opened once the take's directory exists. What is said // before then is kept and written first. `opts.record: false` keeps none. const recordMod = opts.record === false ? null : await import("./renderRecord.mjs"); const id = typeof rawSpec?.id === "string" && isTakeId(rawSpec.id) ? rawSpec.id : null; /** @type {any} */ let rec = null; /** @type {string[]} */ const earlier = []; const baseLog = opts.log ?? (() => {}); const baseEmit = opts.emit ?? (() => {}); const log = (line) => { if (rec) rec.line(line); else if (recordMod) earlier.push(String(line)); baseLog(line); }; const emit = (ev) => { if (rec) rec.event(ev); baseEmit(ev); }; const label = typeof rawSpec?.label === "string" ? rawSpec.label : null; const openRecord = async (takeDir) => { if (!recordMod || !id || rec) return; rec = await recordMod .openRenderRecord(takeDir, { take: id, projectDir, project: opts.projectId ?? null, label, argv: opts.argv, reportsRoot: opts.reportsRoot === undefined ? REPORTS_ROOT : opts.reportsRoot, earlier, }) .catch(() => null); }; let lockFile = null; // CANCEL (takeCancel.mjs): while the take holds its build lock it answers a // cancel request -- its render stopped, the take marked cancelled. const abort = new AbortController(); /** @type {Record | null} */ let asked = null; let stopWatch = null; let rebuild = false; const onTakeDir = async (takeDir, tid) => { await openRecord(takeDir); lockFile = await prune.writeBuildLock(takeDir, { take: tid, from: opts.from ?? null, ...(label ? { label } : {}) }).catch(() => null); rebuild = await stat(path.join(takeDir, TAKE_FILE)).then(() => true, () => false); stopWatch = cancel.watchCancel(takeDir, (req) => { asked = req; log(`${tid}: cancel asked${req?.by ? ` by ${req.by}` : ""} — stopping the render`); abort.abort(); }); }; let r; try { r = await makeTakeLocked(projectDir, rawSpec, { ...opts, log, emit, onTakeDir, signal: abort.signal }); } catch (e) { // A refusal before the take's directory was made: recorded only for a take that exists (a rebuild). if (!rec && id && recordMod) { const dir = path.join(takesDirOf(projectDir), id); if (await stat(path.join(dir, TAKE_FILE)).then(() => true, () => false)) await openRecord(dir); } if (abort.signal.aborted && id) { const by = String(asked?.by ?? ""); await cancel.markCancelled(projectDir, id, { by, label, rebuild }).catch(() => {}); const err = new cancel.TakeCancelled(id, by); await rec?.fail(err, { cancelled: true }); throw err; } await rec?.fail(e); throw e; } finally { stopWatch?.(); if (lockFile) await prune.removeBuildLock(lockFile); } // Made: a cancel asked too late to stop it is moot, and an earlier cancelled run's mark is history. if (!r.skipped) { const dir = path.join(takesDirOf(projectDir), r.id); await Promise.all([unlink(path.join(dir, cancel.CANCEL_FILE)).catch(() => {}), unlink(path.join(dir, cancel.CANCELLED_FILE)).catch(() => {})]); // done only with a non-empty mp4 (the record says failed otherwise, and so does this). const doc = await rec?.done({ mp4: path.join(dir, PREVIEW), seconds: r.take?.seconds ?? null }); if (doc && doc.state !== "done") throw new Error(doc.error ?? `take ${r.id}: the render left no mp4`); } if (!r.skipped && opts.pruneAfter !== false) { await prune.pruneAfterBuild(projectDir, { built: r.id, log: (line) => baseLog(`${r.id}: ${line}`) }); } return r; } /** * What a take renders, composed and not written: the project's manifest with the take's style and patch * (preset → manifest → style → take patch), the clip deck's rulings applied, windowed when the take has a * window. makeTake renders it; a preview or a changes reel (takePreview.mjs) renders the same. * * @param {string} projectDir * @param {ReturnType} spec * @param {{ styles?: Record }>, log?: (line: string) => void }} [opts] */ export async function composeTake(projectDir, spec, opts = {}) { const log = opts.log ?? (() => {}); // A SAVED VERSION renders its frozen manifest (takes//base.manifest.json), never the draft as it is now. const frozenText = await frozenBaseText(projectDir, spec.id); const baseText = frozenText ?? (await readFile(path.join(projectDir, MANIFEST), "utf8")); if (frozenText !== null) log(`${spec.id}: a saved version — rendering its frozen ${BASE_FILE}, not the draft`); const base = JSON.parse(baseText); const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); let stylePatch = null; if (spec.style) { stylePatch = styles[spec.style]?.patch ?? null; if (!stylePatch) { const known = Object.keys(styles); throw new Error(`unknown style "${spec.style}"${known.length ? ` — one of ${known.join(", ")}` : " (no montage styles are installed)"}`); } } const patches = [stylePatch, spec.patch].filter(Boolean); // preset → manifest → style → take patch (presets.mjs): a preset named by // the manifest or by a patch is the base layer under them all. const manifest = /** @type {Record} */ (resolvePresetLayers(base, patches)); if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error("the patched manifest has no timeline"); const changes = changeLines(resolvePresetLayers(base), manifest, patches); const kind = changes.length === 0 ? "reference" : (spec.kind ?? "different"); // The clip deck's rulings (report-to-video/montage-rulings.mjs), applied to // the WHOLE cut before it is windowed: a ruled-out clip leaves the window, // and the counter is numbered over every kept clip, so a window still counts // #31 of 70. The build applies them again over the render manifest beside // the project's, where they change nothing more. The take's own manifest // (what a pick copies) stays the manifest as written. const ruled = applyMontageRulings(manifest, await readMontageRulings(projectDir)); for (const line of rulingsLines(ruled)) log(`${spec.id}: ${line}`); // The render: the window's entries (timed against the project's, so every // take of a group covers the same ones), or the whole cut. let renderDoc = ruled.manifest; /** @type {null | { ids: string[], basis: string, total: number }} */ let covered = null; if (spec.window !== "full") { const scheduleFile = path.join(projectDir, "out", "sourced", "schedule.json"); const schedule = await readJson(scheduleFile); covered = windowEntries(base.timeline, spec.window, schedule, base.render ?? null); const [schedSt, manSt] = await Promise.all([stat(scheduleFile).catch(() => null), stat(path.join(projectDir, MANIFEST)).catch(() => null)]); log(`${spec.id}: ${windowBasisLine(covered, { schedule: !!schedule, scheduleOlder: !!(schedSt && manSt && schedSt.mtimeMs < manSt.mtimeMs) })}`); const present = new Set(sourcedEntries(ruled.manifest.timeline).map((e) => e.id)); let ids = withPatchEntries(ruled.manifest.timeline, base.timeline, covered.ids).filter((id) => present.has(id)); // A take whose patch REPLACES the timeline with entries of its own (a // tight version, walked) holds none of the project's entries to cover: // its window is timed over its OWN timeline instead (by the estimates -- // the deck's schedule names the project's entries). if (!ids.length && isObj(spec.patch) && Array.isArray(spec.patch.timeline) && !covered.ids.some((id) => present.has(id))) { covered = windowEntries(ruled.manifest.timeline, spec.window, null, ruled.manifest.render ?? null); log( `${spec.id}: none of those is in the take's own timeline — the window covers ${covered.ids.length} of ITS entries ` + `(${covered.ids.join(", ")}), timed by their own lengths`, ); ids = covered.ids.filter((id) => present.has(id)); } if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`); renderDoc = windowManifest(ruled.manifest, ids); } return { baseText, base, styles, manifest, changes, kind, patches, ruled, renderDoc, covered, frozen: frozenText !== null }; } /** makeTake's body; `onTakeDir` is called once the take's directory exists, before anything is linked or rendered. */ async function makeTakeLocked(projectDir, rawSpec, opts) { const spec = checkSpec(rawSpec); const emit = opts.emit ?? (() => {}); const log = opts.log ?? (() => {}); const now = opts.now ?? (() => new Date()); const takeDir = path.join(takesDirOf(projectDir), spec.id); const takeFile = path.join(takeDir, TAKE_FILE); const previous = await readJson(takeFile); if (previous && !opts.force) { emit({ ev: "take", id: spec.id, phase: "skipped" }); return { id: spec.id, skipped: true }; } // --from is checked before anything is written: a bad name leaves no work dir. const fromTake = opts.from ? await import("./takeFrom.mjs") : null; if (fromTake) await fromTake.fromTakeSourced(projectDir, spec.id, opts.from); const { baseText, styles, manifest, changes, kind, patches, renderDoc: composed, covered, frozen } = await composeTake(projectDir, spec, { styles: opts.styles, log }); let renderDoc = composed; if (spec.quick) renderDoc = /** @type {Record} */ (mergePatch(renderDoc, QUICK_RENDER)); // A clip ruled incorrect (the walk's verdict) still in what would render: // refused, by name, before anything is written -- `umtool check` calls it // blocking (clip-incorrect), and a take is a render like any other. const wrong = incorrectClips(renderDoc.timeline); if (wrong.length) throw new Error(`${spec.id}: ${wrong.map(incorrectWhy).join("; ")}`); // A clip whose quote the quote check did not hear where it plays (lane // one-clock, lib/report/quoteCheck.mjs): refused the same way, unless a // person ruled it (`quoteRuled`). No check on record refuses nothing. The // take's own current rows (`quote-check --take`) AND the project's: never // fewer refusals than the project's rows make for the same cut. { const { takeQuoteRefusals } = await import("./quoteCheck.mjs"); const unheard = await takeQuoteRefusals(projectDir, spec.id, renderDoc.timeline); if (unheard.length) { throw new Error( `${spec.id}: ${unheard.map((u) => u.why.replace("

", path.basename(projectDir))).join("; ")} ` + "(heard and right after all: umtool window

--quote-ruled)", ); } } await mkdir(takeDir, { recursive: true }); await opts.onTakeDir?.(takeDir, spec.id); const takeOut = path.join(takeDir, "out"); await (opts.ensureOut ?? ((d) => mkdir(d, { recursive: true })))(takeOut); const linked = await linkSharedOut(projectDir, takeOut); if (linked.length) log(`${spec.id}: reusing the project's ${linked.join(" and ")}`); // Asked once, kept: a later build of this take without --keep-frames sets // its chrome frames aside in out/.keep-frames/ rather than pruning them. if (opts.keepFrames === true) await markKeepFrames(takeOut, { now }); if (fromTake) { const got = await fromTake.linkFromTake(projectDir, spec.id, /** @type {string} */ (opts.from), takeOut); log( `${spec.id}: linked from ${opts.from}: ${got.segments} segment file(s), ` + `${got.frames.length ? got.frames.join(", ") : "no chrome frames"}, ${got.batches} crossfade batch(es), ` + `${got.chunks ?? 0} encode chunk(s)${got.records ? ` and ${got.records} chunk record(s)` : ""}` + `${got.ladder ? `, ${got.ladder} ladder chunk(s)` : ""}` + `${got.ladderFit?.length ? ` (the scale ${got.ladderFit.join(", ")} landed at)` : ""}` + `${(got.variants?.length ?? 1) > 1 ? ` (variants ${got.variants.join(", ")})` : ""} — reused where they still match`, ); // This take's own newer build, kept (takeFrom.mjs): said, so a re-run says why it did not start over. if (got.keptOwn?.length || got.keptOwnFrames?.length) { log( `${spec.id}: kept this take's own newer ` + [got.keptOwn?.length ? `${got.keptOwn.length} segment(s)` : null, got.keptOwnFrames?.length ? got.keptOwnFrames.join(", ") : null] .filter(Boolean).join(" and ") + ` (${opts.from}'s older ones kept beside them for reuse)`, ); } } // The take's manifest is written under a work name until the render is // done: a failed REBUILD must not leave the old preview beside a new manifest. const nextManifest = path.join(takeDir, `.next.${MANIFEST}`); await writeFile(nextManifest, serialise(manifest), "utf8"); const renderPath = renderManifestPath(projectDir, spec.id); await writeFile(renderPath, serialise(renderDoc), "utf8"); // The last make's hard link of preview.mp4 is unlinked first: a build that // wrote the cut in place would otherwise write INTO the old preview, and a // failed rebuild must leave the old take whole. const preview = path.join(takeDir, PREVIEW); await unlinkIfSameFile(path.join(takeOut, `${String(manifest.slug ?? "")}.mp4`), preview); // The draft pointer as the render starts (versions.mjs): a working take repoints it when it is made, but // only if nothing moved it meanwhile (an Open in draft during a long render keeps what was opened). const draftPointerAtStart = frozen ? null : await readFile(path.join(takesDirOf(projectDir), DRAFT_FILE), "utf8").catch(() => ""); const transition = Number(manifest.render?.transition ?? 0); const xfade = patches.some((p) => getPath(p, "render.transition") !== undefined) && transition > 0; emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null, basis: covered?.basis ?? null }); let file; // How long the render itself took (UI notes #18: a take's ETA is read from // the project's past renders, lib/report/takeEta.mjs): from the build's // first event -- after the heavy slot admitted it, so a wait at the slot's // door is not counted -- to its end. Recorded as take.json `renderSeconds`. const clock = opts.clock ?? Date.now; const renderStart = clock(); let firstEventAt = null; const timedEmit = (ev) => { if (firstEventAt === null && ev?.ev !== "take") firstEventAt = clock(); emit(ev); }; try { // A cancel asked while the take was being set up: no render at all. if (opts.signal?.aborted) throw new Error(`${spec.id}: cancelled before its render started`); const render = opts.render ?? (await import("./takeRender.mjs")).renderTake; ({ file } = await render({ manifestPath: renderPath, outDir: takeOut, slug: String(manifest.slug ?? ""), full: spec.window === "full", xfade, keepFrames: opts.keepFrames === true, emit: timedEmit, log, ...(opts.signal ? { signal: opts.signal } : {}), })); } catch (e) { // Stopped by a cancel: the half-made manifest goes too (a finished take's own is untouched). if (opts.signal?.aborted) await rm(nextManifest, { force: true }); throw e; } finally { await rm(renderPath, { force: true }); } const renderSeconds = Math.round((clock() - (firstEventAt ?? renderStart)) / 100) / 10; // A render that "succeeded" without a picture is a failure, never a take // (renderRecord.mjs): checked before the old preview is replaced. const made = await stat(file).catch(() => null); if (!made || !made.isFile()) throw new Error(`${spec.id}: the render exited 0 but wrote no mp4 (${file} is not there)`); if (made.size === 0) throw new Error(`${spec.id}: the render exited 0 but its mp4 is empty (0 bytes): ${file}`); await moveFile(file, preview); await keepBuildName(preview, file, (line) => log(`${spec.id}: ${line}`)); await rename(nextManifest, path.join(takeDir, MANIFEST)); const seconds = opts.probe ? await opts.probe(preview) : null; const listing = previous ? null : await listTakes(projectDir); const order = spec.order ?? (typeof previous?.order === "number" ? previous.order : Math.max(0, ...(listing?.takes ?? []).map((t) => t.order)) + 1); const styleLabel = spec.style ? styles[spec.style]?.label : null; const summary = spec.summary || (spec.style ? styles[spec.style]?.summary ?? "" : ""); const doc = { id: spec.id, group: spec.group, order, label: spec.label, kind, summary, changes: [...(styleLabel ? [`style: ${styleLabel}`] : []), ...changes], preview: PREVIEW, seconds: seconds === null || seconds === undefined ? null : Math.round(seconds * 100) / 100, builtAt: now().toISOString(), style: spec.style, patch: spec.patch, window: spec.window, ...(spec.quick ? { quick: true } : {}), ...(covered ? { entries: { ids: covered.ids, basis: covered.basis } } : {}), baseHash: hashText(baseText), // The take it was built from: the pruner keeps a kept take's base (takePrune.mjs). ...(opts.from ? { from: opts.from } : {}), // The render's own time, for the next take's ETA (takeEta.mjs). renderSeconds, // Which cut its post items are (post-slurs.mjs): censored, or the uncensored one (`umtool take … --uncensored`). ...(cutSlurState(manifest) ? { slurs: cutSlurState(manifest) } : {}), // A SAVED VERSION rendered (versions.mjs): still that version -- its frozen base is what was rendered. ...(previous?.version === true ? { version: true, ...(typeof previous.savedAt === "string" ? { savedAt: previous.savedAt } : {}), ...(typeof previous.draftedFrom === "string" && previous.draftedFrom ? { draftedFrom: previous.draftedFrom } : {}), } : {}), }; const tmp = tmpPathFor(takeFile); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); // A whole-cut take of the DRAFT as it is (not a frozen version re-rendered) is the draft's parent now (versions.mjs). if (!frozen && isWorkingTake(doc)) { const nowPointer = await readFile(path.join(takesDirOf(projectDir), DRAFT_FILE), "utf8").catch(() => ""); if (nowPointer === draftPointerAtStart) { const { writeDraft } = await import("./versions.mjs"); await writeDraft(projectDir, { from: spec.id, hash: doc.baseHash, at: doc.builtAt }).catch(() => {}); } else log(`${spec.id}: the draft was opened or saved while this rendered — its parent is left as that made it`); } // A whole-cut take of the manifest is its group's pick now (takes.mjs autoPickTake): mark only. const group = ((listing ?? (await listTakes(projectDir))).takes ?? []).filter((t) => t.group === doc.group).map((t) => t.id); const pick = await autoPickTake(projectDir, { ...doc, id: spec.id }, group).catch((e) => ({ picked: false, why: e instanceof Error ? e.message : String(e) })); if (pick.picked) log(`${spec.id}: the working cut's take now (picked: ${pick.why})`); else if (isWorkingTake(doc)) log(`${spec.id}: not picked — ${pick.why}`); emit({ ev: "take", id: spec.id, phase: "done", seconds: doc.seconds }); return { id: spec.id, skipped: false, take: doc }; } /** * A DRAFT take (walk a take): the take recorded -- its label, group, style, * patch and window -- with NOTHING rendered, so it can be walked (the bench * on the take's own timeline, takeEdit.mjs) before anybody pays for a build. * `umtool take

--id X --draft`; a later `umtool take

--id X --full` * renders it from its stored patch, edits and all (makeTake over it). * * takes//take.json `draft: true`, `preview` naming where the render * will go, `seconds`/`builtAt` null, and the * baseHash of the manifest it was drafted against * * The patch is applied here once, to check it makes a manifest with a * timeline (a patch that does not is refused now, not at the render), and to * write the take's `changes` lines. No take.json is written over a RENDERED * take (its preview would then sit beside a take that says it has none); * over a draft only with `force`. * * @param {string} projectDir * @param {TakeSpec} rawSpec `window` absent: the render's window is said when it is rendered * @param {{ force?: boolean, styles?: Record }>, now?: () => Date, draftedFrom?: string }} [opts] */ export async function draftTake(projectDir, rawSpec, opts = {}) { const spec = checkSpec(rawSpec); const window = rawSpec?.window === undefined || rawSpec?.window === null ? null : spec.window; const now = opts.now ?? (() => new Date()); const takeDir = path.join(takesDirOf(projectDir), spec.id); const takeFile = path.join(takeDir, TAKE_FILE); const previous = await readJson(takeFile); if (previous && previous.draft !== true) throw new Error(`take ${spec.id} is rendered — a draft needs an id of its own`); if (previous && !opts.force) throw new Error(`take ${spec.id} exists (a draft) — pass --force to record it again`); const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8"); const base = JSON.parse(baseText); const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); let stylePatch = null; if (spec.style) { stylePatch = styles[spec.style]?.patch ?? null; if (!stylePatch) { const known = Object.keys(styles); throw new Error(`unknown style "${spec.style}"${known.length ? ` — one of ${known.join(", ")}` : " (no montage styles are installed)"}`); } } const patches = [stylePatch, spec.patch].filter(Boolean); const manifest = patches.reduce((m, p) => mergePatch(m, p), base); if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error("the patched manifest has no timeline"); const changes = changeLines(base, manifest, patches); const styleLabel = spec.style ? styles[spec.style]?.label : null; const listing = await listTakes(projectDir); const order = spec.order ?? (typeof previous?.order === "number" ? previous.order : Math.max(0, ...listing.takes.filter((t) => t.id !== spec.id).map((t) => t.order)) + 1); const doc = { id: spec.id, group: spec.group, order, label: spec.label, kind: changes.length === 0 ? "reference" : (spec.kind ?? "different"), summary: spec.summary || (spec.style ? styles[spec.style]?.summary ?? "" : ""), changes: [...(styleLabel ? [`style: ${styleLabel}`] : []), ...changes], preview: PREVIEW, seconds: null, builtAt: null, style: spec.style, patch: spec.patch, window, ...(spec.quick ? { quick: true } : {}), // A draft made FROM another take (`--draft --from `): what a changes reel compares it with by default (takePreview.mjs). ...(typeof opts.draftedFrom === "string" && opts.draftedFrom ? { draftedFrom: opts.draftedFrom } : {}), draft: true, draftedAt: now().toISOString(), baseHash: hashText(baseText), }; await mkdir(takeDir, { recursive: true }); const tmp = tmpPathFor(takeFile); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); const clips = manifest.timeline.filter((e) => isObj(e) && e.type === "clip").length; return { id: spec.id, take: doc, clips, entries: manifest.timeline.length }; } /** Remove `file` when it is a hard link of `of` (the same inode); anything else is left. */ async function unlinkIfSameFile(file, of) { const [a, b] = await Promise.all([lstat(file).catch(() => null), lstat(of).catch(() => null)]); if (a && b && a.isFile() && a.ino === b.ino && a.dev === b.dev) await unlink(file); } /** * The render back where the build left it, as a hard link of the preview: the * take's out/ is then a built out/ like the project's (variants, Deliver). Not * possible across filesystems; the readers fall back to the preview then. */ async function keepBuildName(preview, file, log) { try { await link(preview, file); } catch (err) { log(`the render is only ${PREVIEW} (no ${path.basename(file)} link in out/: ${/** @type {any} */ (err)?.code ?? err})`); } } /** Rename, or copy and remove across filesystems (a take's out/ may be on the media root). */ async function moveFile(from, to) { try { await rename(from, to); } catch (err) { if (/** @type {any} */ (err)?.code !== "EXDEV") throw err; const { copyFile, unlink } = await import("node:fs/promises"); const tmp = tmpPathFor(to); await copyFile(from, tmp); await rename(tmp, to); await unlink(from).catch(() => {}); } } // --------------------------------------------------------------------------- // Recipes. // --------------------------------------------------------------------------- /** * A recipe, checked: `{ group?, window?, quick?, takes: [{ id, label, style?, * patch?, summary?, kind?, group?, window?, quick? }] }`. A take's own group, * window and quick win over the recipe's. Ids are unique. * * @param {unknown} raw * @returns {{ group: string, window: "full" | { at: number, dur: number }, quick: boolean, takes: ReturnType[] }} */ export function parseRecipe(raw) { if (!isObj(raw)) throw new Error("a recipe is an object"); const group = typeof raw.group === "string" && raw.group.trim() ? raw.group.trim() : DEFAULT_GROUP; const window = raw.window === "full" ? "full" : normalizeWindow(raw.window); const quick = raw.quick === true; if (!Array.isArray(raw.takes) || !raw.takes.length) throw new Error("a recipe needs takes: [...]"); const seen = new Set(); const takes = raw.takes.map((t, i) => { if (!isObj(t)) throw new Error(`takes[${i}] is not an object`); const spec = checkSpec({ group, window, quick, ...t }); if (seen.has(spec.id)) throw new Error(`take ${spec.id} is in the recipe twice`); seen.add(spec.id); return spec; }); return { group, window, quick, takes }; } /** * A recipe's takes, one after another (one render at a time). A take that * exists is skipped unless `force`; a take that fails is recorded and the next * one is made. `only` limits the run to those ids. * * @param {string} projectDir * @param {unknown} recipe * @param {Parameters[2] & { only?: string[] | null }} [opts] */ export async function makeTakes(projectDir, recipe, opts = {}) { const r = parseRecipe(recipe); const list = opts.only?.length ? r.takes.filter((t) => opts.only?.includes(t.id)) : r.takes; if (opts.only?.length && list.length !== opts.only.length) { const missing = opts.only.filter((id) => !r.takes.some((t) => t.id === id)); throw new Error(`not in the recipe: ${missing.join(", ")}`); } const needStyles = list.some((t) => t.style); const styles = opts.styles ?? (needStyles ? (await loadMontageStyles()).styles : {}); const results = []; for (const [i, spec] of list.entries()) { opts.emit?.({ ev: "take", id: spec.id, phase: "start", i: i + 1, n: list.length }); try { const done = await makeTake(projectDir, spec, { ...opts, styles }); results.push({ id: spec.id, status: done.skipped ? "skipped" : "made" }); } catch (err) { const error = err instanceof Error ? err.message : String(err); opts.emit?.({ ev: "take", id: spec.id, phase: "failed", error }); opts.log?.(`${spec.id}: failed — ${error}`); results.push({ id: spec.id, status: "failed", error }); } } return results; } /** * The recipe "Make all styles" runs: every style, one take each, with one * group and window. The take id is the style's name made into a take id. * * @param {Record} styles * @param {{ group?: string, window?: unknown, quick?: boolean }} [opts] */ export function allStylesRecipe(styles, { group = DEFAULT_GROUP, window = DEFAULT_WINDOW, quick = false } = {}) { const names = Object.keys(styles); if (!names.length) throw new Error("no montage styles are installed"); const used = new Set(); return { group, window, ...(quick ? { quick: true } : {}), takes: names.map((name) => { const id = uniqueTakeId(name, used); used.add(id); return { id, label: styles[name].label, style: name }; }), }; } /** A take id from any words: lower case, dashes, unique against `taken`. */ export function uniqueTakeId(words, taken = new Set()) { const base = String(words ?? "") .toLowerCase() .normalize("NFKD") .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 56) || "take"; const ok = /^[a-z0-9]/.test(base) ? base : `t-${base}`.slice(0, 56); if (!taken.has(ok)) return ok; for (let n = 2; ; n += 1) if (!taken.has(`${ok}-${n}`)) return `${ok}-${n}`; } // --------------------------------------------------------------------------- // Picking a take. // --------------------------------------------------------------------------- export class TakeStale extends Error { /** @param {string} message */ constructor(message) { super(message); this.name = "TakeStale"; } } /** * Has the project's manifest changed since the take was made? `null` when the * take does not say what it was made from (made by hand, before release 33). * * @param {string} projectDir * @param {{ baseHash?: string | null }} take */ export async function takeIsStale(projectDir, take) { if (!take.baseHash) return null; const text = await readFile(path.join(projectDir, MANIFEST), "utf8").catch(() => null); return text === null ? true : hashText(text) !== take.baseHash; } /** * A SAVED VERSION's manifest as the draft would hold it: its frozen base * (takes//base.manifest.json) byte for byte, or -- when a style or a patch * was laid over the version since (a "No intro" toggle) -- the base with them * merged (RFC 7386, no preset resolved: the draft names its preset as the base * did). null for a take with no frozen base. * * @param {string} projectDir * @param {string} takeId * @returns {Promise, exact: boolean }>} */ export async function versionManifestOf(projectDir, takeId) { const baseText = await frozenBaseText(projectDir, takeId); if (baseText === null) return null; const base = JSON.parse(baseText); const doc = await readJson(path.join(takesDirOf(projectDir), takeId, TAKE_FILE)); let stylePatch = null; if (typeof doc?.style === "string" && doc.style.trim()) stylePatch = (await loadMontageStyles()).styles[doc.style.trim()]?.patch ?? null; const patches = [stylePatch, isObj(doc?.patch) ? doc.patch : null].filter(Boolean); if (!patches.length) return { text: baseText, manifest: base, exact: true }; const manifest = /** @type {Record} */ (patches.reduce((m, p) => mergePatch(m, p), base)); return { text: serialise(manifest), manifest, exact: false }; } /** * "Use this take": the take's video.manifest.json over the project's, through * the manifest writer (replaceManifest: the auto snapshot `auto-before-pick-take`, * so "Undo last edit" takes it back) inside withEditNotes, then the pick in * verdicts.json (one per group). * * REFUSED (TakeStale) when the project's manifest is not the one the take was * made from -- a pick would throw away whatever changed since -- unless * `anyway`. A take that does not record its base is refused the same way. * * @param {{ id: string, dir: string, kind: string }} project * @param {string} takeId * @param {{ anyway?: boolean, token?: string | null, now?: Date, pinned?: boolean }} [opts] * `pinned`: true pins the pick (no auto-pick over it), false unpins (takes.mjs setTakePicked) */ export async function pickTake(project, takeId, { anyway = false, token = null, now = new Date(), pinned = undefined } = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const listing = await listTakes(project.dir); const take = listing.takes.find((t) => t.id === takeId); if (!take) throw new Error(`no take ${takeId}`); // A SAVED VERSION (versions.mjs) is its frozen base, rendered or not: that is what a pick copies. const frozen = await versionManifestOf(project.dir, takeId); // A draft has no rendered manifest to use: "Make this the cut" (takeEdit.mjs promoteTake) applies its patch. if (take.draft && !frozen) throw new Error(`take ${takeId} is a draft — nothing rendered to use; make it the cut (umtool take ${project.id} --id ${takeId} --promote)`); const text = frozen ? frozen.text : await readFile(path.join(takesDirOf(project.dir), takeId, MANIFEST), "utf8").catch(() => null); if (text === null) throw new Error(`take ${takeId} has no ${MANIFEST} to use`); const manifest = JSON.parse(text); if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${takeId}'s ${MANIFEST} is not a manifest`); // Already the project's manifest (picked before): nothing to write, nothing to refuse. const current = await readFile(path.join(project.dir, MANIFEST), "utf8").catch(() => null); const same = current === text; if (!anyway && !same) { const stale = await takeIsStale(project.dir, take); if (stale === null) throw new TakeStale("This take does not record which manifest it was made from"); if (stale) throw new TakeStale("The project changed since this take was made"); } const { result, editNotes } = same ? { result: { snapshot: null, token: null }, editNotes: null } : await withEditNotes(project, () => replaceManifest(project.dir, manifest, { token, op: "pick-take" })); const group = listing.takes.filter((t) => t.group === take.group).map((t) => t.id); const { verdicts } = await setTakePicked(project.dir, takeId, group, { now, pinned }); return { take: takeId, group: take.group, snapshot: result.snapshot, token: result.token, editNotes, verdicts }; } // --------------------------------------------------------------------------- // The app's jobs: the CLI above, as job steps (lib/jobs.ts runs them). // --------------------------------------------------------------------------- /** * A take render's timeout: a window is minutes; the whole cut is the fast * build's own budget, and a cut that renders its on-screen chrome (`seconds`, * its estimated length) RENDER_BUDGET seconds of job per second of cut. */ export const takeTimeoutMs = (full, clipCount, seconds = 0) => (full ? Math.max(15 * 60_000, clipCount * 60_000, Math.round(seconds * RENDER_BUDGET * 1000)) : 15 * 60_000); const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); const windowArgs = (w) => (w === "full" ? ["--full"] : ["--at", String(w.at), "--dur", String(w.dur)]); /** * What a Takes-page button asks for, as the steps of one job. Every argument * is checked here first, so a bad request is a 400 and not a failed job. * * { take: { id?, label, group?, style?, patch?, window?, summary?, kind?, quick? }, force? } New take * { allStyles: { group?, window?, quick? }, force? } Make all styles * { rebuild: "" } Rebuild * any of them with `priority: true`: --priority, render mode for the render (renderMode.mjs) * * @param {{ id: string }} project * @param {Record} req * @param {{ styles: Record, existing: Array<{ id: string, window?: unknown }>, clipCount: number, seconds?: number }} ctx * @returns {{ kind: string, takes: string[], steps: Array<{ label: string, argv: string[], cwd: string, env: Record, ndjson: true, timeoutMs: number }> }} */ export function takeSteps(project, req, { styles, existing, clipCount, seconds = 0 }) { const ids = new Set(existing.map((t) => t.id)); const base = { cwd: UMTOOL_DIR, env: {}, ndjson: /** @type {const} */ (true) }; const cli = ["node", umtoolCli()]; const force = req.force === true ? ["--force"] : []; // "Give renders the machine" (the take panel's toggle): render mode for the // job's render (renderMode.mjs; `umtool take … --priority`). const priority = req.priority === true ? ["--priority"] : []; if (typeof req.rebuild === "string") { const t = existing.find((x) => x.id === req.rebuild); if (!t) throw new Error(`no take ${req.rebuild}`); // `window`: render it over this window rather than its own (a draft's // Render full / Render a window: a draft may not say one yet). const win = req.window === undefined || req.window === null ? null : req.window === "full" ? "full" : normalizeWindow(req.window); const full = (win ?? t.window) === "full"; return { kind: `take ${project.id} ${t.id} (${/** @type {any} */ (t).draft ? "render" : "rebuild"})`, takes: [t.id], steps: [{ ...base, label: `${/** @type {any} */ (t).draft ? "render" : "rebuild"} take ${t.id}`, argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), ...priority, "--progress", "ndjson"], timeoutMs: takeTimeoutMs(full, clipCount, seconds), }], }; } if (isObj(req.allStyles)) { const recipe = allStylesRecipe(styles, { group: typeof req.allStyles.group === "string" && req.allStyles.group.trim() ? req.allStyles.group.trim() : DEFAULT_GROUP, window: req.allStyles.window === "full" ? "full" : normalizeWindow(req.allStyles.window), quick: req.allStyles.quick === true, }); const group = ["--group", recipe.group]; return { kind: `takes ${project.id} (all styles)`, takes: recipe.takes.map((t) => t.id), steps: [{ ...base, label: `make ${recipe.takes.length} take(s), one per style`, argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...(recipe.quick ? ["--quick"] : []), ...force, ...priority, "--progress", "ndjson"], timeoutMs: recipe.takes.length * takeTimeoutMs(recipe.window === "full", clipCount, seconds), }], }; } if (isObj(req.take)) { const t = req.take; const id = t.id === undefined || t.id === "" ? uniqueTakeId(t.label || t.style || "take", ids) : t.id; const spec = checkSpec({ ...t, id }); if (spec.style && !styles[spec.style]) throw new Error(`unknown style "${spec.style}"`); if (ids.has(spec.id) && req.force !== true) throw new Error(`take ${spec.id} exists — rebuild it, or tick "make it again"`); const argv = [ ...cli, "take", project.id, "--id", spec.id, "--label", spec.label, "--group", spec.group, ...(spec.kind ? ["--kind", spec.kind] : []), ...(spec.summary ? ["--summary", spec.summary] : []), ...(spec.style ? ["--style", spec.style] : []), ...(spec.patch ? ["--patch-json", JSON.stringify(spec.patch)] : []), ...windowArgs(spec.window), ...(spec.quick ? ["--quick"] : []), ...force, ...priority, "--progress", "ndjson", ]; return { kind: `take ${project.id} ${spec.id}`, takes: [spec.id], steps: [{ ...base, label: `make take ${spec.id}`, argv, timeoutMs: takeTimeoutMs(spec.window === "full", clipCount, seconds) }], }; } throw new Error("say what to make: take, allStyles or rebuild"); } /** The group a new take is offered: the newest take's, else the default. */ export function lastGroup(takes) { const newest = [...takes].sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? "")))[0]; return newest?.group ?? DEFAULT_GROUP; }