Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 8d871c9f5da229a40cb20eef0ecc4c1df8408888
parent fac655eba798ac8197b02d73cfd1c75dedfd56b3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 17:31:20 -0500

umtool: take --preview and --changes -- a take at the preview tier (1280x720, veryfast, crf 26; render.preview), and a reel of only what changed against its base, each item labelled with its full-cut time (operator, 5 Nov: "make fast preview render a first class feature because these huge feedback loops are a nightmare")

- build-video: render.tier (outputTier), read only from a preview's render manifest: each chunk of the
  final encode scaled last at the tier's preset and crf (in its argv, so in its key: never a full render's
  chunk), a final not chunk-encoded scaled once at the end, 4 chunk jobs at a tier. No tier: byte for byte
  as before.
- lib/report/takePreview.mjs: previewTake (takes/<t>/out/<slug>.preview.mp4, its build and record in
  out/preview/), changesTake (what changed per entry and kind, the runs with a neighbour each side, one
  build in out/changes/, pieces cut ± pad with a burned-in label, out/<slug>.changes.mp4 and changes.json
  with full-cut times from the base's measured schedule + the changed items' measured lengths), fastRenders.
- takeMaker: composeTake (what a take renders, composed and not written), shared by makeTake and the
  previews; a draft made --from records draftedFrom. takeFrom: linkVariantDir (chunks optional).
- take status: preview and changes beside the take's render; a queued --preview/--changes step is never
  read as the take's own render.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/lib/queue/cli.mjs | 42+++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/takeCli.mjs | 48++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/takeFrom.mjs | 18+++++++++++++++---
Mumtool/lib/report/takeMaker.mjs | 54++++++++++++++++++++++++++++++++++++------------------
Aumtool/lib/report/takePreview.mjs | 814+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takePreview.test.mjs | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
7 files changed, 1214 insertions(+), 34 deletions(-)

diff --git a/umtool/lib/queue/cli.mjs b/umtool/lib/queue/cli.mjs @@ -14,6 +14,7 @@ import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readRenderRecord, recordLines, renderPointerFile } from "../report/renderRecord.mjs"; +import { fastKindOf } from "../report/takePreview.mjs"; import { addStep, cancelStep, @@ -337,11 +338,36 @@ export async function jobsCommand(args, { reportsRoot = REPORTS_ROOT, log = cons * @param {{ take: string | null, json: boolean, showLog: boolean, tail: number | null, reportsRoot?: string, env?: Record<string, string | undefined>, * log: (s: string) => void, err: (s: string) => void }} o */ +export { fastKindOf }; + +/** + * A take's preview and changes renders, for `take status`: each one's record and output (takePreview.mjs + * fastRenders), or the queue step still to run it. + */ +async function fastStatus(project, id, steps) { + const { fastRenders } = await import("../report/takePreview.mjs"); + const slug = await readFile(path.join(project.dir, "video.manifest.json"), "utf8").then((t) => String(JSON.parse(t).slug ?? ""), () => ""); + const got = await fastRenders(path.join(project.dir, "takes", id), slug); + /** @type {Record<string, any>} */ + const out = {}; + for (const kind of ["preview", "changes"]) { + const step = steps.filter((s) => s.target.take === id && fastKindOf(s.argv) === kind).at(-1) ?? null; + const rec = got[/** @type {"preview" | "changes"} */ (kind)]; + const live = rec && (rec.state === "running" || rec.state === "waiting"); + if (step && !live && (step.state === "queued" || step.state === "blocked" || (step.state === "running" && !(rec?.endedAt === null)))) { + out[kind] = { ...(rec ?? {}), state: step.state === "running" ? "running" : step.state, queue: { qid: step.qid, state: step.state, after: step.after, error: step.error } }; + } else if (rec) out[kind] = rec; + } + return out; +} + export async function takeStatus(project, { take, json, showLog, tail, reportsRoot = REPORTS_ROOT, env = process.env, log, err }) { const { statusExitCode } = await import("../report/renderRecord.mjs"); const takesRoot = path.join(project.dir, "takes"); const dir = queueDirOf({ reportsRoot, env }); - const steps = (await listSteps(dir)).map((s) => resolveStep(s)).filter((s) => s.target?.project === project.id && s.target?.take); + const allSteps = (await listSteps(dir)).map((s) => resolveStep(s)).filter((s) => s.target?.project === project.id && s.target?.take); + // A preview or a changes reel is not the take's render: its steps are reported beside it (fastStatus). + const steps = allSteps.filter((s) => !fastKindOf(s.argv)); const ids = take ? [take] : (await readdir(takesRoot).catch(() => [])).filter((n) => !n.startsWith(".")); const rows = []; for (const id of ids) { @@ -376,6 +402,9 @@ export async function takeStatus(project, { take, json, showLog, tail, reportsRo if (doc?.builtAt && !doc.draft) row = { project: project.id, take: id, state: "done", recorded: false, builtAt: doc.builtAt, seconds: doc.seconds ?? null, mp4: doc.preview ?? "preview.mp4", exit: 0 }; else row = { project: project.id, take: id, state: "none", error: doc?.draft ? "a draft: never rendered" : `no render of take ${id} is recorded`, exit: 1 }; } + const fast = await fastStatus(project, id, allSteps); + if (row && Object.keys(fast).length) Object.assign(row, fast); + else if (!row && Object.keys(fast).length) row = { project: project.id, take: id, state: "none", error: "never rendered at full quality", exit: 1, ...fast }; if (row) rows.push(row); } rows.sort((a, b) => String(b.startedAt ?? b.queue?.qid ?? "").localeCompare(String(a.startedAt ?? a.queue?.qid ?? ""))); @@ -389,17 +418,28 @@ export async function takeStatus(project, { take, json, showLog, tail, reportsRo log(JSON.stringify(take ? { ...rows[0], logPath: path.join(takesRoot, take, "render.log") } : { project: project.id, takes: rows }, null, 2)); return code; } + const fastLines = (r) => { + for (const kind of ["preview", "changes"]) { + const f = r[kind]; + if (!f) continue; + const what = f.queue ? `${String(f.state).toUpperCase()} in the queue as ${f.queue.qid}` : String(f.state ?? "?").toUpperCase(); + log(` ${kind}: ${what}${f.mp4 ? ` — ${f.mp4}${f.seconds != null ? ` (${f.seconds} s)` : ""}` : ""}${f.items != null ? `, ${f.items} piece(s) against ${f.from}, list ${f.list}` : ""}${f.error ? ` — ${f.error}` : ""}`); + } + }; for (const r of rows) { if (r.queue) { log(`${project.id} take ${r.take}: ${r.state.toUpperCase()} in the queue as ${r.queue.qid}${r.queue.after ? ` (after ${r.queue.after})` : ""}${r.error ? ` — ${r.error}` : ""}`); log(` poll: umtool queue status ${r.queue.qid}`); + fastLines(r); continue; } if (r.recorded === false || r.state === "none") { log(`${project.id} take ${r.take}: ${r.state.toUpperCase()}${r.recorded === false ? ` (made ${fmtTime(r.builtAt)}, before renders recorded themselves)` : ` — ${r.error}`}`); + fastLines(r); continue; } for (const l of recordLines(r, { logPath: path.join(takesRoot, r.take, r.log ?? "render.log"), tail: take ? (tail ?? 12) : 0 })) log(l); + fastLines(r); } if (showLog && take) { const file = path.join(takesRoot, take, "render.log"); diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -44,6 +44,14 @@ export const TAKE_USAGE = [ " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]", " [--from TAKE] [--keep-frames] [--priority] [--uncensored]", " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames] [--priority]", + " umtool take <project> --id <id> --preview [--from TAKE] [--at S --dur S | --full] [--priority] [--json]", + " the take as stored (a draft too) at the PREVIEW tier (render.preview: 1280x720, veryfast,", + " crf 26; the same layout, segments, chrome and sound): takes/<id>/out/<slug>.preview.mp4,", + " its build and record in out/preview/; the take's full render untouched", + " umtool take <project> --id <id> --changes [--from TAKE] [--pad 3] [--no-preview] [--priority] [--json]", + " a reel of only what changed against TAKE (default: the take's own from): each changed item", + " ± pad s, labelled with its time in the full cut: takes/<id>/out/<slug>.changes.mp4 and", + " takes/<id>/changes.json", " made again from its own take.json (its stored patch, walked edits included); a window", " flag renders it over that window instead of its own", " umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,", @@ -131,7 +139,7 @@ function parse(args) { const valued = new Set([ "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect", "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name", "--tail", - "--import-item", "--after", "--before", "--as", + "--import-item", "--after", "--before", "--as", "--pad", ]); /** @type {Record<string, string[]>} */ const flags = {}; @@ -265,6 +273,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons if (!id) throw new CliError("--id <id>: the take's directory name (lower-case letters, digits, dashes)"); if (p.has("--promote")) return await promote(project, id, p, log, err); if (p.has("--import-item")) return await importItems(project, id, p, { reportsRoot, log, err }); + if (p.has("--preview") || p.has("--changes")) return await fastRender(project, id, p, out, { args, log, deps, renderMode }); const draft = p.has("--draft") || p.has("--no-render"); const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null); // A DRAFT named with no patch of its own is rendered from what it stores -- @@ -320,7 +329,7 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons if (spec.label && !/uncensored/i.test(spec.label)) spec.label = `${spec.label} (uncensored)`; } if (draft) { - const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) }); + const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(p.has("--from") ? { draftedFrom: p.one("--from") } : {}), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) }); if (p.has("--json")) { log(JSON.stringify({ ok: true, draft: true, ...d }, null, 2)); return 0; @@ -360,6 +369,41 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons } /** + * `umtool take <p> --id <t> --preview [--from <t0>] [--at S --dur S | --full]` · `--changes [--from <t0>] [--pad S] + * [--no-preview]`: the take's fast-feedback renders (takePreview.mjs), never its deliverable. + */ +async function fastRender(project, id, p, out, { args, log, deps, renderMode }) { + if (p.has("--preview") && p.has("--changes")) { + // `--changes --preview` is the default reel (preview quality), said both ways. + if (p.has("--no-preview")) throw new CliError("--changes --preview and --no-preview: one or the other"); + } + for (const n of ["--draft", "--no-render", "--rebuild", "--promote", "--patch", "--patch-json", "--set", "--style", "--effect", "--uncensored", "--keep-frames"]) { + if (p.has(n)) throw new CliError(`${n} is not for a ${p.has("--changes") ? "changes reel" : "preview"}: it renders the take as it is stored (make or edit the take first)`); + } + const tp = await import("./takePreview.mjs"); + const common = { + from: p.one("--from") ?? null, + log: out.log, + emit: out.emit, + projectId: project.id, + argv: ["take", ...args], + ...(deps?.render ? { render: /** @type {any} */ (deps.render) } : {}), + }; + const run = async () => { + if (p.has("--changes")) { + const pad = p.has("--pad") ? Number(p.one("--pad")) : undefined; + if (pad !== undefined && !(Number.isFinite(pad) && pad >= 0 && pad <= 30)) throw new CliError("--pad is 0–30 seconds"); + if (p.has("--at") || p.has("--dur") || p.has("--full")) throw new CliError("a changes reel is of the whole cut: no --at/--dur/--full"); + return tp.changesTake(project.dir, id, { ...common, ...(pad !== undefined ? { pad } : {}), preview: !p.has("--no-preview") }); + } + return tp.previewTake(project.dir, id, { ...common, window: windowOf(p) ?? undefined }); + }; + const r = await withTakePriority({ priority: p.has("--priority"), project: project.id, take: id, log: out.log, ...(renderMode ?? {}) }, run); + if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); + return 0; +} + +/** * `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <id> | --before <id>] * [--as <id>] [--dry-run] [--json]`: items of other projects cloned into the take, their files linked in (takeImport.mjs). */ diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -159,8 +159,20 @@ export async function linkFromTake(projectDir, id, from, takeOut) { return out; } +/** + * One built variant directory's files linked into another (linkVariant), for a preview or a changes reel + * (takePreview.mjs): `src` a take's out/sourced or out/preview/sourced, `dst` the preview's own. `chunks: + * false` leaves the final encode's chunks and their record out -- a full render's are never a preview's. + * @param {{ src: string, dst: string, kept?: string | null, from: string, chunks?: boolean }} o + */ +export async function linkVariantDir({ src, dst, kept = null, from, chunks = true }) { + if (!(await isDir(src))) return null; + if (path.resolve(src) === path.resolve(dst)) return null; + return linkVariant({ src, dst, kept: kept ?? keptFramesDir(path.dirname(src), path.basename(src)), from, chunks }); +} + /** One variant's files, `src` (the other take's out/<variant>) into `dst`; `kept` its set-aside layers. */ -async function linkVariant({ src, dst, kept, from }) { +async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) { const out = { segments: 0, frames: [], batches: 0, chunks: 0, records: 0, keptOwn: [], keptOwnFrames: [] }; const segs = path.join(src, "segments"); @@ -242,13 +254,13 @@ async function linkVariant({ src, dst, kept, from }) { // The final encode's chunks and sound, by content key: theirs beside ours. const chunks = path.join(src, CHUNKS_DIR); const chunksOut = path.join(dst, CHUNKS_DIR); - for (const f of await names(chunks)) { + for (const f of withChunks ? await names(chunks) : []) { if (!/^(chunk|audio)-[0-9a-f]+\.(mp4|m4a)$/.test(f) || !(await isFile(path.join(chunks, f)))) continue; await mkdir(chunksOut, { recursive: true }); if (!(await isFile(path.join(chunksOut, f))) && (await linkFile(path.join(chunks, f), path.join(chunksOut, f)))) out.chunks += 1; } // Their record of the chunks, unless ours is newer: what "why re-encoded" compares with. - const theirRecord = await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null); + const theirRecord = withChunks ? await lstat(path.join(chunks, CHUNKS_RECORD)).catch(() => null) : null; if (theirRecord?.isFile()) { const ownRecord = await lstat(path.join(chunksOut, CHUNKS_RECORD)).catch(() => null); if (!ownRecord?.isFile() || ownRecord.mtimeMs < theirRecord.mtimeMs) { diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -595,24 +595,17 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { return r; } -/** 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 ?? (() => {}); +/** + * 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<typeof checkSpec>} spec + * @param {{ styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, log?: (line: string) => void }} [opts] + */ +export async function composeTake(projectDir, spec, opts = {}) { 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 = await readFile(path.join(projectDir, MANIFEST), "utf8"); const base = JSON.parse(baseText); const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); @@ -668,6 +661,29 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { 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 }; +} + +/** 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 } = await composeTake(projectDir, spec, { styles: opts.styles, log }); + let renderDoc = composed; if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (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 @@ -828,7 +844,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { * * @param {string} projectDir * @param {TakeSpec} rawSpec `window` absent: the render's window is said when it is rendered - * @param {{ force?: boolean, styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, now?: () => Date }} [opts] + * @param {{ force?: boolean, styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, now?: () => Date, draftedFrom?: string }} [opts] */ export async function draftTake(projectDir, rawSpec, opts = {}) { const spec = checkSpec(rawSpec); @@ -875,6 +891,8 @@ export async function draftTake(projectDir, rawSpec, opts = {}) { patch: spec.patch, window, ...(spec.quick ? { quick: true } : {}), + // A draft made FROM another take (`--draft --from <t>`): 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), diff --git a/umtool/lib/report/takePreview.mjs b/umtool/lib/report/takePreview.mjs @@ -0,0 +1,814 @@ +// FAST FEEDBACK (operator, 5 Nov 2026: "make fast preview render a first class feature because these huge +// feedback loops are a nightmare"): two renders of a take that are not its deliverable. +// +// umtool take <p> --id <t> --preview [--from <t0>] +// the WHOLE take at the preview tier -- the same cut, composed exactly as its full render composes it +// (the 1920×1080 layout, its segments, its chrome frames, its sound: the same mix and loudness, so a +// timing or an audio judgement made on it holds), only its final picture encoded smaller and faster +// (render.preview: 1280×720, x264 veryfast, crf 26; build-video outputTier). Into +// takes/<t>/out/<slug>.preview.mp4 +// takes/<t>/out/preview/ the build's own out/: its schedule, segments, chunks, and +// its record (render.json, render.log) +// The take's full render -- preview.mp4, out/<slug>.mp4, out/sourced/, take.json, render.json -- is +// never touched. A draft is previewed from its stored patch, as its render would be. +// +// umtool take <p> --id <t> --changes [--from <t0>] [--pad 3] [--no-preview] +// a REEL of only what changed against <t0> (default: the take's own `from`): each changed item -- added, +// re-read, re-picked, re-voiced, fx, a trim, a hold, a panel, … -- with one neighbour each side +// rendered in one build (takes/<t>/out/changes/), then cut to the item ± pad seconds, each piece with +// a label burned in ("21:19 · p-2116831815466193102 · re-voiced") giving its time in the FULL cut, +// joined into takes/<t>/out/<slug>.changes.mp4. takes/<t>/changes.json lists the same: the input the +// render-verify view reads. A removed item is shown as the join it leaves. +// +// WHAT A PREVIEW SHARES, AND WHAT IT NEVER FEEDS. Its final encode's chunks key apart from the full render's +// (the tier's scale, preset and crf are in each chunk's argv, so in its key: chunked-encode.mjs), and live +// in out/preview/, so a preview chunk never stands in for a full one -- and a full render's chunks are not +// linked into a preview. What is NOT tier-dependent is shared both ways: a clip or post segment, a chrome +// frame and the cut's sound are the same bytes whichever tier they end up in, keyed by what makes them +// (segment-cache.mjs, post-render.mjs, frame-keys.mjs), so a preview reuses a full render's and the render +// pool's. That is the speed: a preview of a take whose base was rendered re-encodes nothing but its +// chunks, at a fifth of the pixels and a fast preset. `render.preview.segments: "preview"` encodes the +// segments a preview has to BUILD at the tier's preset and crf too (keyed apart, never a full render's); +// off by default, because it forfeits reusing the full render's. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { applyMontageRulings, readMontageRulings } from "umtool-report-to-video/montage-rulings"; +import { composeTake, checkSpec, estimatedSeconds, linkSharedOut, MANIFEST, sourcedEntries, windowManifest } from "./takeMaker.mjs"; +import { takesDirOf, TAKE_FILE } from "./takes.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; + +/** The preview tier's defaults (render.preview overrides each). */ +export const PREVIEW_DEFAULTS = Object.freeze({ width: 1280, height: 720, preset: "veryfast", crf: 26, segments: "shared" }); +/** The build dirs under takes/<t>/out/. */ +export const PREVIEW_DIR = "preview"; +export const CHANGES_DIR = "changes"; +/** The changes reel's list, beside take.json. */ +export const CHANGES_FILE = "changes.json"; +/** Seconds of context either side of a changed item in the reel. */ +export const DEFAULT_PAD = 3; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const X264_PRESETS = ["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"]; + +/** + * The preview tier a manifest asks for: `render.preview` over PREVIEW_DEFAULTS, checked. The cut's own fps + * is kept (a frame-keyed chrome frame is shared with the full render only at the cut's own rate), and the + * tier is never larger than the cut: a 640×360 cut previews at 640×360. Pure. + * + * @param {Record<string, any>} [render] + * @returns {{ width: number, height: number, preset: string, crf: number, segments: "shared" | "preview" }} + */ +export function previewKnobs(render = {}) { + const raw = render?.preview; + if (raw !== undefined && raw !== null && !isObj(raw)) throw new Error("render.preview is an object: { width, height, preset, crf, segments }"); + const k = { ...PREVIEW_DEFAULTS, ...(isObj(raw) ? raw : {}) }; + const W = Number(render?.width ?? 1920); + const H = Number(render?.height ?? 1080); + let width = Math.round(Number(k.width)); + let height = Math.round(Number(k.height)); + if (!Number.isFinite(width) || width < 16 || !Number.isFinite(height) || height < 16) throw new Error(`render.preview: width and height are pixels (≥ 16), got ${JSON.stringify(raw)}`); + if (width > W || height > H) { + // Never larger than the cut: its own size, its aspect kept. + const f = Math.min(W / width, H / height); + width = Math.round(width * f); + height = Math.round(height * f); + } + width -= width % 2; + height -= height % 2; + const crf = Number(k.crf); + if (!Number.isFinite(crf) || crf < 0 || crf > 51) throw new Error(`render.preview.crf is 0–51, got ${JSON.stringify(k.crf)}`); + const preset = String(k.preset); + if (!X264_PRESETS.includes(preset)) throw new Error(`render.preview.preset is an x264 preset (${X264_PRESETS.join(", ")}), got ${JSON.stringify(k.preset)}`); + if (k.segments !== "shared" && k.segments !== "preview") throw new Error(`render.preview.segments is "shared" or "preview", got ${JSON.stringify(k.segments)}`); + return { width, height, preset, crf, segments: k.segments }; +} + +/** + * A render manifest at the preview tier: `render.tier` (build-video outputTier), and with `segments: + * "preview"` the cut's own preset and crf too (the segments it builds). The manifest is copied. Pure. + * `segments`: the caller's default for that knob when the manifest does not set it. + * @param {Record<string, any>} doc + * @param {{ segments?: "shared" | "preview" | null }} [o] + */ +export function atPreviewTier(doc, { segments = null } = {}) { + const k = previewKnobs(doc.render ?? {}); + // A caller's default (a changes reel's: "preview") gives way to a manifest that says. + if (segments && !(isObj(doc.render?.preview) && doc.render.preview.segments !== undefined)) k.segments = segments; + const render = { ...(doc.render ?? {}), tier: { name: "preview", width: k.width, height: k.height, preset: k.preset, crf: k.crf } }; + if (k.segments === "preview") Object.assign(render, { preset: k.preset, crf: k.crf }); + return { ...doc, render }; +} + +/** Where a take's preview and changes renders go. Pure. */ +export function previewPaths(takeDir, slug) { + const out = path.join(takeDir, "out"); + return { + previewOut: path.join(out, PREVIEW_DIR), + previewMp4: path.join(out, `${slug}.preview.mp4`), + changesOut: path.join(out, CHANGES_DIR), + changesMp4: path.join(out, `${slug}.changes.mp4`), + changesFile: path.join(takeDir, CHANGES_FILE), + }; +} + +// --------------------------------------------------------------------------- +// What changed: one take's timeline against another's. +// --------------------------------------------------------------------------- + +const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); + +/** The narration's change, in a word: re-picked (an older take), re-voiced / re-read (a new one), read knobs. */ +function narrationKind(a, b) { + const A = isObj(a) ? a : {}; + const B = isObj(b) ? b : {}; + const takesA = Array.isArray(A.takes) ? A.takes : []; + const takesB = Array.isArray(B.takes) ? B.takes : []; + const pickedB = Number.isInteger(B.pick) ? takesB[B.pick] : null; + if (A.pick !== B.pick || !same(takesA[A.pick], pickedB)) { + if (!pickedB) return "re-read"; + const before = takesA.some((t) => same(t?.file, pickedB.file)); + if (before) return "re-picked"; + const ops = new Set((Array.isArray(pickedB.steps) ? pickedB.steps : []).map((s) => s?.op).filter(Boolean)); + if (ops.has("revoice")) return "re-voiced"; + if (ops.has("pause")) return "paused"; + if (ops.has("rejoin") || ops.has("join")) return "re-joined"; + if (ops.has("tempo")) return "tempo"; + return "re-read"; + } + if (!same(A.script, B.script)) return "re-read"; + return "read knobs"; +} + +/** Keys of an entry, by the kind of change a person checks for. */ +const KEY_KINDS = [ + [["fx"], "fx"], + [["cutStart", "cutEnd", "start", "end", "from", "to", "media", "clip", "full", "gaps", "room"], "media trim"], + [["hold", "lead"], "hold"], + [["panel", "layout"], "panel"], + [["pictureOnly"], "picture only"], + [["thread", "parents", "conversation", "quoted", "replyingTo"], "thread"], + [["redact", "slurs"], "slurs"], + [["text", "heading", "title", "subtitle", "onscreen", "quote", "cite", "citeUrl", "channelTitle", "date"], "text"], + [["audio", "mute", "muteFrom", "loudness"], "sound"], + [["blur"], "blur"], +]; + +/** + * The kinds of one entry's change (a → b): a sorted list of words, `narration` read closely. Pure. + * @param {Record<string, any>} a + * @param {Record<string, any>} b + * @returns {{ kinds: string[], keys: string[] }} + */ +export function entryChangeKinds(a, b) { + const keys = [...new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])].filter((k) => !same(a?.[k], b?.[k])).sort(); + const kinds = new Set(); + for (const k of keys) { + if (k === "narration") { + kinds.add(narrationKind(a?.narration, b?.narration)); + continue; + } + const hit = KEY_KINDS.find(([ks]) => ks.includes(k)); + kinds.add(hit ? hit[1] : "edited"); + } + return { kinds: [...kinds].sort(), keys }; +} + +/** + * Lines for what changed outside the timeline: `render.<path>` leaves and top-level keys. Pure. + * @returns {string[]} + */ +export function renderLevelChanges(a, b) { + const out = []; + const walk = (x, y, prefix) => { + if (isObj(x) && isObj(y)) { + for (const k of [...new Set([...Object.keys(x), ...Object.keys(y)])].sort()) walk(x[k], y[k], prefix ? `${prefix}.${k}` : k); + return; + } + if (!same(x, y)) out.push(prefix); + }; + for (const k of [...new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])].sort()) { + if (k === "timeline" || k === "generatedOn") continue; + if (k === "render") { + // The preview's own knobs change no frame of the full cut. + const ra = { ...(a?.render ?? {}) }; + const rb = { ...(b?.render ?? {}) }; + delete ra.preview; + delete rb.preview; + walk(ra, rb, "render"); + } else if (!same(a?.[k], b?.[k])) out.push(k); + } + return out; +} + +/** + * The changes of one timeline against another's, by entry id, in the NEW timeline's order. Pure. + * + * changed { id, index, kind: "changed" | "added" | "moved", kinds, keys } one per entry of `after` + * that is new, edited or moved (its predecessor among the shared ids is another) + * removed { id, after, before } an entry of `before` gone: the ids now either side of where it was + * + * @param {Array<Record<string, any>>} beforeTimeline + * @param {Array<Record<string, any>>} afterTimeline + */ +export function diffTimelines(beforeTimeline, afterTimeline) { + const A = sourcedEntries(beforeTimeline); + const B = sourcedEntries(afterTimeline); + const byA = new Map(A.map((e) => [e.id, e])); + const byB = new Map(B.map((e) => [e.id, e])); + const sharedA = A.filter((e) => byB.has(e.id)).map((e) => e.id); + const sharedB = B.filter((e) => byA.has(e.id)).map((e) => e.id); + const prevA = new Map(sharedA.map((id, i) => [id, i ? sharedA[i - 1] : null])); + const prevB = new Map(sharedB.map((id, i) => [id, i ? sharedB[i - 1] : null])); + const changed = []; + B.forEach((e, index) => { + const old = byA.get(e.id); + if (!old) { + changed.push({ id: e.id, index, kind: "added", kinds: [`added ${e.type ?? "entry"}`], keys: [] }); + return; + } + const { kinds, keys } = entryChangeKinds(old, e); + const moved = prevA.get(e.id) !== prevB.get(e.id) && !(prevA.get(e.id) && !byB.has(prevA.get(e.id))); + if (moved) kinds.unshift("moved"); + if (kinds.length) changed.push({ id: e.id, index, kind: keys.length ? "changed" : "moved", kinds, keys }); + }); + const removed = []; + A.forEach((e, i) => { + if (byB.has(e.id)) return; + // The nearest survivors either side, as they stand in the new timeline. + let after = null; + for (let k = i - 1; k >= 0 && after === null; k -= 1) if (byB.has(A[k].id)) after = A[k].id; + let before = null; + for (let k = i + 1; k < A.length && before === null; k += 1) if (byB.has(A[k].id)) before = A[k].id; + removed.push({ id: e.id, after, before, type: e.type ?? null }); + }); + return { changed, removed }; +} + +/** + * The runs a changes reel renders: each change with one neighbour either side (a removal: the two entries + * now either side of it), overlapping or touching ranges merged. Each run lists its ids (in the new + * timeline's order) and its FOCI -- one per change, each a labelled piece of the reel. Pure. + * + * @param {string[]} ids the new timeline's ids, in order + * @param {ReturnType<typeof diffTimelines>} diff + * @param {{ neighbours?: number }} [o] + */ +export function planRuns(ids, diff, { neighbours = 1 } = {}) { + const at = new Map(ids.map((id, i) => [id, i])); + /** @type {Array<{ lo: number, hi: number, focus: Array<Record<string, any>> }>} */ + const ranges = []; + for (const c of diff.changed) { + const i = at.get(c.id); + if (i === undefined) continue; + ranges.push({ lo: Math.max(0, i - neighbours), hi: Math.min(ids.length - 1, i + neighbours), focus: [{ type: "item", id: c.id, index: i, kind: c.kind, kinds: c.kinds }] }); + } + for (const r of diff.removed) { + const a = r.after !== null ? at.get(r.after) : undefined; + const b = r.before !== null ? at.get(r.before) : undefined; + if (a === undefined && b === undefined) continue; + const lo = a ?? b; + const hi = b ?? a; + ranges.push({ lo: /** @type {number} */ (lo), hi: /** @type {number} */ (hi), focus: [{ type: "join", id: r.id, after: r.after, before: r.before, index: lo, kind: "removed", kinds: [`removed ${r.type ?? "entry"}`] }] }); + } + ranges.sort((x, y) => x.lo - y.lo || x.hi - y.hi); + const merged = []; + for (const r of ranges) { + const last = merged[merged.length - 1]; + if (last && r.lo <= last.hi + 1) { + last.hi = Math.max(last.hi, r.hi); + last.focus.push(...r.focus); + } else merged.push({ ...r, focus: [...r.focus] }); + } + return merged.map((r) => ({ + ids: ids.slice(r.lo, r.hi + 1), + focus: r.focus.sort((x, y) => x.index - y.index || (x.type === "join" ? 1 : -1)), + })); +} + +// --------------------------------------------------------------------------- +// Times: in the reel's build, and in the FULL cut. +// --------------------------------------------------------------------------- + +/** + * Each entry's place in the FULL cut of the new timeline, and how it was worked out. Pure. + * + * With the base take's MEASURED schedule (its render's out/sourced/schedule.json, `estimated: false`): an + * entry that did not change keeps its measured length, moved by what changed before it -- each changed or + * added entry's length as the reel's build measured it, less each changed or removed entry's old length. + * That is exact when every changed entry was measured (basis "measured": the base's schedule + the reel's + * measured lengths), to within what a change moves in its neighbours (a clock's rewind, a hold). Without + * the base's schedule every length is the estimate (estimatedSeconds), the changed ones measured (basis + * "estimate"). + * + * @param {{ timeline: Array<Record<string, any>>, changedIds: Set<string>, base: { segments: Array<{ id: string, start: number, duration: number }>, transition?: number, estimated?: boolean } | null, + * measured: Map<string, number>, estimate?: (e: Record<string, any>) => number }} o + * @returns {{ basis: "measured" | "estimate", times: Map<string, { start: number, end: number, exact: boolean }> }} + */ +export function fullCutTimes({ timeline, changedIds, base, measured, estimate = estimatedSeconds }) { + const entries = sourcedEntries(timeline); + const times = new Map(); + const exactBase = !!base && base.estimated !== true && Array.isArray(base.segments) && base.segments.length > 0; + if (!exactBase) { + let t = 0; + let exact = true; + for (const e of entries) { + const m = measured.get(e.id); + const d = m ?? estimate(e); + if (m === undefined) exact = false; + times.set(e.id, { start: t, end: t + d, exact }); + t += d; + } + return { basis: "estimate", times }; + } + const D = Number(base?.transition ?? 0) || 0; + const old = new Map(base.segments.map((s) => [s.id, { start: Number(s.start), duration: Number(s.duration ?? (Number(s.end) - Number(s.start))) }])); + const newIds = new Set(entries.map((e) => e.id)); + // The old segments a change took out of the clock: a changed entry's old length, a removed one's. + const outOld = base.segments.filter((s) => (changedIds.has(s.id) && old.has(s.id)) || !newIds.has(s.id)).map((s) => old.get(s.id)); + let prevEnd = 0; + let addedSoFar = 0; + let exactSoFar = true; + for (const e of entries) { + const o = old.get(e.id); + if (!changedIds.has(e.id) && o) { + const lost = outOld.filter((x) => x && x.start < o.start).reduce((n, x) => n + x.duration - D, 0); + const start = o.start + addedSoFar - lost; + times.set(e.id, { start, end: start + o.duration, exact: exactSoFar }); + prevEnd = start + o.duration; + continue; + } + const m = measured.get(e.id); + const d = m ?? estimate(e); + if (m === undefined) exactSoFar = false; + const start = Math.max(0, prevEnd - (times.size ? D : 0)); + times.set(e.id, { start, end: start + d, exact: exactSoFar }); + addedSoFar += d - (times.size > 1 ? D : 0); + prevEnd = start + d; + } + return { basis: exactSoFar ? "measured" : "estimate", times }; +} + +/** Seconds as m:ss (h:mm:ss past an hour). Pure. */ +export function clockOf(s) { + const t = Math.max(0, Math.floor(Number(s) || 0)); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const sec = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`; +} + +/** A reel piece's label: "21:19 · p-… · re-voiced". Pure. */ +export function pieceLabel(focus, fullStart) { + const what = focus.type === "join" ? `${focus.id} removed — the join` : focus.id; + return `${clockOf(fullStart)} · ${what} · ${focus.kinds.join(", ")}`; +} + +/** + * The pieces of the reel: per focus, its span in the reel BUILD (the item ± pad, clamped to its run's + * entries; a removal's: the join ± pad) and in the full cut. Pure. + * + * @param {ReturnType<typeof planRuns>} runs + * @param {Map<string, { start: number, duration: number }>} build each id's place in the reel's build + * @param {Map<string, { start: number, end: number, exact: boolean }>} full + * @param {number} pad + */ +export function reelPieces(runs, build, full, pad) { + const pieces = []; + for (const run of runs) { + const first = build.get(run.ids[0]); + const last = build.get(run.ids[run.ids.length - 1]); + if (!first || !last) throw new Error(`the changes build has no place for ${run.ids.join(", ")}`); + const lo = first.start; + const hi = last.start + last.duration; + for (const f of run.focus) { + let a; + let b; + let fa; + let fb; + let exact; + if (f.type === "join") { + const anchor = f.after !== null ? build.get(f.after) : null; + const at = anchor ? anchor.start + anchor.duration : /** @type {any} */ (build.get(f.before)).start; + a = at - pad; + b = at + pad; + const fe = f.after !== null ? full.get(f.after) : null; + fa = fe ? fe.end : full.get(f.before)?.start ?? 0; + fb = fa; + exact = fe ? fe.exact : full.get(f.before)?.exact ?? false; + } else { + const s = /** @type {{ start: number, duration: number }} */ (build.get(f.id)); + a = s.start - pad; + b = s.start + s.duration + pad; + const fe = full.get(f.id); + fa = fe?.start ?? 0; + fb = fe?.end ?? fa + s.duration; + exact = fe?.exact ?? false; + } + const from = Math.max(lo, a); + const to = Math.min(hi, b); + pieces.push({ ...f, from: round3(from), to: round3(to), fullStart: round3(fa), fullEnd: round3(fb), exact, label: pieceLabel(f, fa) }); + } + } + return pieces; +} + +const round3 = (v) => Math.round(v * 1000) / 1000; + +// --------------------------------------------------------------------------- +// The renders. +// --------------------------------------------------------------------------- + +async function readJson(file) { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch { + return null; + } +} + +const isDir = (p) => stat(/* turbopackIgnore: true */ p).then((s) => s.isDirectory(), () => false); + +/** A take's stored spec (take.json), checked: what its preview renders, as its render would. */ +async function storedSpec(projectDir, id) { + const take = await readJson(path.join(takesDirOf(projectDir), id, TAKE_FILE)); + if (!take) throw new Error(`no take ${id} in ${path.basename(projectDir)} (make it first: umtool take <p> --id ${id} --draft …)`); + return { + take, + spec: checkSpec({ + id, + label: take.label || id, + group: take.group, + kind: take.kind === "similar" ? "similar" : undefined, + summary: take.summary, + style: take.style ?? null, + patch: take.patch ?? null, + window: take.window ?? "full", + }), + }; +} + +/** The manifest a base take rendered (its video.manifest.json), else its composition now (a draft). */ +async function baseManifest(projectDir, from) { + const dir = path.join(takesDirOf(projectDir), from); + const rendered = await readJson(path.join(dir, MANIFEST)); + if (rendered) return { manifest: rendered, rendered: true }; + const { spec } = await storedSpec(projectDir, from); + const c = await composeTake(projectDir, { ...spec, window: "full" }); + return { manifest: c.manifest, rendered: false }; +} + +/** + * The built dirs a preview links from (takeFrom.mjs linkVariantDir), in order: this take's own full + * render's (no chunks: a full render's are never a preview's), the base take's full render's (the same), + * then the base take's preview or changes builds (with their chunks: the same tier's). + */ +async function linkSources(projectDir, id, from, dst, { tierDir }) { + const { linkVariantDir } = await import("./takeFrom.mjs"); + const takes = takesDirOf(projectDir); + const sources = [{ src: path.join(takes, id, "out", "sourced"), from: id, chunks: false }]; + if (from) { + sources.push({ src: path.join(takes, from, "out", "sourced"), from, chunks: false }); + for (const d of [PREVIEW_DIR, CHANGES_DIR]) sources.push({ src: path.join(takes, from, "out", d, "sourced"), from, chunks: true }); + } + if (tierDir) for (const d of [PREVIEW_DIR, CHANGES_DIR]) if (d !== tierDir) sources.push({ src: path.join(takes, id, "out", d, "sourced"), from: id, chunks: true }); + const got = []; + for (const s of sources) { + const r = await linkVariantDir({ src: s.src, dst, from: s.from, chunks: s.chunks }).catch((e) => { + throw new Error(`linking ${path.relative(takes, s.src)}: ${e instanceof Error ? e.message : e}`); + }); + if (r) got.push(`${path.relative(takes, s.src)}: ${r.segments} segment file(s)${r.frames.length ? `, ${r.frames.join(", ")}` : ""}${r.chunks ? `, ${r.chunks} chunk(s)` : ""}`); + } + return got; +} + +/** + * One build of a render manifest into `outDir` (the take's preview or changes dir): through renderTake, + * the heavy slot and all, recorded in outDir/render.json and render.log. Resolves to the build's mp4. + */ +async function buildInto(projectDir, { id, label, kind, renderDoc, outDir, from, opts }) { + const recordMod = await import("./renderRecord.mjs"); + await mkdir(outDir, { recursive: true }); + const rec = await recordMod + .openRenderRecord(outDir, { take: id, projectDir, project: opts.projectId ?? null, label: `${label} (${kind})`, argv: opts.argv, reportsRoot: null }) + .catch(() => null); + const log = (line) => { + rec?.line(line); + (opts.log ?? (() => {}))(line); + }; + const emit = (ev) => { + rec?.event(ev); + (opts.emit ?? (() => {}))(ev); + }; + const renderPath = path.join(projectDir, `.take-${id}.${kind}.render.json`); + try { + const linked = await linkSharedOut(projectDir, outDir); + if (linked.length) log(`${id}: ${kind}: reusing the project's ${linked.join(" and ")}`); + const got = await linkSources(projectDir, id, from, path.join(outDir, "sourced"), { tierDir: path.basename(outDir) }); + for (const g of got) log(`${id}: ${kind}: linked ${g}`); + await writeFile(renderPath, JSON.stringify(renderDoc, null, 2) + "\n", "utf8"); + const render = opts.render ?? (await import("./takeRender.mjs")).renderTake; + const t0 = Date.now(); + const { file } = await render({ manifestPath: renderPath, outDir, slug: String(renderDoc.slug ?? ""), full: false, xfade: Number(renderDoc.render?.transition ?? 0) > 0 && opts.xfade === true, keepFrames: false, emit, log, ...(opts.signal ? { signal: opts.signal } : {}) }); + const made = await stat(file).catch(() => null); + if (!made?.isFile() || made.size === 0) throw new Error(`${id}: the ${kind} render wrote no mp4 (${file})`); + return { file, rec, log, renderSeconds: Math.round((Date.now() - t0) / 100) / 10 }; + } catch (e) { + await rec?.fail(e); + throw e; + } finally { + await rm(renderPath, { force: true }); + } +} + +async function probeSeconds(file) { + const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]).catch(() => ({ stdout: "" })); + const n = Number(String(stdout).trim()); + return Number.isFinite(n) ? n : null; +} + +/** A video's frame size, `[w, h]`, or null. */ +export async function probeSize(file) { + const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]).catch(() => ({ stdout: "" })); + const [w, h] = String(stdout).trim().split(",").map(Number); + return Number.isFinite(w) && Number.isFinite(h) ? [w, h] : null; +} + +/** + * `umtool take <p> --id <t> --preview [--from <t0>]`: the whole take (or its window) at the preview tier. + * + * @param {string} projectDir + * @param {string} id + * @param {{ from?: string | null, window?: "full" | { at: number, dur: number } | null, log?: (l: string) => void, emit?: (ev: any) => void, + * render?: Function, projectId?: string, argv?: string[], signal?: AbortSignal }} [opts] + */ +export async function previewTake(projectDir, id, opts = {}) { + const { take, spec } = await storedSpec(projectDir, id); + const from = opts.from ?? null; + if (from) await checkFrom(projectDir, id, from); + const log = opts.log ?? (() => {}); + const c = await composeTake(projectDir, { ...spec, window: opts.window ?? spec.window ?? "full" }, { log }); + const renderDoc = atPreviewTier(c.renderDoc); + const takeDir = path.join(takesDirOf(projectDir), id); + const slug = String(c.manifest.slug ?? ""); + const p = previewPaths(takeDir, slug); + const t = renderDoc.render.tier; + log(`${id}: a preview — ${t.width}x${t.height}, ${t.preset}, crf ${t.crf}${previewKnobs(c.renderDoc.render).segments === "preview" ? ", its segments at the tier too" : ""}; the full render's files untouched${from ? `; reusing ${from}'s` : ""}${take.draft ? " (a draft: its stored patch)" : ""}`); + const b = await buildInto(projectDir, { id, label: spec.label, kind: PREVIEW_DIR, renderDoc, outDir: p.previewOut, from, opts }); + try { + await rename(b.file, p.previewMp4); + } catch (e) { + await b.rec?.fail(e); + throw e; + } + const seconds = await probeSeconds(p.previewMp4); + const doc = await b.rec?.done({ mp4: p.previewMp4, seconds }); + if (doc && doc.state !== "done") throw new Error(doc.error ?? `${id}: the preview left no mp4`); + b.log(`${id}: preview ${path.relative(takeDir, p.previewMp4)} — ${seconds ?? "?"} s, rendered in ${b.renderSeconds} s`); + return { id, mp4: p.previewMp4, seconds, renderSeconds: b.renderSeconds, tier: t }; +} + +async function checkFrom(projectDir, id, from) { + if (from === id) throw new Error(`--from ${from}: that is this take — name another take`); + const dir = path.join(takesDirOf(projectDir), from); + if (!(await isDir(dir))) throw new Error(`--from ${from}: no such take in ${path.basename(projectDir)}`); +} + +/** + * Where each entry sits in a build: its own schedule (out/<v>/sourced/schedule.json, when written by this + * build and naming every id), else the probed lengths of its segments end to end. + */ +async function buildPlaces(variantDir, ids, since) { + const sched = await readJson(path.join(variantDir, "schedule.json")); + const st = await stat(path.join(variantDir, "schedule.json")).catch(() => null); + const places = new Map(); + if (sched && st && st.mtimeMs >= since - 1000 && Array.isArray(sched.segments)) { + for (const s of sched.segments) places.set(s.id, { start: Number(s.start), duration: Number(s.duration ?? Number(s.end) - Number(s.start)) }); + if (ids.every((id) => places.has(id))) return { places, basis: "schedule" }; + } + places.clear(); + let t = 0; + for (const id of ids) { + const d = await probeSeconds(path.join(variantDir, "segments", `${id}.mp4`)); + if (d === null) throw new Error(`the changes build left no segment for ${id} (and no schedule naming it)`); + places.set(id, { start: t, duration: d }); + t += d; + } + return { places, basis: "segments" }; +} + +/** + * The base take's MEASURED schedule: its render's schedule.json (a deck cut's), else -- a cut without the + * deck writes none -- its segments' probed lengths end to end, when every entry of its timeline has one + * (a take's hard cuts). Null when neither: the full-cut times are then estimates. + */ +async function baseScheduleOf(variantDir, manifest) { + const sched = await readJson(path.join(variantDir, "schedule.json")); + if (sched && sched.estimated !== true && Array.isArray(sched.segments) && sched.segments.length) return sched; + const ids = sourcedEntries(manifest?.timeline).map((e) => e.id); + if (!ids.length) return null; + const segments = []; + let t = 0; + for (const id of ids) { + const d = await probeSeconds(path.join(variantDir, "segments", `${id}.mp4`)); + if (d === null) return null; + segments.push({ id, start: t, duration: d }); + t += d; + } + return { estimated: false, transition: 0, segments, from: "segments" }; +} + +/** The font a reel's labels are drawn in: the cut's bold, its regular, else a common one on this machine. */ +async function labelFont(render) { + const candidates = [render?.fontBold, render?.fontRegular, "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/liberation/LiberationSans-Bold.ttf"]; + for (const f of candidates) if (typeof f === "string" && f && (await stat(f).then((s) => s.isFile(), () => false))) return f; + return null; +} + +/** The ffmpeg drawtext filter of a reel piece's label (the text from a file: nothing to escape). Pure. */ +export function labelFilter({ textFile, font, height }) { + const size = Math.max(12, Math.round(height * 0.034)); + const esc = (p) => p.replace(/\\/g, "\\\\").replace(/:/g, "\\:").replace(/'/g, "\\'"); + return [ + `drawtext=textfile='${esc(textFile)}'`, + ...(font ? [`fontfile='${esc(font)}'`] : []), + `fontsize=${size}`, "fontcolor=white", "box=1", "boxcolor=black@0.66", `boxborderw=${Math.round(size * 0.45)}`, + `x=${Math.round(size * 0.9)}`, `y=${Math.round(size * 0.9)}`, + ].join(":"); +} + +/** + * `umtool take <p> --id <t> --changes [--from <t0>] [--pad 3] [--no-preview]`: the reel of what changed. + * + * @param {string} projectDir + * @param {string} id + * @param {{ from?: string | null, pad?: number, preview?: boolean, log?: (l: string) => void, emit?: (ev: any) => void, + * render?: Function, projectId?: string, argv?: string[], signal?: AbortSignal, now?: () => Date }} [opts] + */ +export async function changesTake(projectDir, id, opts = {}) { + const { take, spec } = await storedSpec(projectDir, id); + const from = opts.from ?? (typeof take.from === "string" ? take.from : null) ?? (typeof take.draftedFrom === "string" ? take.draftedFrom : null); + if (!from) throw new Error(`${id}: --from <take>: the take to compare with (this take does not record one)`); + await checkFrom(projectDir, id, from); + const pad = opts.pad ?? DEFAULT_PAD; + if (!Number.isFinite(pad) || pad < 0 || pad > 30) throw new Error("--pad is 0–30 seconds"); + const log = opts.log ?? (() => {}); + const takeDir = path.join(takesDirOf(projectDir), id); + const c = await composeTake(projectDir, { ...spec, window: "full" }, { log }); + const base = await baseManifest(projectDir, from); + const diff = diffTimelines(base.manifest.timeline, c.manifest.timeline); + const renderLines = renderLevelChanges(base.manifest, c.manifest); + // What renders: the ruled cut (its clip rulings applied, as the render's), so ids are the rendered ones. + const ruled = applyMontageRulings(c.manifest, await readMontageRulings(projectDir)).manifest; + const ids = sourcedEntries(ruled.timeline).map((e) => e.id); + const runs = planRuns(ids, diff); + const slug = String(c.manifest.slug ?? ""); + const p = previewPaths(takeDir, slug); + const preview = opts.preview !== false; + const baseSchedule = base.rendered ? await baseScheduleOf(path.join(takesDirOf(projectDir), from, "out", "sourced"), base.manifest) : null; + const changedIds = new Set(diff.changed.map((x) => x.id)); + log( + `${id}: changes against ${from}${base.rendered ? "" : " (a draft: its stored patch, as it would render now)"} — ` + + `${diff.changed.length} item(s) changed or added, ${diff.removed.length} removed` + + `${renderLines.length ? `; outside the timeline: ${renderLines.slice(0, 6).join(", ")}${renderLines.length > 6 ? ", …" : ""}` : ""}`, + ); + const doc = { + version: 1, + take: id, + from, + madeAt: (opts.now ?? (() => new Date()))().toISOString(), + pad, + tier: preview ? "preview" : "full", + reel: null, + times: null, + render: renderLines, + items: /** @type {any[]} */ ([]), + }; + if (!runs.length) { + log(`${id}: no item changed against ${from}${renderLines.length ? " — only render-level knobs: render a --preview to judge them" : ""}; no reel`); + await writeAtomic(p.changesFile, doc); + return { id, mp4: null, changes: doc }; + } + const want = new Set(runs.flatMap((r) => r.ids)); + let renderDoc = windowManifest(ruled, ids.filter((x) => want.has(x))); + // Its segments at the tier too, unless render.preview.segments says otherwise: a changes build is a + // window of the cut, whose post items key by their window's plan (a clock's, a progress bar's) and are + // built again whatever the base had -- so a fast encode of them forfeits no reuse. + if (preview) renderDoc = atPreviewTier(renderDoc, { segments: "preview" }); + log(`${id}: rendering ${want.size} entr${want.size === 1 ? "y" : "ies"} in ${runs.length} run(s): ${runs.map((r) => r.ids.join(" ")).join(" | ")}`); + const since = Date.now(); + const b = await buildInto(projectDir, { id, label: spec.label, kind: CHANGES_DIR, renderDoc, outDir: p.changesOut, from, opts }); + try { + const built = await buildPlaces(path.join(p.changesOut, "sourced"), [...want].sort((x, y) => ids.indexOf(x) - ids.indexOf(y)), since); + const measured = new Map([...changedIds].filter((x) => built.places.has(x)).map((x) => [x, built.places.get(x).duration])); + const full = fullCutTimes({ timeline: ruled.timeline, changedIds, base: baseSchedule, measured }); + const pieces = reelPieces(runs, built.places, full.times, pad); + // Cut, labelled, joined. + const work = path.join(p.changesOut, "reel-work"); + await rm(work, { recursive: true, force: true }); + await mkdir(work, { recursive: true }); + const font = await labelFont(renderDoc.render); + const size = (await probeSize(b.file)) ?? [Number(renderDoc.render?.width ?? 1920), Number(renderDoc.render?.height ?? 1080)]; + const tier = renderDoc.render?.tier; + const enc = ["-c:v", "libx264", "-preset", String(tier?.preset ?? renderDoc.render?.preset ?? "medium"), "-crf", String(tier?.crf ?? renderDoc.render?.crf ?? 20), "-pix_fmt", "yuv420p", "-r", String(renderDoc.render?.fps ?? 30), + "-c:a", "aac", "-b:a", String(renderDoc.render?.audioBitrate ?? "160k"), "-ar", String(renderDoc.render?.audioRate ?? 48000), "-ac", String(renderDoc.render?.audioChannels ?? 2)]; + const files = []; + let reelAt = 0; + for (const [k, piece] of pieces.entries()) { + const text = path.join(work, `label-${k}.txt`); + await writeFile(text, piece.label, "utf8"); + const out = path.join(work, `piece-${String(k).padStart(3, "0")}.mp4`); + const dur = Math.max(0.1, piece.to - piece.from); + await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-ss", piece.from.toFixed(3), "-i", b.file, "-t", dur.toFixed(3), "-vf", labelFilter({ textFile: text, font, height: size[1] }), ...enc, out], { maxBuffer: 1 << 26 }); + const got = (await probeSeconds(out)) ?? dur; + piece.reelStart = round3(reelAt); + piece.reelEnd = round3(reelAt + got); + reelAt += got; + files.push(out); + } + const list = path.join(work, "pieces.txt"); + await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n", "utf8"); + const tmp = p.changesMp4.replace(/\.mp4$/, `.${process.pid}.tmp.mp4`); + await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-c", "copy", "-movflags", "+faststart", tmp], { maxBuffer: 1 << 26 }); + await rename(tmp, p.changesMp4); + await rm(work, { recursive: true, force: true }); + const seconds = await probeSeconds(p.changesMp4); + doc.reel = path.relative(takeDir, p.changesMp4); + doc.times = { + basis: full.basis, + how: full.basis === "measured" + ? `${from}'s measured ${baseSchedule?.from === "segments" ? "segment lengths (its out/sourced/segments, end to end)" : "schedule (out/sourced/schedule.json)"}, each changed item's length as the changes build measured it` + : baseSchedule + ? `estimates: a changed item was not measured` + : `estimates: ${from} ${base.rendered ? "left no schedule or segments to measure" : "was never rendered"} — each unchanged item's length estimated, the changed ones measured`, + build: built.basis, + }; + doc.items = pieces.map((x) => ({ + id: x.id, type: x.type, kind: x.kind, kinds: x.kinds, label: x.label, + at: x.fullStart, end: x.fullEnd, exact: x.exact, + reel: { from: x.reelStart, to: x.reelEnd }, + ...(x.type === "join" ? { after: x.after, before: x.before } : {}), + })); + await writeAtomic(p.changesFile, doc); + const rd = await b.rec?.done({ mp4: p.changesMp4, seconds }); + if (rd && rd.state !== "done") throw new Error(rd.error ?? `${id}: the changes reel left no mp4`); + for (const it of doc.items) b.log(` ${it.label} (reel ${clockOf(it.reel.from)})`); + b.log(`${id}: changes reel ${doc.reel} — ${doc.items.length} piece(s), ${seconds ?? "?"} s; full-cut times: ${doc.times.basis} (${doc.times.how}); list: ${CHANGES_FILE}`); + return { id, mp4: p.changesMp4, seconds, changes: doc, renderSeconds: b.renderSeconds }; + } catch (e) { + await b.rec?.fail(e); + throw e; + } +} + +async function writeAtomic(file, doc) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, file); +} + +/** A take step's fast-feedback kind: "preview", "changes", or null for the take's own render (lib/queue). Pure. */ +export function fastKindOf(argv) { + const a = Array.isArray(argv) ? argv : []; + if (a[0] !== "take") return null; + if (a.includes("--changes")) return "changes"; + if (a.includes("--preview")) return "preview"; + return null; +} + +/** + * What `umtool take status` says of a take's fast-feedback renders: each one's record (out/preview/render.json, + * out/changes/render.json, resolved) and its output, when there. + * @param {string} takeDir + * @param {string} slug + */ +export async function fastRenders(takeDir, slug) { + const { readRenderRecord } = await import("./renderRecord.mjs"); + const p = previewPaths(takeDir, slug); + const one = async (dir, mp4) => { + const rec = await readRenderRecord(dir); + const st = await stat(mp4).catch(() => null); + if (!rec && !st) return null; + return { + state: rec?.state ?? (st ? "done" : null), + mp4: st?.isFile() ? mp4 : null, + mp4Bytes: st?.size ?? null, + seconds: rec?.seconds ?? null, + endedAt: rec?.endedAt ?? null, + error: rec?.error ?? null, + log: rec ? path.join(dir, "render.log") : null, + }; + }; + const [preview, changes, list] = await Promise.all([one(p.previewOut, p.previewMp4), one(p.changesOut, p.changesMp4), readJson(p.changesFile)]); + return { + preview, + changes: changes || list ? { ...(changes ?? { state: null, mp4: null }), list: list ? p.changesFile : null, items: Array.isArray(list?.items) ? list.items.length : null, from: list?.from ?? null } : null, + }; +} diff --git a/umtool/lib/report/takePreview.test.mjs b/umtool/lib/report/takePreview.test.mjs @@ -0,0 +1,181 @@ +// takePreview.mjs: the preview tier's knobs, the tier keyed apart from the full render's chunks, what +// changed between two takes (per kind), the reel's runs and pieces, and the full-cut time math. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + PREVIEW_DEFAULTS, atPreviewTier, clockOf, diffTimelines, entryChangeKinds, fullCutTimes, labelFilter, pieceLabel, planRuns, + previewKnobs, previewPaths, reelPieces, renderLevelChanges, +} from "./takePreview.mjs"; +import { fastKindOf } from "../queue/cli.mjs"; +import { chunkJobs, chunkVideoArgs, outputTier, tierFinalArgs } from "umtool-report-to-video/build-video"; + +const R = { width: 1920, height: 1080, fps: 30, preset: "medium", crf: 20, audioRate: 48000, audioChannels: 2 }; + +test("previewKnobs: the defaults, a knob over them, never larger than the cut, checked", () => { + assert.deepEqual(previewKnobs(R), { ...PREVIEW_DEFAULTS }); + assert.deepEqual(previewKnobs({ ...R, preview: { width: 960, height: 540, crf: 30 } }), { width: 960, height: 540, preset: "veryfast", crf: 30, segments: "shared" }); + // A 640x360 cut previews at its own size. + assert.deepEqual(previewKnobs({ ...R, width: 640, height: 360 }).width, 640); + assert.deepEqual(previewKnobs({ ...R, width: 640, height: 360 }).height, 360); + assert.throws(() => previewKnobs({ ...R, preview: { preset: "warp" } }), /x264 preset/); + assert.throws(() => previewKnobs({ ...R, preview: { crf: 99 } }), /0–51/); + assert.throws(() => previewKnobs({ ...R, preview: { segments: "half" } }), /shared/); + assert.throws(() => previewKnobs({ ...R, preview: "yes" }), /an object/); +}); + +test("atPreviewTier: render.tier set, the cut's own encode kept unless segments: preview", () => { + const doc = { slug: "s", render: R, timeline: [] }; + const t = atPreviewTier(doc); + assert.deepEqual(t.render.tier, { name: "preview", width: 1280, height: 720, preset: "veryfast", crf: 26 }); + assert.equal(t.render.preset, "medium"); + assert.equal(t.render.crf, 20); + assert.equal(doc.render.tier, undefined, "the manifest is copied"); + const s = atPreviewTier({ ...doc, render: { ...R, preview: { segments: "preview" } } }); + assert.equal(s.render.preset, "veryfast"); + assert.equal(s.render.crf, 26); + // A changes reel's default (segments at the tier), unless the manifest says. + assert.equal(atPreviewTier(doc, { segments: "preview" }).render.preset, "veryfast"); + assert.equal(atPreviewTier({ ...doc, render: { ...R, preview: { segments: "shared" } } }, { segments: "preview" }).render.preset, "medium"); + assert.deepEqual(outputTier(t.render), t.render.tier); + assert.equal(outputTier(R), null); +}); + +test("a preview's chunk keys are never a full render's: the tier's scale, preset and crf are in the key", () => { + const job = { + segments: ["/w/a.mp4", "/w/b.mp4"], durs: [2, 2], starts: [0, 2], span: { a: 0, b: 60 }, D: 0, totalFrames: 120, outPath: "/w/c.mp4", + }; + const full = chunkVideoArgs({ ...job, render: R }); + const prev = chunkVideoArgs({ ...job, render: atPreviewTier({ render: R }).render }); + assert.notDeepEqual(full.keyArgv, prev.keyArgv); + assert.ok(prev.keyArgv.join(" ").includes("scale=1280:720")); + assert.ok(prev.argv.includes("veryfast") && prev.argv.includes("26")); + // The full render's argv is what it always was: no scale, its own preset and crf. + assert.ok(!full.keyArgv.join(" ").includes("scale=1280")); + assert.ok(full.argv.includes("medium") && full.argv.includes("20")); + assert.equal(tierFinalArgs(R, "a", "b"), null); + // A preview encodes more chunks at once (its fast encode leaves the decode the bottleneck); the env still wins. + assert.equal(chunkJobs({}, R), 2); + assert.equal(chunkJobs({}, atPreviewTier({ render: R }).render), 4); + assert.equal(chunkJobs({ REPORT_VIDEO_CHUNK_JOBS: "3" }, atPreviewTier({ render: R }).render), 3); + assert.ok(tierFinalArgs(atPreviewTier({ render: R }).render, "a", "b")?.join(" ").includes("scale=1280:720")); +}); + +test("previewPaths: the outputs beside the full render's, the builds in their own dirs", () => { + const p = previewPaths("/r/p/takes/t", "slug"); + assert.equal(p.previewMp4, "/r/p/takes/t/out/slug.preview.mp4"); + assert.equal(p.previewOut, "/r/p/takes/t/out/preview"); + assert.equal(p.changesMp4, "/r/p/takes/t/out/slug.changes.mp4"); + assert.equal(p.changesFile, "/r/p/takes/t/changes.json"); +}); + +const post = (id, o = {}) => ({ type: "post", id, text: "words", narration: { script: "words", pick: 0, takes: [{ file: `n/${id}/take-1.wav` }] }, ...o }); + +test("entryChangeKinds: each kind of change by its keys, the narration read closely", () => { + const a = post("p1"); + const k = (b) => entryChangeKinds(a, b).kinds; + assert.deepEqual(k(a), []); + // A new take picked: re-read; one with a revoice step: re-voiced; an older one picked again: re-picked. + assert.deepEqual(k({ ...a, narration: { ...a.narration, pick: 1, takes: [...a.narration.takes, { file: "n/p1/take-2.wav" }] } }), ["re-read"]); + assert.deepEqual(k({ ...a, narration: { ...a.narration, pick: 1, takes: [...a.narration.takes, { file: "n/p1/take-2.revoice.wav", steps: [{ op: "revoice" }] }] } }), ["re-voiced"]); + const two = { ...a, narration: { ...a.narration, takes: [...a.narration.takes, { file: "n/p1/take-2.wav" }] } }; + assert.deepEqual(entryChangeKinds(two, { ...two, narration: { ...two.narration, pick: 1 } }).kinds, ["re-picked"]); + assert.deepEqual(k({ ...a, narration: { ...a.narration, rate: 1.1 } }), ["read knobs"]); + assert.deepEqual(k({ ...a, fx: [{ kind: "caption" }] }), ["fx"]); + assert.deepEqual(k({ ...a, hold: 2 }), ["hold"]); + assert.deepEqual(k({ ...a, panel: "side" }), ["panel"]); + assert.deepEqual(k({ ...a, pictureOnly: true }), ["picture only"]); + assert.deepEqual(k({ ...a, thread: { read: true } }), ["thread"]); + assert.deepEqual(k({ ...a, redact: ["x"] }), ["slurs"]); + assert.deepEqual(k({ ...a, media: [{ start: 2, end: 9 }] }), ["media trim"]); + assert.deepEqual(k({ ...a, wibble: 1 }), ["edited"]); + const clip = { type: "clip", id: "c1", start: 1, end: 4 }; + assert.deepEqual(entryChangeKinds(clip, { ...clip, cutEnd: 3.5 }).kinds, ["media trim"]); +}); + +test("diffTimelines: added, changed, moved and removed, in the new timeline's order", () => { + const A = [post("a"), post("b"), post("c"), post("d")]; + const B = [post("a"), post("c"), post("b", { hold: 1 }), { type: "video", id: "v", src: "x.mp4" }]; + const d = diffTimelines(A, B); + assert.deepEqual(d.changed.map((c) => [c.id, c.kind, c.kinds]), [ + ["c", "moved", ["moved"]], + ["b", "changed", ["moved", "hold"]], + ["v", "added", ["added video"]], + ]); + assert.deepEqual(d.removed, [{ id: "d", after: "c", before: null, type: "post" }]); + assert.deepEqual(diffTimelines(A, A), { changed: [], removed: [] }); +}); + +test("renderLevelChanges: render leaves and top-level keys, not the timeline nor render.preview", () => { + const a = { slug: "s", timeline: [post("a")], render: { crf: 20, chrome: { deck: { x: 1 } } } }; + const b = { slug: "s", timeline: [post("b")], render: { crf: 20, chrome: { deck: { x: 2 } }, preview: { crf: 30 } }, title: "T" }; + assert.deepEqual(renderLevelChanges(a, b), ["render.chrome.deck.x", "title"]); +}); + +test("planRuns: a change with a neighbour each side, a removal as its join, touching runs merged", () => { + const ids = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; + const diff = { + changed: [{ id: "b", kind: "changed", kinds: ["re-read"] }, { id: "c", kind: "changed", kinds: ["fx"] }, { id: "i", kind: "added", kinds: ["added video"] }], + removed: [{ id: "x", after: "e", before: "f", type: "post" }], + }; + const runs = planRuns(ids, diff); + assert.deepEqual(runs.map((r) => r.ids), [["a", "b", "c", "d", "e", "f"], ["h", "i", "j"]]); + assert.deepEqual(runs[0].focus.map((f) => [f.type, f.id]), [["item", "b"], ["item", "c"], ["join", "x"]]); + assert.deepEqual(planRuns(ids, { changed: [{ id: "a", kind: "changed", kinds: ["fx"] }], removed: [] }).map((r) => r.ids), [["a", "b"]]); +}); + +test("fullCutTimes: the base's measured schedule moved by the changed items' measured lengths", () => { + // Base: a 10, b 20, c 5, d 7 (an intro-less hard-cut cut). New: b re-read to 25 s, x (6 s) added after c, d removed. + const base = { estimated: false, transition: 0, segments: [ + { id: "a", start: 0, duration: 10 }, { id: "b", start: 10, duration: 20 }, { id: "c", start: 30, duration: 5 }, { id: "d", start: 35, duration: 7 }, { id: "e", start: 42, duration: 3 }, + ] }; + const timeline = [post("a"), post("b"), post("c"), post("x"), post("e")]; + const measured = new Map([["b", 25], ["x", 6]]); + const r = fullCutTimes({ timeline, changedIds: new Set(["b", "x"]), base, measured }); + assert.equal(r.basis, "measured"); + const at = (id) => [r.times.get(id)?.start, r.times.get(id)?.end]; + assert.deepEqual(at("a"), [0, 10]); + assert.deepEqual(at("b"), [10, 35]); + assert.deepEqual(at("c"), [35, 40]); + assert.deepEqual(at("x"), [40, 46]); + // e: 42 in the base; +25 +6 for b and x, −20 (b's old) −7 (d removed) = 46. + assert.deepEqual(at("e"), [46, 49]); + // A changed item not measured: from then on an estimate. + const est = fullCutTimes({ timeline, changedIds: new Set(["b", "x"]), base, measured: new Map([["b", 25]]), estimate: () => 4 }); + assert.equal(est.basis, "estimate"); + assert.equal(est.times.get("a")?.exact, true); + assert.equal(est.times.get("e")?.exact, false); + // No base schedule: every length estimated but the measured ones. + const none = fullCutTimes({ timeline, changedIds: new Set(["b"]), base: null, measured: new Map([["b", 25]]), estimate: () => 4 }); + assert.equal(none.basis, "estimate"); + assert.deepEqual([none.times.get("c")?.start, none.times.get("e")?.start], [29, 37]); +}); + +test("reelPieces: the item ± pad within its run, a removal's join, labelled with the full cut's time", () => { + const runs = [{ ids: ["a", "b", "c"], focus: [{ type: "item", id: "b", index: 1, kind: "changed", kinds: ["re-voiced"] }] }, + { ids: ["d", "e"], focus: [{ type: "join", id: "x", after: "d", before: "e", index: 3, kind: "removed", kinds: ["removed post"] }] }]; + const build = new Map([["a", { start: 0, duration: 2 }], ["b", { start: 2, duration: 10 }], ["c", { start: 12, duration: 1 }], ["d", { start: 13, duration: 4 }], ["e", { start: 17, duration: 5 }]]); + const full = new Map([["b", { start: 1279.5, end: 1289.5, exact: true }], ["d", { start: 1500, end: 1504, exact: false }], ["e", { start: 1504, end: 1509, exact: false }]]); + const p = reelPieces(runs, build, full, 3); + assert.deepEqual([p[0].from, p[0].to], [0, 13]); + assert.equal(p[0].label, "21:19 · b · re-voiced"); + assert.deepEqual([p[1].from, p[1].to], [14, 20]); + assert.equal(p[1].label, "25:04 · x removed — the join · removed post"); + assert.equal(p[1].exact, false); +}); + +test("clockOf, pieceLabel and the label's filter", () => { + assert.equal(clockOf(1279.9), "21:19"); + assert.equal(clockOf(3725), "1:02:05"); + assert.equal(pieceLabel({ type: "item", id: "k", kinds: ["fx", "hold"] }, 61), "1:01 · k · fx, hold"); + const f = labelFilter({ textFile: "/w/label 1.txt", font: "/f/a:b.ttf", height: 720 }); + assert.ok(f.startsWith("drawtext=textfile='/w/label 1.txt'")); + assert.ok(f.includes("fontfile='/f/a\\:b.ttf'")); + assert.ok(f.includes("fontsize=24")); +}); + +test("fastKindOf: a take step's preview or changes, never the take's own render", () => { + assert.equal(fastKindOf(["take", "p", "--id", "t", "--preview"]), "preview"); + assert.equal(fastKindOf(["take", "p", "--id", "t", "--changes", "--preview"]), "changes"); + assert.equal(fastKindOf(["take", "p", "--id", "t", "--full"]), null); + assert.equal(fastKindOf(["takes", "ls", "p"]), null); +}); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -4934,6 +4934,33 @@ export function xfadeConcatArgs({ segments, durs, render, outPath, railPlan = nu ]; } +/** The argv that brings a finished cut to its tier's size and encode, the sound copied. Pure. */ +export function tierFinalArgs(render, inPath, outPath) { + const t = outputTier(render); + if (!t) return null; + return [ + "-nostdin", "-v", "error", "-y", "-i", inPath, + "-map", "0:v:0", "-map", "0:a?", + "-vf", `scale=${t.width}:${t.height}:flags=bicubic,setsar=1`, + "-c:v", "libx264", "-preset", t.preset, "-crf", String(t.crf), "-pix_fmt", "yuv420p", + "-c:a", "copy", "-movflags", "+faststart", + outPath, + ]; +} + +/** A final not yet at its tier's size (outputTier) is encoded to it, through a rename. Nothing without a tier. */ +async function tierFinalPass(final, render) { + const t = outputTier(render); + if (!t) return; + const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", final]); + const [w, h] = String(stdout).trim().split(",").map(Number); + if (w === t.width && h === t.height) return; + const tmp = final.replace(/\.mp4$/, `.${process.pid}.tier.mp4`); + await execFileP(FFMPEG, /** @type {string[]} */ (tierFinalArgs(render, final, tmp)), { maxBuffer: 1 << 26 }); + await rename(tmp, final); + EMIT("note", { message: `${t.name}: the cut ${w}x${h} → ${t.width}x${t.height} (${t.preset}, crf ${t.crf})` }); +} + // ---- the chunked final encode (chunked-encode.mjs) --------------------------- /** Is the final encode chunked? `REPORT_VIDEO_CHUNKED=0` or `render.chunkedEncode: false` say no. */ @@ -4942,17 +4969,54 @@ export function chunkedEncodeOn(render = {}, env = process.env) { return render?.chunkedEncode !== false; } -/** How many chunks are encoded at once: `REPORT_VIDEO_CHUNK_JOBS`, else 2. */ -export function chunkJobs(env = process.env) { +/** + * How many chunks are encoded at once: `REPORT_VIDEO_CHUNK_JOBS`, else 2 -- 4 at a preview's tier + * (outputTier), whose fast encode leaves each chunk's single-threaded decode and overlay the bottleneck. + */ +export function chunkJobs(env = process.env, render = null) { const n = Number(env.REPORT_VIDEO_CHUNK_JOBS); - return Number.isInteger(n) && n >= 1 ? Math.min(n, 8) : 2; + if (Number.isInteger(n) && n >= 1) return Math.min(n, 8); + return outputTier(render) ? 4 : 2; } -/** A chunk's picture encode: the cut's own settings, no sound. */ +/** + * THE OUTPUT TIER (umtool take … --preview / --changes; lib/report/takePreview.mjs): `render.tier`, which + * only a preview's render manifest carries -- `{ name: "preview", width, height, preset, crf }`. The cut is + * composed exactly as the full render composes it (the same 1920×1080 layout, segments, chrome frames and + * sound); only its FINAL picture is encoded smaller and faster: each chunk of the final encode scaled to + * `width`×`height` at the tier's preset and crf. Those are in the chunk's argv, so in its key: a preview's + * chunks key apart from the full render's and never stand in for them. Null (every full render): nothing + * changes, byte for byte. Pure. + * + * @returns {{ name: string, width: number, height: number, preset: string, crf: number } | null} + */ +export function outputTier(render) { + const t = render?.tier; + if (!t || typeof t !== "object" || Array.isArray(t)) return null; + const even = (v, d) => { + const n = Math.round(Number(v ?? d)); + if (!Number.isFinite(n) || n < 16 || n > 7680) throw new Error(`render.tier: width/height must be 16–7680, got ${JSON.stringify(v)}`); + return n - (n % 2); + }; + const crf = Number(t.crf ?? 26); + if (!Number.isFinite(crf) || crf < 0 || crf > 51) throw new Error(`render.tier.crf must be 0–51, got ${JSON.stringify(t.crf)}`); + const preset = String(t.preset ?? "veryfast"); + if (!/^(ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow)$/.test(preset)) throw new Error(`render.tier.preset: an x264 preset, got ${JSON.stringify(t.preset)}`); + return { name: String(t.name ?? "preview"), width: even(t.width, 1280), height: even(t.height, 720), preset, crf }; +} + +/** The scale filter a tier lays on the final picture (`[in]…[out]`), or null without one. Pure. */ +export function tierScaleFilter(render, inLabel, outLabel = "[vtier]") { + const t = outputTier(render); + if (!t) return null; + return `${inLabel}scale=${t.width}:${t.height}:flags=bicubic,setsar=1${outLabel}`; +} + +/** A chunk's picture encode: the cut's own settings (a tier's, when it has one), no sound. */ const chunkEncodeArgs = (render) => [ "-c:v", "libx264", - "-preset", render.preset ?? "medium", - "-crf", String(render.crf ?? 20), + "-preset", outputTier(render)?.preset ?? render.preset ?? "medium", + "-crf", String(outputTier(render)?.crf ?? render.crf ?? 20), "-pix_fmt", "yuv420p", "-r", String(render.fps), "-an", @@ -5041,6 +5105,10 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins // Nothing laid over and no dip: -map cannot name a trim's output twice, so // the label is used as is (it is a filter output, which -map can name). } + // A preview's tier (outputTier): the picture scaled last -- in the graph, so in the key. + const scaled = tierScaleFilter(render, dp.label); + if (scaled) parts.push(scaled); + const outLabel = scaled ? "[vtier]" : dp.label; const graph = parts.join(";"); const keyGraph = hk ? graph.replace(hf.chain, hk.chain) : graph; const head = ["-nostdin", "-v", "error", "-y"]; @@ -5049,7 +5117,7 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins ...segs.flatMap((s) => ["-i", s]), ...(hf ? hf.inputs : []), "-filter_complex", graph, - "-map", dp.label, + "-map", outLabel, ...chunkEncodeArgs(render), outPath, ]; @@ -5058,7 +5126,7 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins ...segs.flatMap((_, k) => ["-i", `<in:${k}>`]), ...(hk ? hk.inputs : []), "-filter_complex", keyGraph, - "-map", dp.label, + "-map", outLabel, ...chunkEncodeArgs(render), ]; return { argv, keyArgv, inputs, first, last }; @@ -5459,7 +5527,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, EMIT("note", { message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused` + `${plan.some((p) => p.pooled) ? `, ${plan.filter((p) => p.pooled).length} from the render pool` : ""}), ` + - `${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs()} at a time)`, + `${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs(process.env, render)} at a time)`, }); // Why, grouped, so a line says what changed rather than listing 80 chunks. const byWhy = new Map(); @@ -5515,7 +5583,7 @@ export async function chunkedConcat({ segments, render, outPath, chrome = null, }); }); const tEnc = Date.now(); - await runPool([audioJob, ...jobs], chunkJobs()); + await runPool([audioJob, ...jobs], chunkJobs(process.env, render)); const encSeconds = (Date.now() - tEnc) / 1000; // Joined: the concat demuxer over the chunks in order, the sound beside. @@ -7331,6 +7399,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly ); } await pruneFrames(); + // A preview's tier (outputTier) on a final that did not pass the chunked encode (a stream-copied hard + // cut with no deck, a rail's pass): scaled once here, the sound copied. + await tierFinalPass(final, render); const { stdout } = await execFileP(FFPROBE, [ "-v", "error", "-show_entries", "format=duration,size",