// BEAT REELS, PLAYED AND WALKED FROM THE MASTER (lane/beat-reels, 2 Nov). // // The operator: "I want to be able to play and walk the trailer the same as // main, even if I need to have a rendered main first." A reel's beats // (promo/-beats.json, trailerBeats.mjs) are spans of a take's FINISHED // MASTER (`takes//out/.mp4`), so the chrome on screen is the // render's own and nothing is built to preview it: the Play view is seeks. // // The mapping is the trailer's own, never a second one: each beat goes // through report-to-video/trailer.mjs `planTrailer` over the take's build // records (the schedule and the segments' cut records), exactly as `umtool // trailer` maps it -- the master's crossfades kept out, the seamless runs // joined, a clip's gaps played as the master's jump cut. What Play shows is // the plan's pieces with the edges AS WRITTEN (`snap: false`): the cut then // moves each clip beat's edges into the nearest pause (≤ SNAP_MAX_SHIFT), and // says so per edge in its record. // // A beat the take cannot map (its clip is not in that take's cut, or it lies // outside the source its segment was cut from) is not dropped silently: its // row carries the refusal and the reel plays the others. // // Plain ESM: the CLI (`umtool trailer --reel`) reads the take choice from here too. import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { offsetIn, recordGaps } from "umtool-report-to-video/gaps"; import { TRAILER_XFADE_DEFAULT, TrailerError, loadTakeBuild, parseBeats, planTrailer, scheduleSpans, trailerOutPath, trailerRecordPath, } from "umtool-report-to-video/trailer"; import { anchorContext, reelStatus } from "./reelAnchor.mjs"; import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; import { listTakes, takesDirOf } from "./takes.mjs"; import { DEFAULT_REEL, TRAILER_LIMIT_DEFAULT, readTrailerBeats, reelFileOf, reelVersion } from "./trailerBeats.mjs"; const r3 = (n) => Number(Number(n).toFixed(3)); const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then(JSON.parse, () => null); /** The `--out` that puts a reel's cut at `..mp4` (the trailer reel: the default name). */ export const reelOutArg = (slug, reel = DEFAULT_REEL) => (reel === DEFAULT_REEL ? null : `${slug}.${reel}`); /** * Every take that has (or will have) a master: its slug, the master's path and * mtime, whether its build records are there, and whether it is rendering now. * Newest master first. * * @param {string} projectDir */ export async function takeMasters(projectDir) { const { takes } = await listTakes(projectDir); const out = []; for (const t of takes) { const dir = path.join(takesDirOf(projectDir), t.id); const m = await readJson(path.join(dir, "video.manifest.json")); const slug = typeof m?.slug === "string" ? m.slug : null; const master = slug ? path.join(dir, "out", `${slug}.mp4`) : null; const st = master ? await stat(master).catch(() => null) : null; const schedule = await stat(path.join(dir, "out", "sourced", "schedule.json")).catch(() => null); const locks = await Promise.all([path.join(dir, BUILD_LOCK), path.join(dir, "out", BUILD_LOCK)].map((f) => readBuildLock(f))); out.push({ id: t.id, label: t.label, draft: t.draft === true, builtAt: t.builtAt, slug, dir, master: st?.isFile() ? master : null, masterMtimeMs: st?.isFile() ? Math.round(st.mtimeMs) : null, masterSize: st?.isFile() ? st.size : null, built: !!schedule && !!st?.isFile(), rendering: locks.some((l) => lockIsLive(l)), }); } out.sort((a, b) => (b.masterMtimeMs ?? 0) - (a.masterMtimeMs ?? 0) || String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? ""))); return out; } /** * Where a reel has been cut: in each take, its output (`..mp4`, the * trailer reel `.trailer.mp4`) and the record beside it. Newest first. * * @param {Awaited>} masters * @param {string} reel */ export async function reelCuts(masters, reel = DEFAULT_REEL, { version = null } = {}) { const out = []; for (const t of masters) { if (!t.slug) continue; const file = trailerOutPath(t.dir, t.slug, reelOutArg(t.slug, reel)); const st = await stat(file).catch(() => null); if (!st?.isFile()) continue; const recordPath = trailerRecordPath(file); const rec = await readJson(recordPath); out.push({ take: t.id, out: file, size: st.size, mtimeMs: Math.round(st.mtimeMs), record: rec ? recordPath : null, builtAt: typeof rec?.builtAt === "string" ? rec.builtAt : new Date(st.mtimeMs).toISOString(), seconds: Number.isFinite(rec?.seconds) ? rec.seconds : null, encodeSeconds: Number.isFinite(rec?.encodeSeconds) ? rec.encodeSeconds : null, notes: Array.isArray(rec?.notes) ? rec.notes.length : 0, // Cut from another master than the one there now (its record names the master's mtime; // an older record, before that: cut before the master was written): rendered again since. stale: t.masterMtimeMs !== null && (Number.isFinite(rec?.source?.masterMtimeMs) ? rec.source.masterMtimeMs !== t.masterMtimeMs : st.mtimeMs < t.masterMtimeMs), // The reel edited since the cut (its record names the reel's version, trailerBeats.mjs reelVersion). reelChanged: !!(version && typeof rec?.reel?.version === "string" && rec.reel.version !== version), }); } out.sort((a, b) => String(b.builtAt).localeCompare(String(a.builtAt))); return out; } /** * The take a reel plays and is cut from: the one asked for; else the reel's * pinned `take`; else the take it was last cut from; else the latest take * with a finished master. Only a take with a master and its build records * qualifies (a take rendering now does not, unless asked for by name). * * @returns {{ id: string, why: "asked" | "pinned" | "last cut" | "latest master" } | null} */ export function pickReelTake({ asked = null, pinned = null, cuts = [], masters = [] }) { const ok = (id, { rendering = false } = {}) => masters.some((m) => m.id === id && m.built && (rendering || !m.rendering)); if (asked && masters.some((m) => m.id === asked)) return { id: asked, why: "asked" }; if (pinned && ok(pinned)) return { id: pinned, why: "pinned" }; const last = cuts.find((c) => ok(c.take)); if (last) return { id: last.take, why: "last cut" }; const latest = masters.find((m) => m.built && !m.rendering); return latest ? { id: latest.id, why: "latest master" } : null; } /** * Each beat mapped onto the master, the trailer's own way (planTrailer, the * edges as written). Pure: the build is loadTakeBuild's. * * @param {{ schedule: any, records: Map, manifest: any }} build * @param {any[]} rawBeats the reel file's beats * @param {{ intro?: boolean, xfade?: number }} [opts] */ export function reelPlan(build, rawBeats, { intro = false, xfade = TRAILER_XFADE_DEFAULT } = {}) { const { spans, total, fps, D } = scheduleSpans(build.schedule); const entries = new Map((build.manifest?.timeline ?? []).filter((e) => e?.id).map((e) => [e.id, e])); /** @type {Array<{ n: number, raw: any, beat: any | null, problem: string | null }>} */ const rows = rawBeats.map((raw, i) => { let beat = null; let problem = null; try { [beat] = parseBeats([raw]); // Mapped alone first: a beat the take cannot place is said by its number, the others still play. planTrailer({ schedule: build.schedule, records: build.records, beats: [beat], xfade: 0, snap: false }); } catch (e) { problem = (e instanceof Error ? e.message : String(e)).replace(/^beat 1\b/, `beat ${i + 1}`); beat = null; } return { n: i + 1, raw, beat, problem }; }); const good = rows.filter((r) => r.beat); const notes = []; let plan = null; let usedXfade = xfade; const tryPlan = (x, withIntro) => planTrailer({ schedule: build.schedule, records: build.records, beats: good.map((r) => r.beat), intro: withIntro, xfade: x, snap: false }); if (good.length || intro) { try { plan = tryPlan(xfade, intro); } catch (e) { const why = e instanceof Error ? e.message : String(e); // The intro refused (no brand intro in this take) or a piece too short for the crossfade: // played without what refused, and said. try { plan = tryPlan(xfade, false); notes.push(`played without the intro: ${why}`); intro = false; } catch { try { plan = tryPlan(0, false); usedXfade = 0; intro = false; notes.push(`played with hard cuts: ${why}`); } catch (e2) { notes.push(e2 instanceof Error ? e2.message : String(e2)); plan = null; } } } } const pieces = plan?.pieces ?? []; const off = intro && plan ? 1 : 0; const byRow = new Map(good.map((r, k) => [r.n, pieces[k + off]])); const out = rows.map((r) => { const p = byRow.get(r.n) ?? null; const raw = r.raw ?? {}; const isClip = raw.id !== undefined; const e = isClip ? entries.get(raw.id) : null; let asked = null; let limits = null; let map = null; if (r.beat && isClip) { const seg = spans.get(raw.id); const rec = build.records.get(raw.id); const gaps = recordGaps(rec); const toMaster = (src) => r3(seg.start + offsetIn(src, rec.start, gaps)); asked = { start: toMaster(raw.start), end: toMaster(raw.end) }; // A handle may go anywhere the source its segment was cut from plays // (the cut record's start–end, what `umtool trailer` accepts); an edge // in the master's own crossfade is pulled out of it by the plan. limits = { start: r3(seg.start), end: r3(Math.min(seg.end, toMaster(rec.end))), source: { start: rec.start, end: rec.end }, }; map = { segStart: seg.start, recStart: rec.start, gaps }; } else if (r.beat) { asked = { start: r3(raw.at), end: r3(raw.at + raw.dur) }; limits = { start: 0, end: r3(total), source: null }; } return { n: r.n, kind: isClip ? "clip" : "raw", id: isClip ? String(raw.id) : null, label: typeof raw.label === "string" ? raw.label : null, verdict: raw.verdict === "confirmed" || raw.verdict === "note" ? raw.verdict : null, beat: isClip ? { start: raw.start, end: raw.end, ...(Array.isArray(raw.gaps) && raw.gaps.length ? { gaps: raw.gaps } : {}) } : { at: raw.at, dur: raw.dur }, problem: r.problem, // Where it plays: the plan's piece (master span after the crossfades are kept out; where it lands in the reel). piece: p ? { at: p.at, master: p.master, frames: p.frames, seamless: p.seamless === true, moved: p.moved ?? null, source: p.source ?? null, // A gapped beat: the master spans it leaves out, and what it plays. cuts: (p.cuts ?? []).map((c) => ({ from: c.from, to: c.to })), seconds: p.seconds ?? p.master.duration, } : null, asked, limits, map, quote: typeof e?.quote === "string" ? e.quote : null, title: typeof (e?.title ?? e?.onscreen?.title) === "string" ? (e.title ?? e.onscreen.title) : null, channel: typeof e?.channel === "string" ? e.channel : (build.manifest?.provenance?.channelSlug ?? null), video: typeof e?.video === "string" ? e.video : null, date: typeof e?.date === "string" ? e.date : null, }; }); const introPiece = intro && plan ? pieces[0] : null; return { fps, transition: D, masterSeconds: r3(total), xfade: plan ? plan.xfade : usedXfade, intro: introPiece ? { at: introPiece.at, master: introPiece.master } : null, total: plan ? plan.total : 0, rows: out, planNotes: [...notes, ...(plan?.notes ?? [])], }; } /** * What the reel's Play and walk read: the reel (its settings and beats), the * takes that have masters, the take chosen, each beat on that master, and the * reel's cuts. `noMaster` when no take has a finished master -- the page says * so and offers the render; nothing renders on its own. * * @param {{ id: string, dir: string }} project * @param {{ reel?: string, take?: string | null }} [opts] */ export async function reelPlayView(project, { reel = DEFAULT_REEL, take = null } = {}) { const doc = await readTrailerBeats(project.dir, { reel }); const settings = doc.settings ?? {}; const masters = await takeMasters(project.dir); const cuts = await reelCuts(masters, reel, { version: doc.exists ? reelVersion(doc) : null }); const chosen = pickReelTake({ asked: take, pinned: settings.take ?? null, cuts, masters }); const base = { project: project.id, reel, file: reelFileOf(reel), title: settings.title ?? null, limit: typeof settings.limit === "number" ? settings.limit : TRAILER_LIMIT_DEFAULT, xfade: typeof settings.xfade === "number" ? settings.xfade : TRAILER_XFADE_DEFAULT, introAsked: settings.intro === true, pinned: settings.take ?? null, token: doc.token, beats: doc.beats.length, takes: masters.map((m) => ({ id: m.id, label: m.label, built: m.built, rendering: m.rendering, draft: m.draft, master: m.master, masterMtimeMs: m.masterMtimeMs })), cuts, }; if (!chosen) { const latest = masters[0] ?? null; return { ...base, take: null, noMaster: { why: masters.length ? `no take has a finished master yet${masters.some((m) => m.rendering) ? ` (${masters.filter((m) => m.rendering).map((m) => m.id).join(", ")} is rendering)` : ""} — a reel plays the master's own frames, so render a take first` : "this project has no takes yet — a reel plays a take's finished master, so make and render one first", take: latest?.id ?? null, }, }; } const m = masters.find((x) => x.id === chosen.id); if (!m?.built) { return { ...base, take: { id: chosen.id, why: chosen.why, label: m?.label ?? chosen.id }, noMaster: { why: `take ${chosen.id} has no finished master${m?.rendering ? " (it is rendering now)" : ""}: ${m?.master ? "its build records (out/sourced/schedule.json) are missing" : `no out/${m?.slug ?? ""}.mp4`}`, take: chosen.id } }; } let build; try { build = await loadTakeBuild(m.dir); } catch (e) { return { ...base, take: { id: chosen.id, why: chosen.why, label: m.label }, noMaster: { why: e instanceof TrailerError || e instanceof Error ? e.message : String(e), take: chosen.id } }; } const plan = reelPlan(build, doc.beats, { intro: settings.intro === true, xfade: base.xfade }); // Each beat against this take (reelAnchor.mjs): what it was cut against, and what changed since. const ctx = await anchorContext(m.dir, { take: chosen.id, masterMtimeMs: m.masterMtimeMs, build }).catch(() => null); const status = ctx ? reelStatus(doc.beats, ctx) : null; if (status) for (const r of plan.rows) { const st = status.rows[r.n - 1]; r.status = st ? { state: st.state, why: st.why, ...(st.was ? { was: st.was } : {}), ...(st.now ? { now: st.now } : {}) } : null; } return { status: status ? { take: status.take, against: status.against, changed: status.changed, counts: status.counts, line: status.line } : null, ...base, take: { id: chosen.id, why: chosen.why, label: m.label, slug: build.slug, master: build.master, masterMtimeMs: m.masterMtimeMs, rendering: m.rendering, }, noMaster: null, ...plan, }; } /** * A take's anchoring context (reelAnchor.mjs anchorContext), by its id: the * anchor a beat written against it gets, and what it says of each clip now. * Null when the take has no finished master. * * @param {string} projectDir * @param {string} take */ export async function anchorContextOf(projectDir, take) { const m = (await takeMasters(projectDir)).find((x) => x.id === take); if (!m?.built) return null; return anchorContext(m.dir, { take, masterMtimeMs: m.masterMtimeMs }); } /** A reel's cut may take this long on the runner: one ffmpeg pass over spans of a master, in the heavy slot (it may wait there). */ export const REEL_CUT_TIMEOUT_MS = 45 * 60 * 1000; /** * The runner's job for Cut the trailer: `umtool trailer

--reel --take * ` -- the CLI, so the page and a terminal do the same thing; it takes the * heavy slot itself (trailerCli.mjs). * * @param {{ id: string }} project * @param {string} reel * @param {string} take * @param {{ umtoolDir: string, finale?: number | null, out?: string | null, dryRun?: boolean }} o */ export function reelCutSteps(project, reel, take, { umtoolDir, finale = null, out = null, dryRun = false }) { // The cut's options (lane/ui-simplify, the reel panel's Options): --finale S (the master's last S seconds to close // on), --out NAME (a NAME only -- never a path from a page), --dry-run (the mapping, nothing written). const extra = [ ...(Number.isFinite(finale) && finale > 0 ? ["--finale", String(finale)] : []), ...(typeof out === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(out) ? ["--out", out] : []), ...(dryRun ? ["--dry-run"] : []), ]; return { kind: `trailer ${project.id} ${reel} (${take})${dryRun ? " (dry run)" : ""}`, steps: [{ label: `cut the reel ${reel} from take ${take}'s master${dryRun ? " (dry run)" : ""}`, argv: ["node", path.join(/* turbopackIgnore: true */ umtoolDir, "bin", "umtool.mjs"), "trailer", project.id, "--reel", reel, "--take", take, ...extra], cwd: umtoolDir, env: {}, timeoutMs: REEL_CUT_TIMEOUT_MS, }], }; }