// 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
--id --preview [--from ]
// 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//out/.preview.mp4
// takes//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/.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 --id --preview --at S --dur S
// CUT SECONDS [S, S + dur] of the take's own cut (its schedule: the last preview's or render's, else its
// entries' own lengths, said as estimates) -- not the project's draft, whose timeline a take may not
// share (rev9-a9, 12 Nov: `--at 440 --dur 170` timed over the draft rendered 92 s of early clips). The
// whole take is handed to the build with the window (build-video --cut-window): every segment built or
// reused by its key, only the window's seconds laid and encoded, the deck drawn over the whole cut's
// schedule from S -- its timeline, counters and trail at their state then, never reset. Into
// takes//out/.preview.-.mp4 the window's own file, never over the full preview's
// takes//out/window/ its build and record
//
// umtool take --id --changes [--from ] [--pad 3] [--no-preview]
// a REEL of only what changed against (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//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//out/.changes.mp4. takes//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, getPath, linkSharedOut, MANIFEST, mergePatch, QUICK_RENDER, sourcedEntries, windowEntries, windowManifest } from "./takeMaker.mjs";
import { takesDirOf, TAKE_FILE } from "./takes.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
const execFileP = promisify(execFile);
const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg";
const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe";
/** The 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//out/. */
export const PREVIEW_DIR = "preview";
export const CHANGES_DIR = "changes";
/** A windowed preview's build dir (`--preview --at S --dur S`). */
export const WINDOW_DIR = "window";
/** 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} [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 }");
// A 9:16 cut (`render.format: "vertical"`, built 1080x1920 whatever its width and height say) previews 9:16:
// the defaults turned on their side, never squashed into a 16:9 tier (lane vertical-deck).
const vertical = render?.format === "vertical";
const k = { ...PREVIEW_DEFAULTS, ...(vertical ? { width: PREVIEW_DEFAULTS.height, height: PREVIEW_DEFAULTS.width } : {}), ...(isObj(raw) ? raw : {}) };
const W = vertical ? 1080 : Number(render?.width ?? 1920);
const H = vertical ? 1920 : 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} 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),
};
}
/** Seconds in a file name: 440, 612.5. Pure. */
const secondsName = (v) => String(Math.round(Number(v) * 1000) / 1000);
/** A windowed preview's file, beside the full preview and never over it: .preview.-.mp4. Pure. */
export function windowPreviewMp4(takeDir, slug, win) {
return path.join(takeDir, "out", `${slug}.preview.${secondsName(win.at)}-${secondsName(win.at + win.dur)}.mp4`);
}
/**
* Which entries of the TAKE's own cut a window of cut seconds covers: timed by `schedule` (the take's last
* measured one, when newer than its take.json: takeScheduleOf) when it names every entry, else by the entries'
* own lengths (estimates). A window that starts at or past the end -- measured, or estimated (said so) -- is
* refused before anything is built, naming the unit. Pure.
*
* @param {Array>} timeline the take's render timeline (its rulings applied)
* @param {{ at: number, dur: number }} win
* @param {{ segments?: Array<{ id: string, start: number, duration: number }>, estimated?: boolean } | null} schedule
* @param {Record | null} [render] the take's render (an estimate under render.montage applies no gaps)
* @returns {{ ids: string[], basis: "schedule" | "estimate", total: number }}
*/
export function previewWindowPlan(timeline, win, schedule, render = null) {
const measured = schedule && schedule.estimated !== true ? schedule : null;
const w = windowEntries(timeline, win, measured, render);
if (!(win.at < w.total)) {
const len = Math.round(w.total * 10) / 10;
throw new Error(
w.basis === "schedule"
? `--at ${win.at} is past the end of the take's cut (${len} s of cut time, by its schedule): --at and --dur are seconds of the take's cut`
: `--at ${win.at} is past the end of the take's cut by its entries' own lengths (an estimate: ${len} s of cut time; the take has no schedule newer than its take.json): --at and --dur are seconds of the take's cut`,
);
}
return { ids: w.ids, basis: w.basis, total: w.total };
}
// ---------------------------------------------------------------------------
// 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} a
* @param {Record} 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.` 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>} beforeTimeline
* @param {Array>} 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} 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> }>} */
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>, changedIds: Set, base: { segments: Array<{ id: string, start: number, duration: number }>, transition?: number, estimated?: boolean } | null,
* measured: Map, estimate?: (e: Record, render?: Record | null) => number, render?: Record | null }} o
* @returns {{ basis: "measured" | "estimate", times: Map }}
*/
export function fullCutTimes({ timeline, changedIds, base, measured, estimate = estimatedSeconds, render = null }) {
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, render);
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, render);
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} runs
* @param {Map} build each id's place in the reel's build
* @param {Map} 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 --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",
quick: take.quick === true,
}),
};
}
/** As makeTake decides: a take crossfades only when its own patches set a transition (else its hard cuts). */
const takeXfade = (c) => Number(c.manifest.render?.transition ?? 0) > 0 && c.patches.some((p) => getPath(p, "render.transition") !== undefined);
/** 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, xfade, opts, cutWindow = null }) {
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, ...(cutWindow ? { window: cutWindow } : {}) })
.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: xfade === true, keepFrames: false, emit, log, ...(cutWindow ? { cutWindow } : {}), ...(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
--id --preview [--from ]`: 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 = {}) {
// --at/--dur said: seconds of the take's own cut, to the window's own file (windowPreview).
if (opts.window && opts.window !== "full") return windowPreview(projectDir, id, opts.window, 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 });
// A quick take's render is encoded veryfast (makeTake's QUICK_RENDER): its preview builds what it built.
const renderDoc = atPreviewTier(spec.quick ? /** @type {Record} */ (mergePatch(c.renderDoc, QUICK_RENDER)) : 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, xfade: takeXfade(c), 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 };
}
/**
* The take's last measured schedule: its preview's build, else its full render's -- the newer -- and only when it is
* newer than the take's take.json (a take edited since may have grown: review 1, S1); else null (estimates).
*/
async function takeScheduleOf(takeDir) {
const taken = await stat(path.join(takeDir, TAKE_FILE)).catch(() => null);
const got = [];
for (const d of [path.join(takeDir, "out", PREVIEW_DIR, "sourced"), path.join(takeDir, "out", "sourced")]) {
const file = path.join(d, "schedule.json");
const [doc, st] = await Promise.all([readJson(file), stat(file).catch(() => null)]);
if (doc && st && doc.estimated !== true && Array.isArray(doc.segments)) got.push({ doc, mtime: st.mtimeMs, file });
}
got.sort((a, b) => b.mtime - a.mtime);
const best = got[0] ?? null;
// Strictly newer: a timestamp tie (coarse fs clocks) is not proof the schedule saw this take.json.
return best && taken && !(best.mtime > taken.mtimeMs) ? null : best;
}
/** "600-1100": a window's span as a file name and a label say it. Pure. */
export const windowSpan = (win) => `${secondsName(win.at)}-${secondsName(win.at + win.dur)}`;
/**
* `umtool take --id --preview --at S --dur S`: cut seconds [S, S + dur] of the take's own cut at the
* preview tier -- the whole take built (segments reused by their keys), only the window laid and encoded, its
* chrome at its state then (build-video --cut-window). To .preview.-.mp4; the full preview,
* and the take's render, untouched.
*
* @param {string} projectDir
* @param {string} id
* @param {{ at: number, dur: number }} win
* @param {Parameters[2]} [opts]
*/
async function windowPreview(projectDir, id, win, 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: "full" }, { log });
const renderDoc = atPreviewTier(spec.quick ? /** @type {Record} */ (mergePatch(c.renderDoc, QUICK_RENDER)) : c.renderDoc);
const takeDir = path.join(takesDirOf(projectDir), id);
const slug = String(c.manifest.slug ?? "");
const sched = await takeScheduleOf(takeDir);
const plan = previewWindowPlan(renderDoc.timeline, win, sched?.doc ?? null, renderDoc.render ?? null);
const outDir = path.join(takeDir, "out", WINDOW_DIR);
// One window at a time (review 1, S3): its build dir, record and work files are shared.
{
const { readRenderRecord } = await import("./renderRecord.mjs");
const live = await readRenderRecord(outDir);
if (live && (live.state === "running" || live.state === "waiting")) {
throw new Error(`a window preview of ${id} is running (pid ${live.pid}, window ${live.window ? windowSpan(live.window) : "?"}, since ${live.startedAt}): wait for it to end (umtool take status --id ${id})`);
}
}
const span = `cut seconds ${secondsName(win.at)}–${secondsName(win.at + win.dur)}`;
const t = renderDoc.render.tier;
log(
`${id}: a preview of ${span} of the take's cut — ${plan.ids.length} entr${plan.ids.length === 1 ? "y" : "ies"} (${plan.ids.join(", ")}), ` +
(plan.basis === "schedule" ? `timed by ${path.relative(takeDir, sched?.file ?? "")}` : "timed by their own lengths (estimates: the take has no schedule newer than its take.json)") +
`; ${t.width}x${t.height}, ${t.preset}, crf ${t.crf}; the whole cut's segments built or reused, its chrome at its state then (no rail)` +
`${from ? `; reusing ${from}'s` : ""}${take.draft ? " (a draft: its stored patch)" : ""}`,
);
// The window the build laid (build-video's done event: clipped at the cut's end), else the plan's end clips it.
let laid = null;
const emit = opts.emit ?? (() => {});
const watched = { ...opts, emit: (ev) => {
if (ev?.ev === "done" && ev.window && Number.isFinite(Number(ev.window.at)) && Number(ev.window.dur) > 0) laid = { at: Number(ev.window.at), dur: Number(ev.window.dur) };
emit(ev);
} };
const b = await buildInto(projectDir, { id, label: `${spec.label} ${span}`, kind: WINDOW_DIR, renderDoc, outDir, from, xfade: takeXfade(c), opts: watched, cutWindow: win });
const rendered = laid ?? { at: win.at, dur: Math.max(0, Math.min(win.dur, plan.total - win.at)) };
const mp4 = windowPreviewMp4(takeDir, slug, rendered);
try {
await rename(b.file, mp4);
} catch (e) {
await b.rec?.fail(e);
throw e;
}
const seconds = await probeSeconds(mp4);
const doc = await b.rec?.done({ mp4, seconds });
if (doc && doc.state !== "done") throw new Error(doc.error ?? `${id}: the window's preview left no mp4`);
b.log(`${id}: preview of ${span} ${path.relative(takeDir, mp4)} — ${seconds ?? "?"} s, rendered in ${b.renderSeconds} s`);
return { id, mp4, seconds, renderSeconds: b.renderSeconds, tier: t, window: win, rendered, covers: plan.ids, basis: plan.basis };
}
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//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 --id --changes [--from ] [--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 : 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, xfade: takeXfade(c), 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, render: ruled.render ?? null });
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 = tmpPathFor(p.changesMp4.replace(/\.mp4$/, ""), { ext: ".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 = tmpPathFor(file);
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";
// A window of the take (--preview --at/--dur): its own build and record, out/window/ (review 1, S4).
if (a.includes("--preview") && (a.includes("--at") || a.includes("--dur"))) return "window";
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)]);
// The last window's: its record names its file and its window (`span`, as asked).
const windowOut = path.join(takeDir, "out", WINDOW_DIR);
const wrec = await readRenderRecord(windowOut);
const wmp4 = wrec?.mp4 ? path.resolve(windowOut, wrec.mp4) : null;
const window = wrec ? { ...(await one(windowOut, wmp4 ?? path.join(windowOut, "-"))), span: wrec.window ? windowSpan(wrec.window) : null } : null;
return {
preview,
window,
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,
};
}