Archilyzer · Source

archilyzer

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

commit 69999996d2e4e527e61e751cd24e0dc595d6a88f
parent 77882121b8ea9f1283c987d15c3188bbce00d51e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 15:32:37 -0500

umtool: beat reels -- more than one reel per project (promo/<name>-beats.json, the trailer's file unchanged), each with its own limit, crossfade, intro, title and take; a beat's walk verdict; every write an undo point; a reel mapped onto a take's master by the trailer's own planTrailer; `umtool trailer --reel` and `trailer-beats --reel | reels | new-reel | undo | verdict | title | take`; a note anchored to a reel's beat

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

Diffstat:
Mumtool/bin/umtool.mjs | 12+++++++++---
Mumtool/lib/annotations/cli.test.mjs | 13+++++++++++++
Mumtool/lib/annotations/digest.mjs | 14++++++++++++++
Mumtool/lib/annotations/shape.mjs | 33++++++++++++++++++++++++++++++++-
Mumtool/lib/annotations/store.test.mjs | 9+++++++++
Mumtool/lib/annotations/types.ts | 4+++-
Mumtool/lib/decisions.ts | 8++++++--
Mumtool/lib/hrefs.ts | 20+++++++++++++++++---
Mumtool/lib/pieces/tabs.mjs | 2+-
Aumtool/lib/report/reelPlay.mjs | 344+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelPlay.test.mjs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerBeats.mjs | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mumtool/lib/report/trailerBeats.test.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerBeatsCli.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/lib/report/trailerCli.mjs | 58+++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/lib/report/trailerCli.test.mjs | 31+++++++++++++++++++++++++++++++
16 files changed, 1033 insertions(+), 81 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -80,9 +80,11 @@ // umtool render-mode on [--for 90m] [--print-token] -- <cmd …> held while <cmd> runs (its env carries the token) // umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] // [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master -// umtool trailer-beats <project> [ls | add <clip> [<from>-<to>] | set <n> <from>-<to> | remove <n> | move <n> --to <m> -// | order | limit <s|m:ss|x> | xfade <s> | intro on|off | candidates [--add]] the trailer's beats -// (promo/trailer-beats.json): running length against the limit, beats outside their clip +// | --reel <name> [--take <t>] a beat reel (promo/<name>-beats.json) -> <slug>.<name>.mp4 +// umtool trailer-beats <project> [--reel R] [ls | add <clip> [<from>-<to>] | set <n> <from>-<to> | remove <n> | move <n> --to <m> +// | order | limit <s|m:ss|x> | xfade <s> | intro on|off | candidates [--add] | verdict <n> confirmed|note|clear +// | title T | take T | undo | reels | new-reel <name> [--from R]] a reel's beats (the trailer: +// promo/trailer-beats.json): running length against the limit, beats outside their clip // umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence, // each edge into its pause: before -> after for review; --apply writes the named rows // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] @@ -959,10 +961,14 @@ function usage() { " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]", " a trailer cut from the take's finished master: the master's own frames, so the deck shows the", " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)", + " --reel <name> [--take <t>]: a beat reel's beats and settings (promo/<name>-beats.json),", + " written to takes/<t>/out/<slug>.<name>.mp4; no --take: its pinned, last-cut or latest master", " umtool trailer-beats <project> [ls] | add <clip> [<from>-<to>] [--at N] [--label L] | add-raw <at> <dur> | set <n> <from>-<to>", " | remove <n> | move <n> --to <m> | order | limit <s|m:ss|x|instagram|shorts|tiktok> | xfade <s> | intro on|off", " | candidates [--add] the trailer's beats (promo/trailer-beats.json, the Trailer page's file): each", " beat's length, the running length against the platform limit (X 2:20), beats outside their clip", + " | verdict <n> confirmed|note|clear | title T | take T | undo | reels | new-reel <name> [--from R]", + " --reel <name>: that beat reel (promo/<name>-beats.json); every write is an undo point", " umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence (its", " cut's, else the whole ones in its window), each edge into its pause; before -> after; --apply writes", " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>", diff --git a/umtool/lib/annotations/cli.test.mjs b/umtool/lib/annotations/cli.test.mjs @@ -130,3 +130,16 @@ test("a note taken in the Play view: the CLI prints its cut second, its clip and assert.match(d.text, /video\.manifest\.json` is regenerated by/); await rm(root, { recursive: true }); }); + +test("a note on a beat reel's beat: the CLI names the reel's file, the beat, the take's master second and the writer that acts on it", async () => { + const { root, reports, opts } = await fixture(); + const t = await projectTarget("ws/polemic-x", opts); + await writeNote(t, { op: "add", text: "End it on the word.", anchor: { kind: "reel", reel: "teaser", beat: 2, t: 9.5, masterT: 64.25, entry: "e1", sourceT: 12.4, take: "draft-6", ask: "trim" } }, { by: "operator" }); + const d = await run(["ws/polemic-x"], opts); + assert.equal(d.code, 0, d.text); + assert.match(d.text, /\*\*On:\*\* beat 2 of the reel `teaser` \(`promo\/teaser-beats\.json`\), 0:09\.5 into the reel as its Play view plays it from take `draft-6`'s master \(master 1:04\.3\)/); + assert.match(d.text, /\*\*Asks for:\*\* a trim/); + assert.match(d.text, /clip `e1`, at source 12\.4 s\n> /); + assert.match(d.text, /umtool trailer-beats <project> --reel teaser set 2 <from>-<to>/); + await rm(root, { recursive: true }); +}); diff --git a/umtool/lib/annotations/digest.mjs b/umtool/lib/annotations/digest.mjs @@ -175,6 +175,20 @@ function anchorLines(a, ctx) { } return lines; } + case "reel": { + const file = a.reel === "trailer" ? "promo/trailer-beats.json" : `promo/${a.reel}-beats.json`; + const lines = [ + `**On:** beat ${a.beat} of the reel \`${a.reel}\` (\`${file}\`), ${cutClock(a.t)} into the reel as its Play view plays it${a.take ? ` from take \`${a.take}\`'s master${a.masterT !== undefined ? ` (master ${cutClock(a.masterT)})` : ""}` : ""}`, + ]; + if (a.ask) lines.push(`**Asks for:** ${ASK_WORDS[a.ask] ?? a.ask}`); + if (a.entry) { + const e = (manifest?.timeline ?? []).find((x) => x.id === a.entry); + lines.push(`clip \`${a.entry}\`${e?.quote ? "" : " (not in the project's manifest)"}${a.sourceT !== undefined ? `, at source ${a.sourceT} s` : ""}`); + if (e?.quote) lines.push(quoteLine(e.quote)); + } + lines.push(`edit the reel through its writer: \`umtool trailer-beats <project> --reel ${a.reel} set ${a.beat} <from>-<to>\` (or its walk), never the file by hand; \`umtool trailer <project> --reel ${a.reel}\` cuts it`); + return lines; + } case "edit": return [ `**On:** an edit made in umtool to a GENERATED manifest — port it into the generator's inputs`, diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs @@ -15,13 +15,14 @@ export const NOTES_VERSION = 1; export const NOTE_TEXT_LIMIT = 8000; export const NOTE_STATUSES = ["open", "resolved", "wontfix"]; export const NOTE_AUTHORS = ["operator", "agent"]; -export const ANCHOR_KINDS = ["text", "cite", "section", "whole", "moment", "entry", "take", "edit", "cut"]; +export const ANCHOR_KINDS = ["text", "cite", "section", "whole", "moment", "entry", "take", "edit", "cut", "reel"]; export const REPORT_BLOCKS = ["title", "subtitle", "summary", "method"]; /** What a note taken in the Play view asks for (a `cut` anchor's `ask`): the dailies' kinds. */ export const CUT_ASKS = ["trim", "cut", "move", "fact", "look", "other"]; const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; +const REEL_ID = /^[a-z0-9][a-z0-9-]{0,39}$/; const NOTE_ID = /^n_[a-z0-9]{4,32}$/; const isStr = (v) => typeof v === "string"; const short = (v, max) => isStr(v) && v.length <= max; @@ -133,6 +134,36 @@ export function validateAnchor(raw) { } return { anchor: out }; } + case "reel": { + // A beat of a BEAT REEL as its Play view or walk plays it (lane/beat-reels): + // the reel, the beat's number then, the reel second, the master second of + // the take that played, the clip and its source second, and the ask. + if (!isStr(a.reel) || !REEL_ID.test(a.reel)) return { error: "reel anchor needs a reel name" }; + const beat = Number(a.beat); + if (!Number.isInteger(beat) || beat < 1) return { error: "reel anchor needs a beat number (from 1)" }; + const t = Number(a.t); + if (!Number.isFinite(t) || t < 0) return { error: "reel anchor needs t ≥ 0" }; + const out = { kind: "reel", reel: a.reel, beat, t: Number(t.toFixed(2)) }; + for (const k of ["masterT", "sourceT"]) { + if (a[k] === undefined) continue; + const v = Number(a[k]); + if (!Number.isFinite(v) || v < 0) return { error: `reel ${k} is not a second ≥ 0` }; + out[k] = Number(v.toFixed(2)); + } + if (a.entry !== undefined) { + if (!short(a.entry, 128) || !ID.test(a.entry)) return { error: "reel entry is not an entry id" }; + out.entry = a.entry; + } + if (a.take !== undefined) { + if (!isStr(a.take) || !TAKE_ID.test(a.take)) return { error: "reel take is not a take id" }; + out.take = a.take; + } + if (a.ask !== undefined) { + if (!CUT_ASKS.includes(/** @type {string} */ (a.ask))) return { error: `reel ask is one of ${CUT_ASKS.join(", ")}` }; + out.ask = a.ask; + } + return { anchor: out }; + } case "edit": { if (!short(a.field, 128) || !a.field) return { error: "edit anchor needs a field" }; if (a.entry !== undefined && (!short(a.entry, 128) || !ID.test(a.entry))) return { error: "edit entry is not an entry id" }; diff --git a/umtool/lib/annotations/store.test.mjs b/umtool/lib/annotations/store.test.mjs @@ -154,6 +154,15 @@ test("the cut anchor (the Play view): the cut second, the clip and its source se } }); +test("the reel anchor (a beat reel's Play and walk): the reel, the beat, the reel second, the master and source seconds, the take", () => { + assert.deepEqual(validateAnchor({ kind: "reel", reel: "teaser", beat: 3, t: 12.345, masterT: 101.111, entry: "kr1", sourceT: 4815.556, take: "draft-6", ask: "trim", bogus: 1 }).anchor, { + kind: "reel", reel: "teaser", beat: 3, t: 12.35, masterT: 101.11, sourceT: 4815.56, entry: "kr1", take: "draft-6", ask: "trim", + }); + for (const a of [{ kind: "reel", beat: 1, t: 0 }, { kind: "reel", reel: "Bad", beat: 1, t: 0 }, { kind: "reel", reel: "x", beat: 0, t: 0 }, { kind: "reel", reel: "x", beat: 1, t: -1 }, { kind: "reel", reel: "x", beat: 1, t: 0, masterT: -1 }]) { + assert.ok("error" in validateAnchor(a), JSON.stringify(a)); + } +}); + async function sitesFixture() { const root = await tmp(); const sites = path.join(root, "sites"); diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts @@ -43,7 +43,9 @@ export type Anchor = | { kind: "take"; take: string } | { kind: "edit"; entry?: string; field: string; from: unknown; to: unknown } /** A moment of the cut as the Play view plays it: the cut second, the clip and its source second, the take. */ - | { kind: "cut"; t: number; entry?: string; sourceT?: number; take?: string; ask?: CutAsk }; + | { kind: "cut"; t: number; entry?: string; sourceT?: number; take?: string; ask?: CutAsk } + /** A beat of a beat reel as its Play view or walk plays it: the reel, the beat (from 1), the reel second, the take's master second, the clip and its source second. */ + | { kind: "reel"; reel: string; beat: number; t: number; masterT?: number; entry?: string; sourceT?: number; take?: string; ask?: CutAsk }; /** What a Play-view note asks for (shape.mjs CUT_ASKS). */ export type CutAsk = "trim" | "cut" | "move" | "fact" | "look" | "other"; diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -1,5 +1,5 @@ import { readSong, resolveRendition, songProjectId, thumbAliasesFor } from "./browse"; -import { cutHref as cutPageHref, playHref, projectHref } from "./hrefs"; +import { cutHref as cutPageHref, playHref, projectHref, reelPlayHref } from "./hrefs"; import { cachedLoudness } from "./loudness"; import { DEFAULT_TARGET, loudnessVerdict } from "./loudness-types"; import { buildStatus, readManifest } from "./manifest"; @@ -376,6 +376,8 @@ function anchorLabel(a: { kind: string; [k: string]: unknown }): string { return `edit ${a.field}${a.entry ? ` on ${a.entry}` : ""}`; case "cut": return `${a.take ? `take ${a.take} ` : "cut "}@ ${Number(a.t).toFixed(1)}s${a.entry ? ` (${a.entry})` : ""}`; + case "reel": + return `reel ${a.reel} beat ${a.beat}${a.entry ? ` (${a.entry})` : ""}`; default: return "whole"; } @@ -415,7 +417,9 @@ export async function noteDecisions(): Promise<Decision[]> { href: !article && n.anchor.kind === "cut" ? playHref(f.id, { take: (n.anchor as { take?: string }).take ?? null, note: n.id }) - : `${page}?note=${encodeURIComponent(n.id)}`, + : !article && n.anchor.kind === "reel" + ? reelPlayHref(f.id, { reel: n.anchor.reel, take: n.anchor.take ?? null, note: n.id }) + : `${page}?note=${encodeURIComponent(n.id)}`, severity: "open", at: Number.isFinite(at) ? at : 0, }); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -292,9 +292,23 @@ export function claimBenchHref(project: string, claim: string, q: NoteOpt = {}): } /** Alternative renders of one part of a cut. */ -/** The trailer's beats (promo/trailer-beats.json). */ -export function trailerHref(project: string): string { - return `/projects/${encodePath(project)}/trailer`; +/** The trailer's beats (promo/trailer-beats.json), or another beat reel's (`?reel=<name>`: promo/<name>-beats.json). */ +export function trailerHref(project: string, q: { reel?: string | null } = {}): string { + return withQuery(`/projects/${encodePath(project)}/trailer`, { reel: q.reel && q.reel !== "trailer" ? q.reel : null }); +} + +/** A beat reel's Play view: its beats played from a take's rendered master (`take`, else the reel's own choice), from beat `beat`. */ +export function reelPlayHref(project: string, q: NoteOpt & { reel?: string | null; take?: string | null; beat?: number | null } = {}): string { + return withQuery( + `/projects/${encodePath(project)}/trailer/play`, + { reel: q.reel && q.reel !== "trailer" ? q.reel : null, take: q.take, beat: q.beat != null && q.beat > 1 ? q.beat : null }, + q.note, + ); +} + +/** A beat reel's walk: the bench over beat `beat` (from 1) on the take's master. */ +export function reelWalkHref(project: string, q: { reel?: string | null; take?: string | null; beat?: number | null } = {}): string { + return withQuery(`/projects/${encodePath(project)}/trailer/walk`, { reel: q.reel && q.reel !== "trailer" ? q.reel : null, take: q.take, beat: q.beat ?? 1 }); } export function takesHref(project: string, q: NoteOpt = {}): string { diff --git a/umtool/lib/pieces/tabs.mjs b/umtool/lib/pieces/tabs.mjs @@ -172,7 +172,7 @@ export function tabOfSection(name) { /** Where a note's anchor is drawn: a row's on the Cut, a timed note on the final video on Build. */ export function tabOfNoteAnchor(kind) { // A Play-view note (`cut`) is reached from the Cut tab's Play the cut; its own link opens the Play view. - if (kind === "entry" || kind === "edit" || kind === "cut") return "cut"; + if (kind === "entry" || kind === "edit" || kind === "cut" || kind === "reel") return "cut"; if (kind === "moment") return "build"; return "overview"; } diff --git a/umtool/lib/report/reelPlay.mjs b/umtool/lib/report/reelPlay.mjs @@ -0,0 +1,344 @@ +// 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/<name>-beats.json, trailerBeats.mjs) are spans of a take's FINISHED +// MASTER (`takes/<t>/out/<slug>.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 { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; +import { listTakes, takesDirOf } from "./takes.mjs"; +import { DEFAULT_REEL, TRAILER_LIMIT_DEFAULT, readTrailerBeats, reelFileOf } 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 `<slug>.<reel>.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 (`<slug>.<reel>.mp4`, the + * trailer reel `<slug>.trailer.mp4`) and the record beside it. Newest first. + * + * @param {Awaited<ReturnType<typeof takeMasters>>} masters + * @param {string} reel + */ +export async function reelCuts(masters, reel = DEFAULT_REEL) { + 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 before the master there now was written: the take was rendered again since. + stale: t.masterMtimeMs !== null && st.mtimeMs < t.masterMtimeMs, + }); + } + 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<string, any>, 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 } : { 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 } : 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); + 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 ?? "<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 }); + return { + ...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 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 <p> --reel <r> --take + * <t>` -- 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 }} o + */ +export function reelCutSteps(project, reel, take, { umtoolDir }) { + return { + kind: `trailer ${project.id} ${reel} (${take})`, + steps: [{ + label: `cut the reel ${reel} from take ${take}'s master`, + argv: ["node", path.join(/* turbopackIgnore: true */ umtoolDir, "bin", "umtool.mjs"), "trailer", project.id, "--reel", reel, "--take", take], + cwd: umtoolDir, + env: {}, + timeoutMs: REEL_CUT_TIMEOUT_MS, + }], + }; +} diff --git a/umtool/lib/report/reelPlay.test.mjs b/umtool/lib/report/reelPlay.test.mjs @@ -0,0 +1,142 @@ +// Beat reels played from a take's master (reelPlay.mjs): each beat mapped by +// the trailer's own planTrailer, the beats a take cannot place said by number, +// the take a reel plays chosen, the reel's cuts found. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { pickReelTake, reelCutSteps, reelPlan, reelPlayView, takeMasters } from "./reelPlay.mjs"; + +// The trailer test's master: the brand intro, then three clips, 0.5 s dissolves. +const SCHEDULE = { + version: 1, kind: "deck", fps: 30, transition: 0.5, total: 40.167, + segments: [ + { id: "brand-intro", type: "intro", start: 0, duration: 4.167, end: 4.167 }, + { id: "c1", type: "clip", start: 3.667, duration: 12, end: 15.667 }, + { id: "c2", type: "clip", start: 15.167, duration: 10, end: 25.167 }, + { id: "c3", type: "clip", start: 24.667, duration: 15.5, end: 40.167 }, + ], +}; +const RECORDS = new Map([ + ["c1", { id: "c1", start: 100.2, end: 112.2 }], + ["c2", { id: "c2", start: 500, end: 510, gaps: [{ from: 503, to: 505 }] }], + ["c3", { id: "c3", start: 2000, end: 2015.5 }], +]); +const MANIFEST = { slug: "cut", render: { fps: 30 }, timeline: [{ type: "clip", id: "c1", quote: "the first" }, { type: "clip", id: "c2", quote: "the second" }, { type: "clip", id: "c3" }] }; +const build = { schedule: SCHEDULE, records: RECORDS, manifest: MANIFEST }; +const close = (a, b, eps = 1 / 60) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b}`); + +test("each beat is the trailer's piece: its master span, where it lands in the reel, its asked edges and handle limits on the master", () => { + const p = reelPlan(build, [{ id: "c1", start: 104.2, end: 108.2 }, { id: "c3", start: 2002, end: 2006, verdict: "confirmed" }], { xfade: 0.3 }); + assert.equal(p.rows.length, 2); + const [a, b] = p.rows; + close(a.piece.master.start, 7.667); + assert.equal(a.piece.at, 0); + close(b.piece.at, 4 - 0.3); + assert.equal(b.verdict, "confirmed"); + assert.equal(a.quote, "the first"); + close(a.asked.start, 7.667); + close(a.asked.end, 11.667); + // A handle stays inside the source the segment was cut from. + close(a.limits.start, 3.667); + close(a.limits.end, 15.667); + assert.deepEqual(a.limits.source, { start: 100.2, end: 112.2 }); + close(p.total, 7.7); +}); + +test("a beat across a clip's gap maps through the record's gaps (the master's jump cut)", () => { + const p = reelPlan(build, [{ id: "c2", start: 501, end: 507 }], { xfade: 0 }); + const [r] = p.rows; + // 501 → 15.167 + 1; 507 → 15.167 + (7 − 2) = 20.167 + close(r.asked.start, 16.167); + close(r.asked.end, 20.167); + close(r.piece.master.duration, 4); + assert.deepEqual(r.map.gaps, [{ from: 503, to: 505 }]); + assert.match(p.planNotes.join("\n"), /spans a gap/); +}); + +test("a beat the take cannot place is said by its number; the others still play; a missing intro is played without", () => { + const p = reelPlan(build, [{ id: "c1", start: 104, end: 106 }, { id: "gone", start: 1, end: 2 }, { id: "c3", start: 1990, end: 2003 }, { at: 30, dur: 2 }], { intro: true }); + assert.deepEqual(p.rows.map((r) => !!r.piece), [true, false, false, true]); + assert.match(p.rows[1].problem, /^beat 2: no clip "gone"/); + assert.match(p.rows[2].problem, /^beat 3: c3 1990–2003 is outside/); + assert.ok(p.intro); + close(p.rows[0].piece.at, p.intro.master.duration - p.xfade); + const noIntro = reelPlan({ ...build, schedule: { ...SCHEDULE, segments: SCHEDULE.segments.slice(1) } }, [{ id: "c1", start: 104, end: 106 }], { intro: true }); + assert.equal(noIntro.intro, null); + assert.match(noIntro.planNotes[0], /played without the intro/); +}); + +test("the take a reel plays: asked, else pinned, else the last cut's, else the latest master; never one rendering now", () => { + const masters = [ + { id: "d3", built: true, rendering: true }, + { id: "d2", built: true, rendering: false }, + { id: "d1", built: true, rendering: false }, + { id: "d0", built: false, rendering: false }, + ]; + assert.deepEqual(pickReelTake({ asked: "d0", masters }), { id: "d0", why: "asked" }); + assert.deepEqual(pickReelTake({ pinned: "d1", masters }), { id: "d1", why: "pinned" }); + assert.deepEqual(pickReelTake({ pinned: "d0", cuts: [{ take: "d3" }, { take: "d1" }], masters }), { id: "d1", why: "last cut" }); + assert.deepEqual(pickReelTake({ masters }), { id: "d2", why: "latest master" }); + assert.equal(pickReelTake({ masters: [{ id: "x", built: false, rendering: false }] }), null); +}); + +test("Cut the trailer is `umtool trailer <p> --reel <r> --take <t>` on the runner", () => { + const plan = reelCutSteps({ id: "f/kirsche" }, "teaser", "draft-6", { umtoolDir: "/u" }); + assert.equal(plan.kind, "trailer f/kirsche teaser (draft-6)"); + assert.deepEqual(plan.steps[0].argv, ["node", "/u/bin/umtool.mjs", "trailer", "f/kirsche", "--reel", "teaser", "--take", "draft-6"]); +}); + +async function fixture() { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-reelplay-")); + const mk = async (id, order, { built = true } = {}) => { + const t = path.join(dir, "takes", id); + await mkdir(path.join(t, "out", "sourced", "segments"), { recursive: true }); + await writeFile(path.join(t, "take.json"), JSON.stringify({ id, group: "takes", order, label: `take ${id}`, kind: "reference", preview: "preview.mp4" })); + await writeFile(path.join(t, "video.manifest.json"), JSON.stringify(MANIFEST)); + if (!built) return t; + await writeFile(path.join(t, "out", "cut.mp4"), "master"); + await writeFile(path.join(t, "out", "sourced", "schedule.json"), JSON.stringify(SCHEDULE)); + for (const [k, rec] of RECORDS) await writeFile(path.join(t, "out", "sourced", "segments", `${k}.cut.json`), JSON.stringify(rec)); + return t; + }; + return { dir, mk }; +} + +test("the view: no master is said (nothing rendered); with masters, the chosen take's spans, the reel's cuts by take", async () => { + const { dir, mk } = await fixture(); + try { + await mk("draft-1", 1, { built: false }); + let v = await reelPlayView({ id: "p", dir }); + assert.equal(v.take, null); + assert.match(v.noMaster.why, /no take has a finished master yet/); + const d2 = await mk("draft-2", 2); + const d3 = await mk("draft-3", 3); + // draft-2's master is older; draft-3 the latest. + await utimes(path.join(d2, "out", "cut.mp4"), new Date(2026, 0, 1), new Date(2026, 0, 1)); + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "promo", "teaser-beats.json"), JSON.stringify({ title: "T", beats: [{ id: "c1", start: 104, end: 106 }] })); + v = await reelPlayView({ id: "p", dir }, { reel: "teaser" }); + assert.deepEqual(v.take && [v.take.id, v.take.why], ["draft-3", "latest master"]); + assert.equal(v.rows.length, 1); + assert.equal(v.title, "T"); + // A cut of the reel in draft-2 makes it the reel's take. + await writeFile(path.join(d2, "out", "cut.teaser.mp4"), "cut"); + await writeFile(path.join(d2, "out", "cut.teaser.trailer.json"), JSON.stringify({ builtAt: "2026-11-02T10:00:00.000Z", seconds: 2 })); + v = await reelPlayView({ id: "p", dir }, { reel: "teaser" }); + assert.deepEqual([v.take.id, v.take.why], ["draft-2", "last cut"]); + assert.deepEqual(v.cuts.map((c) => [c.take, path.basename(c.out), c.seconds]), [["draft-2", "cut.teaser.mp4", 2]]); + // The trailer reel's cut is <slug>.trailer.mp4, and it is not the teaser's. + await writeFile(path.join(d3, "out", "cut.trailer.mp4"), "cut"); + v = await reelPlayView({ id: "p", dir }, { reel: "teaser", take: "draft-3" }); + assert.deepEqual([v.take.id, v.take.why], ["draft-3", "asked"]); + assert.equal(v.cuts.length, 1); + assert.equal((await takeMasters(dir)).map((m) => m.id).join(","), "draft-3,draft-2,draft-1"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -20,8 +20,20 @@ // intro, beats }` -- parseBeats reads `{ beats }` too. Its indent is kept. A // file that does not parse is never written over. The token is its mtime. // +// BEAT REELS (2 Nov, lane/beat-reels): a project has more than one reel -- +// the X trailer, a teaser, a "Kirsche-first" cut -- each its own file, +// `promo/<name>-beats.json` (the reel `trailer` is today's +// promo/trailer-beats.json, its path unchanged), with its own limit, +// crossfade, intro, title and the take it is cut from. Every function here +// takes `{ reel }` (default `trailer`), so a caller that never names one +// reads and writes exactly the file it always did. A beat may carry the +// walk's `verdict` ("confirmed", or "note": a note was left on it), and every +// write leaves an UNDO POINT: the file as it was, kept in +// `promo/.<file>.undo.json` (newest last, REEL_UNDO_KEEP of them), which +// `undoTrailerBeats` puts back. +// // Plain ESM: the CLI runs it under bare node. -import { copyFile, mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { gappedLength, gapsOf } from "umtool-report-to-video/gaps"; import { TRAILER_XFADE_DEFAULT, TrailerError, parseBeats } from "umtool-report-to-video/trailer"; @@ -30,6 +42,25 @@ import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; export const TRAILER_BEATS_FILE = path.join("promo", "trailer-beats.json"); +/** The reel a caller that names none reads and writes: promo/trailer-beats.json. */ +export const DEFAULT_REEL = "trailer"; +/** A reel's name: lower case, digits and dashes (it is in a file name and an output name). */ +export const REEL_ID = /^[a-z0-9][a-z0-9-]{0,39}$/; +export const isReelId = (v) => typeof v === "string" && REEL_ID.test(v); +/** How many undo points a reel keeps. */ +export const REEL_UNDO_KEEP = 40; +/** What a beat's walk may say of it. */ +export const BEAT_VERDICTS = Object.freeze(["confirmed", "note"]); + +/** A reel's beats file, relative to the project: `promo/<name>-beats.json`. */ +export function reelFileOf(reel = DEFAULT_REEL) { + const name = reel ?? DEFAULT_REEL; + if (!isReelId(name)) throw new Error(`"${name}" is not a reel name (lower case, digits and dashes)`); + return path.join("promo", `${name}-beats.json`); +} + +/** The file a reel's cut is written to in its take's out/: `<slug>.<reel>.mp4` (the trailer reel: `<slug>.trailer.mp4`, as ever). */ +export const reelOutName = (slug, reel = DEFAULT_REEL) => `${slug}.${reel ?? DEFAULT_REEL}.mp4`; /** X's video limit is 2:20; a trailer must be UNDER it. */ export const TRAILER_LIMIT_DEFAULT = 140; /** Platform limits a person picks from (seconds). */ @@ -53,28 +84,59 @@ export class BeatsStale extends Error { } } -const beatsFile = (dir) => path.join(dir, TRAILER_BEATS_FILE); +const beatsFile = (dir, reel = DEFAULT_REEL) => path.join(dir, reelFileOf(reel)); +const undoFileOf = (dir, reel = DEFAULT_REEL) => { + const rel = reelFileOf(reel); + return path.join(dir, path.dirname(rel), `.${path.basename(rel)}.undo.json`); +}; -/** @typedef {{ limit?: number, xfade?: number, intro?: boolean }} TrailerSettings */ -/** @typedef {{ token?: string | null }} BeatsWriteOpts */ +/** @typedef {{ limit?: number, xfade?: number, intro?: boolean, title?: string, take?: string }} TrailerSettings */ +/** @typedef {{ token?: string | null, reel?: string }} BeatsWriteOpts */ /** The file's mtime, the token a writer hands back; null when there is no file. */ -export async function beatsToken(dir) { - const st = await stat(beatsFile(dir)).catch(() => null); +export async function beatsToken(dir, reel = DEFAULT_REEL) { + const st = await stat(beatsFile(dir, reel)).catch(() => null); return st ? String(Math.round(st.mtimeMs)) : null; } /** + * The project's reels: `trailer` always (its file may not exist yet), then + * every other `promo/<name>-beats.json`, by name. Each with its beat count, + * title and limit when its file reads. + * + * @param {string} dir + */ +export async function listReels(dir) { + const names = await readdir(path.join(dir, "promo")).catch(() => []); + const found = new Set([DEFAULT_REEL]); + for (const n of names) { + const m = /^([a-z0-9][a-z0-9-]{0,39})-beats\.json$/.exec(n); + if (m) found.add(m[1]); + } + const out = []; + for (const name of [DEFAULT_REEL, ...[...found].filter((n) => n !== DEFAULT_REEL).sort()]) { + try { + const r = await readTrailerBeats(dir, { reel: name }); + out.push({ name, file: reelFileOf(name), exists: r.exists, beats: r.beats.length, title: r.settings.title ?? null, limit: r.settings.limit ?? TRAILER_LIMIT_DEFAULT, take: r.settings.take ?? null, error: null }); + } catch (e) { + out.push({ name, file: reelFileOf(name), exists: true, beats: 0, title: null, limit: TRAILER_LIMIT_DEFAULT, take: null, error: e instanceof Error ? e.message : String(e) }); + } + } + return out; +} + +/** * The beats file, read: `{ exists, shape, beats, settings, indent }`. Missing: * an empty array. Not JSON, or neither an array nor `{ beats }`: an error, * so nothing writes over it. * * @param {string} dir */ -export async function readTrailerBeats(dir) { +export async function readTrailerBeats(dir, { reel = DEFAULT_REEL } = {}) { + const rel = reelFileOf(reel); let text; try { - text = await readFile(beatsFile(dir), "utf8"); + text = await readFile(beatsFile(dir, reel), "utf8"); } catch { return { exists: false, shape: /** @type {"array" | "object"} */ ("array"), beats: /** @type {any[]} */ ([]), settings: /** @type {TrailerSettings} */ ({}), indent: 1, token: /** @type {string | null} */ (null), doc: null }; } @@ -82,18 +144,41 @@ export async function readTrailerBeats(dir) { try { doc = JSON.parse(text); } catch (e) { - throw new Error(`${TRAILER_BEATS_FILE} does not parse; not reading or writing it (${e instanceof Error ? e.message : e})`); + throw new Error(`${rel} does not parse; not reading or writing it (${e instanceof Error ? e.message : e})`); } const beats = Array.isArray(doc) ? doc : Array.isArray(doc?.beats) ? doc.beats : null; - if (!beats) throw new Error(`${TRAILER_BEATS_FILE} is neither a list of beats nor { "beats": [...] }`); + if (!beats) throw new Error(`${rel} is neither a list of beats nor { "beats": [...] }`); /** @type {TrailerSettings} */ const settings = {}; if (isObj(doc)) { if (typeof doc.limit === "number") settings.limit = doc.limit; if (typeof doc.xfade === "number") settings.xfade = doc.xfade; if (typeof doc.intro === "boolean") settings.intro = doc.intro; + if (typeof doc.title === "string" && doc.title.trim()) settings.title = doc.title; + if (typeof doc.take === "string" && TAKE_ID.test(doc.take)) settings.take = doc.take; + } + return { exists: true, shape: /** @type {"array" | "object"} */ (Array.isArray(doc) ? "array" : "object"), beats, settings, indent: indentOf(text), token: await beatsToken(dir, reel), doc, text }; +} + +const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; +const SETTING_KEYS = ["limit", "xfade", "intro", "title", "take"]; + +/** The reel's undo points, oldest first: `{ at, what, text }` (`text` null: the file did not exist). */ +export async function readReelUndo(dir, { reel = DEFAULT_REEL } = {}) { + try { + const j = JSON.parse(await readFile(undoFileOf(dir, reel), "utf8")); + return Array.isArray(j?.points) ? j.points.filter((p) => p && typeof p.what === "string" && (typeof p.text === "string" || p.text === null)) : []; + } catch { + return []; } - return { exists: true, shape: /** @type {"array" | "object"} */ (Array.isArray(doc) ? "array" : "object"), beats, settings, indent: indentOf(text), token: await beatsToken(dir), doc }; +} + +async function writeUndo(dir, reel, points) { + const file = undoFileOf(dir, reel); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify({ reel, file: reelFileOf(reel), points: points.slice(-REEL_UNDO_KEEP) }, null, 1) + "\n", "utf8"); + await rename(tmp, file); } /** @type {Promise<unknown>} */ @@ -109,11 +194,11 @@ function withBeatsLock(fn) { * settings)` (which throws to refuse), every beat checked by the trailer's own * parseBeats, a `.bak` of the file as it was, then tmp + rename. */ -async function beatsWrite(dir, token, mutate) { +async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an edit" } = {}) { return withBeatsLock(async () => { - const current = await beatsToken(dir); + const current = await beatsToken(dir, reel); if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); - const read = await readTrailerBeats(dir); + const read = await readTrailerBeats(dir, { reel }); const beats = JSON.parse(JSON.stringify(read.beats)); const settings = { ...read.settings }; const result = mutate(beats, settings); @@ -126,23 +211,85 @@ async function beatsWrite(dir, token, mutate) { } const hasSettings = Object.keys(settings).length > 0; const out = read.shape === "array" && !hasSettings ? beats : { ...(isObj(read.doc) ? read.doc : {}), ...settings, beats }; - if (isObj(out)) for (const k of ["limit", "xfade", "intro"]) if (!(k in settings)) delete out[k]; - const file = beatsFile(dir); + if (isObj(out)) for (const k of SETTING_KEYS) if (!(k in settings)) delete out[k]; + const file = beatsFile(dir, reel); await mkdir(path.dirname(file), { recursive: true }); if (read.exists) await copyFile(file, `${file}.bak`).catch(() => {}); + // The undo point: the file as it was, before this write. + await writeUndo(dir, reel, [...(await readReelUndo(dir, { reel })), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }]); const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); await rename(tmp, file); - return { ...result, beats, settings, token: await beatsToken(dir) }; + return { ...result, beats, settings, token: await beatsToken(dir, reel) }; + }); +} + +/** + * Put the reel back as it was before its last write (that write's undo + * point, taken off the list). The token guards it like any write. + * @param {string} dir + * @param {BeatsWriteOpts} [opts] + * @returns {Promise<{ undone: string, at: string, left: number, token: string | null }>} + */ +export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL } = {}) { + return withBeatsLock(async () => { + const current = await beatsToken(dir, reel); + if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); + const points = await readReelUndo(dir, { reel }); + const last = points.pop(); + if (!last) throw new Error(`nothing to undo on the reel ${reel}`); + const file = beatsFile(dir, reel); + if (last.text === null) await rm(file, { force: true }); + else { + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, last.text, "utf8"); + await rename(tmp, file); + } + await writeUndo(dir, reel, points); + return { undone: last.what, at: last.at, left: points.length, token: await beatsToken(dir, reel) }; }); } +/** + * A new reel: `promo/<name>-beats.json`, empty or a copy of another reel's + * beats (`from`), with its own title. Refused when the reel exists. + * @param {string} dir + * @param {string} name + * @param {{ from?: string | null, title?: string | null }} [opts] + */ +export async function createReel(dir, name, { from = null, title = null } = {}) { + if (!isReelId(name)) throw new Error(`"${name}" is not a reel name (lower case, digits and dashes, up to 40)`); + if (await beatsToken(dir, name)) throw new Error(`the reel ${name} exists (${reelFileOf(name)})`); + let beats = []; + /** @type {TrailerSettings} */ + let settings = {}; + if (from) { + const src = await readTrailerBeats(dir, { reel: from }); + if (!src.exists) throw new Error(`no reel ${from} to copy (${reelFileOf(from)})`); + beats = JSON.parse(JSON.stringify(src.beats)).map((b) => { + const c = { ...b }; + delete c.verdict; + return c; + }); + settings = { ...src.settings }; + delete settings.title; + } + const t = typeof title === "string" ? title.trim().slice(0, 120) : ""; + return beatsWrite(dir, null, (list, s) => { + list.splice(0, list.length, ...beats); + Object.assign(s, settings, t ? { title: t } : {}); + return { reel: name, file: reelFileOf(name), copied: from ?? null }; + }, { reel: name, what: from ? `new reel ${name}, from ${from}` : `new reel ${name}` }); +} + /** A beat as a person writes it: `{ id, start, end, label? }` or `{ at, dur, label? }`, rounded to 2 dp. */ function cleanBeat(b) { if (!isObj(b)) throw new Error("a beat is { id, start, end } or { at, dur }"); const label = typeof b.label === "string" && b.label.trim() ? { label: b.label.trim().slice(0, 120) } : {}; - if (b.id !== undefined) return { id: String(b.id), start: r2(b.start), end: r2(b.end), ...label }; - return { at: r2(b.at), dur: r2(b.dur), ...label }; + if (b.verdict !== undefined && b.verdict !== null && !BEAT_VERDICTS.includes(b.verdict)) throw new Error(`a beat's verdict is one of ${BEAT_VERDICTS.join(", ")}`); + const verdict = BEAT_VERDICTS.includes(b.verdict) ? { verdict: b.verdict } : {}; + if (b.id !== undefined) return { id: String(b.id), start: r2(b.start), end: r2(b.end), ...label, ...verdict }; + return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict }; } const indexIn = (beats, i, what = "beat") => { @@ -155,9 +302,9 @@ const indexIn = (beats, i, what = "beat") => { * Add a beat at index `at` (default: where the cut's order puts it, else the end). * @param {string} dir * @param {Record<string, unknown>} beat - * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null }} [opts] + * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null, reel?: string }} [opts] */ -export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null } = {}) { +export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const b = cleanBeat(beat); let i = beats.length; @@ -175,7 +322,7 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif } beats.splice(i, 0, b); return { index: i, beat: b }; - }); + }, { reel, what: `add ${beat?.id ?? "a master beat"}` }); } /** @@ -185,19 +332,20 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif * @param {Record<string, unknown>} patch * @param {BeatsWriteOpts} [opts] */ -export async function updateTrailerBeat(dir, i, patch, { token = null } = {}) { +export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); - if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, label? }"); + if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, label?, verdict? }"); const b = { ...beats[n] }; for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k]; - if (patch.label !== undefined) { - if (patch.label === null || patch.label === "") delete b.label; - else b.label = patch.label; + for (const k of ["label", "verdict"]) { + if (patch[k] === undefined) continue; + if (patch[k] === null || patch[k] === "") delete b[k]; + else b[k] = patch[k]; } beats[n] = cleanBeat(b); return { index: n, beat: beats[n] }; - }); + }, { reel, what: `beat ${Number(i) + 1}: ${Object.keys(isObj(patch) ? patch : {}).join(", ") || "set"}` }); } /** @@ -206,12 +354,12 @@ export async function updateTrailerBeat(dir, i, patch, { token = null } = {}) { * @param {number} i * @param {BeatsWriteOpts} [opts] */ -export async function removeTrailerBeat(dir, i, { token = null } = {}) { +export async function removeTrailerBeat(dir, i, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); const [gone] = beats.splice(n, 1); return { index: n, removed: gone }; - }); + }, { reel, what: `remove beat ${Number(i) + 1}` }); } /** @@ -221,7 +369,7 @@ export async function removeTrailerBeat(dir, i, { token = null } = {}) { * @param {number} to * @param {BeatsWriteOpts} [opts] */ -export async function moveTrailerBeat(dir, i, to, { token = null } = {}) { +export async function moveTrailerBeat(dir, i, to, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); const t = Number(to); @@ -229,7 +377,7 @@ export async function moveTrailerBeat(dir, i, to, { token = null } = {}) { const [b] = beats.splice(n, 1); beats.splice(t, 0, b); return { from: n, to: t }; - }); + }, { reel, what: `move beat ${Number(i) + 1} to ${Number(to) + 1}` }); } /** @@ -241,7 +389,7 @@ export async function moveTrailerBeat(dir, i, to, { token = null } = {}) { * @param {Record<string, any>} manifest * @param {BeatsWriteOpts} [opts] */ -export async function orderTrailerBeats(dir, manifest, { token = null } = {}) { +export async function orderTrailerBeats(dir, manifest, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (beats) => { const order = cutOrder(manifest); const keyed = beats.map((b, k) => ({ b, k, key: b.id !== undefined ? order.get(b.id) ?? Infinity : null })); @@ -255,20 +403,21 @@ export async function orderTrailerBeats(dir, manifest, { token = null } = {}) { const moved = keyed.some((x, i) => x.k !== i); beats.splice(0, beats.length, ...keyed.map((x) => x.b)); return { moved }; - }); + }, { reel, what: "order by the cut" }); } /** * The trailer's settings: `limit` (seconds, the platform's), `xfade` (the - * trailer's crossfade), `intro` (opens on the brand intro). null removes one - * (its default again). + * trailer's crossfade), `intro` (opens on the brand intro), `title` (the + * reel's name for a person), `take` (the take it is cut from, pinned). null + * removes one (its default again). * @param {string} dir * @param {Record<string, unknown>} patch * @param {BeatsWriteOpts} [opts] */ -export async function setTrailerSettings(dir, patch, { token = null } = {}) { +export async function setTrailerSettings(dir, patch, { token = null, reel = DEFAULT_REEL } = {}) { return beatsWrite(dir, token, (_beats, settings) => { - if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro? }"); + if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro?, title?, take? }"); for (const k of ["limit", "xfade"]) { if (patch[k] === undefined) continue; if (patch[k] === null || patch[k] === "") { @@ -285,8 +434,18 @@ export async function setTrailerSettings(dir, patch, { token = null } = {}) { if (patch.intro === null) delete settings.intro; else settings.intro = patch.intro === true; } + if (patch.title !== undefined) { + const t = typeof patch.title === "string" ? patch.title.trim().slice(0, 120) : ""; + if (!t) delete settings.title; + else settings.title = t; + } + if (patch.take !== undefined) { + if (patch.take === null || patch.take === "") delete settings.take; + else if (typeof patch.take !== "string" || !TAKE_ID.test(patch.take)) throw new Error("take is a take id"); + else settings.take = patch.take; + } return {}; - }); + }, { reel, what: `settings: ${Object.keys(isObj(patch) ? patch : {}).join(", ")}` }); } /** Clip id → its place among the cut's clips. */ @@ -316,9 +475,9 @@ export function clockOf(s) { * * @param {Record<string, any>} manifest the project's manifest * @param {{ beats: any[], settings?: Record<string, any> }} doc readTrailerBeats's - * @param {{ introSeconds?: number | null }} [opts] the brand intro's length in a built take, when known + * @param {{ introSeconds?: number | null, reel?: string }} [opts] the brand intro's length in a built take, when known; the reel */ -export function trailerView(manifest, doc, { introSeconds = null } = {}) { +export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT_REEL } = {}) { const settings = doc.settings ?? {}; const limit = typeof settings.limit === "number" ? settings.limit : TRAILER_LIMIT_DEFAULT; const xfade = typeof settings.xfade === "number" ? settings.xfade : TRAILER_XFADE_DEFAULT; @@ -371,6 +530,7 @@ export function trailerView(manifest, doc, { introSeconds = null } = {}) { kind, ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end } : { at: raw?.at, dur: raw?.dur }), label: typeof raw?.label === "string" ? raw.label : null, + verdict: BEAT_VERDICTS.includes(raw?.verdict) ? raw.verdict : null, seconds: r2(seconds), running: r2(running), over: running > limit, @@ -380,7 +540,11 @@ export function trailerView(manifest, doc, { introSeconds = null } = {}) { }); const total = r2(sum - xfade * Math.max(0, pieces - 1)); return { - file: TRAILER_BEATS_FILE, + reel: reel ?? DEFAULT_REEL, + file: reelFileOf(reel), + title: typeof settings.title === "string" ? settings.title : null, + take: typeof settings.take === "string" ? settings.take : null, + confirmed: rows.filter((r) => r.verdict === "confirmed").length, limit, xfade, intro, diff --git a/umtool/lib/report/trailerBeats.test.mjs b/umtool/lib/report/trailerBeats.test.mjs @@ -140,3 +140,83 @@ test("the intro's length comes from the newest built take's schedule", async () await rm(dir, { recursive: true, force: true }); } }); + +// ---- beat reels (lane/beat-reels) ------------------------------------------- + +test("reels: the trailer is promo/trailer-beats.json, any other promo/<name>-beats.json; listed, made empty or as a copy", async () => { + const { DEFAULT_REEL, createReel, listReels, reelFileOf, reelOutName } = await import("./trailerBeats.mjs"); + assert.equal(reelFileOf(DEFAULT_REEL), TRAILER_BEATS_FILE); + assert.equal(reelFileOf("teaser"), path.join("promo", "teaser-beats.json")); + assert.throws(() => reelFileOf("Bad Name"), /not a reel name/); + assert.equal(reelOutName("kirsche", "trailer"), "kirsche.trailer.mp4"); + assert.equal(reelOutName("kirsche", "x-first"), "kirsche.x-first.mp4"); + const dir = await project([{ id: "a", start: 12, end: 18, verdict: "confirmed" }]); + try { + assert.deepEqual((await listReels(dir)).map((r) => [r.name, r.beats]), [["trailer", 1]]); + await createReel(dir, "teaser", { title: "The teaser" }); + await createReel(dir, "kf", { from: "trailer" }); + await assert.rejects(createReel(dir, "kf"), /exists/); + await assert.rejects(createReel(dir, "no", { from: "ghost" }), /no reel ghost/); + const reels = await listReels(dir); + assert.deepEqual(reels.map((r) => [r.name, r.beats, r.title]), [["trailer", 1, null], ["kf", 1, null], ["teaser", 0, "The teaser"]]); + // A copy drops the walk's verdicts: the new reel has not been walked. + assert.deepEqual((await readTrailerBeats(dir, { reel: "kf" })).beats, [{ id: "a", start: 12, end: 18 }]); + // Writes to one reel leave the others alone. + await addTrailerBeat(dir, { id: "c", start: 61, end: 64 }, { reel: "teaser" }); + assert.equal((await readTrailerBeats(dir)).beats.length, 1); + assert.equal((await readTrailerBeats(dir, { reel: "teaser" })).beats.length, 1); + const v = trailerView(manifest(), await readTrailerBeats(dir, { reel: "teaser" }), { reel: "teaser" }); + assert.equal(v.reel, "teaser"); + assert.equal(v.file, path.join("promo", "teaser-beats.json")); + assert.equal(v.title, "The teaser"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a beat's verdict (confirmed / note) is kept, cleared with null, refused when it is anything else; title and take are settings", async () => { + const dir = await project([{ id: "a", start: 12, end: 18 }]); + try { + await updateTrailerBeat(dir, 0, { verdict: "confirmed", start: 12.5 }); + assert.deepEqual((await readTrailerBeats(dir)).beats[0], { id: "a", start: 12.5, end: 18, verdict: "confirmed" }); + assert.equal(trailerView(manifest(), await readTrailerBeats(dir)).confirmed, 1); + await assert.rejects(updateTrailerBeat(dir, 0, { verdict: "great" }), /verdict is one of confirmed, note/); + await updateTrailerBeat(dir, 0, { verdict: null }); + assert.deepEqual((await readTrailerBeats(dir)).beats[0], { id: "a", start: 12.5, end: 18 }); + await setTrailerSettings(dir, { title: " X cut ", take: "draft-6" }); + const d = await readTrailerBeats(dir); + assert.deepEqual(d.settings, { title: "X cut", take: "draft-6" }); + await assert.rejects(setTrailerSettings(dir, { take: "Not A Take" }), /take is a take id/); + await setTrailerSettings(dir, { title: null, take: null }); + assert.deepEqual((await readTrailerBeats(dir)).settings, {}); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("every write is an undo point: undo puts the file back as it was, one write at a time, and the token guards it", async () => { + const { readReelUndo, undoTrailerBeats } = await import("./trailerBeats.mjs"); + const dir = await project([{ id: "a", start: 12, end: 18 }]); + try { + const before = await fileOf(dir); + await updateTrailerBeat(dir, 0, { start: 13 }); + await addTrailerBeat(dir, { id: "c", start: 61, end: 64 }); + assert.deepEqual((await readReelUndo(dir)).map((p) => p.what), ["beat 1: start", "add c"]); + const tok = await beatsToken(dir); + await assert.rejects(undoTrailerBeats(dir, { token: "0" }), BeatsStale); + const u = await undoTrailerBeats(dir, { token: tok }); + assert.equal(u.undone, "add c"); + assert.equal(u.left, 1); + assert.deepEqual((await readTrailerBeats(dir)).beats, [{ id: "a", start: 13, end: 18 }]); + await undoTrailerBeats(dir); + assert.equal(await fileOf(dir), before); + await assert.rejects(undoTrailerBeats(dir), /nothing to undo/); + // A reel made here: its first undo takes the file away again. + const { createReel } = await import("./trailerBeats.mjs"); + await createReel(dir, "teaser"); + await undoTrailerBeats(dir, { reel: "teaser" }); + assert.equal(await beatsToken(dir, "teaser"), null); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerBeatsCli.mjs b/umtool/lib/report/trailerBeatsCli.mjs @@ -11,13 +11,19 @@ import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { + BEAT_VERDICTS, BeatsStale, - TRAILER_BEATS_FILE, + DEFAULT_REEL, TRAILER_LIMITS, addTrailerBeat, beatsToken, clockOf, + createReel, introSecondsOf, + isReelId, + listReels, + readReelUndo, + reelFileOf, moveTrailerBeat, orderTrailerBeats, readTrailerBeats, @@ -25,6 +31,7 @@ import { setTrailerSettings, trailerCandidatesOf, trailerView, + undoTrailerBeats, updateTrailerBeat, } from "./trailerBeats.mjs"; @@ -38,14 +45,20 @@ export const TRAILER_BEATS_USAGE = [ " umtool trailer-beats <project> remove <n> | move <n> --to <m> | order (the cut's order)", ` umtool trailer-beats <project> limit <seconds|m:ss|${TRAILER_LIMITS.map((l) => l.id).join("|")}> | xfade <s> | intro on|off`, " umtool trailer-beats <project> candidates [--add] the walk's ★ clips not yet beats (--add: all of them)", + ` umtool trailer-beats <project> verdict <n> ${BEAT_VERDICTS.join("|")}|clear the walk's word on beat n`, + " umtool trailer-beats <project> title <text>|none | take <take>|none the reel's name, the take it is cut from", + " umtool trailer-beats <project> undo the reel as it was before its last write (each write is an undo point)", + " umtool trailer-beats <project> reels [--json] the project's reels", + " umtool trailer-beats <project> new-reel <name> [--from <reel>] [--title T] a new reel (empty, or a copy)", "", - `The file is <project>/${TRAILER_BEATS_FILE}; \`umtool trailer <p> --take <t> --beats <that file>\` cuts the trailer.`, + "--reel <name> on any of these: that reel (promo/<name>-beats.json); the default is `trailer`, promo/trailer-beats.json.", + "`umtool trailer <p> --reel <name> [--take <t>]` cuts it.", ].join("\n"); class CliError extends Error {} function parse(args) { - const valued = new Set(["--at", "--to", "--label"]); + const valued = new Set(["--at", "--to", "--label", "--reel", "--from", "--title"]); /** @type {Record<string, string>} */ const flags = {}; const positional = []; @@ -89,7 +102,7 @@ export function viewLines(v) { for (const r of v.rows) { const what = r.kind === "clip" ? `${r.id.padEnd(8)} ${String(r.start).padStart(9)}–${String(r.end).padEnd(9)}` : `(master) at ${r.at} for ${r.dur}`.padEnd(29); const flag = r.problems.length ? ` ! ${r.problems.join("; ")}` : ""; - lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${flag}`); + lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${flag}`); } lines.push( `${v.rows.length} beat(s): ${clockOf(v.total)} of ${clockOf(v.limit)}${v.over ? ` — OVER by ${(v.total - v.limit).toFixed(1)} s` : ` (${v.remaining.toFixed(1)} s to spare)`}` + @@ -117,7 +130,9 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const project = r.project; const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); - const token = await beatsToken(project.dir); + let reel = p.has("--reel") ? p.flags["--reel"] : DEFAULT_REEL; + if (!isReelId(reel)) throw new CliError(`--reel ${reel}: a reel name (lower case, digits and dashes)`); + const token = await beatsToken(project.dir, reel); const label = p.has("--label") ? p.flags["--label"] : undefined; const at = p.has("--at") ? beatNo(p.flags["--at"], "--at") : null; let did = null; @@ -130,7 +145,7 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const e = (manifest.timeline ?? []).find((x) => x?.id === id && x.type === "clip"); if (!e) throw new CliError(`no clip ${id} in the cut`); const span = rest[1] ? spanOf(rest[1]) : { start: e.cutStart ?? e.start, end: e.cutEnd ?? e.end }; - const res = await addTrailerBeat(project.dir, { id, ...span, ...(label ? { label } : {}) }, { token, at, manifest }); + const res = await addTrailerBeat(project.dir, { id, ...span, ...(label ? { label } : {}) }, { token, at, manifest, reel }); did = `added beat ${res.index + 1}: ${id} ${res.beat.start}–${res.beat.end}`; break; } @@ -138,7 +153,7 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const a = Number(rest[0]); const d = Number(rest[1]); if (!Number.isFinite(a) || !Number.isFinite(d)) throw new CliError("add-raw <at> <dur>: master seconds"); - const res = await addTrailerBeat(project.dir, { at: a, dur: d, ...(label ? { label } : {}) }, { token, at }); + const res = await addTrailerBeat(project.dir, { at: a, dur: d, ...(label ? { label } : {}) }, { token, at, reel }); did = `added beat ${res.index + 1}: master ${a} for ${d} s`; break; } @@ -146,13 +161,13 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const i = beatNo(rest[0]); const patch = { ...(rest[1] ? spanOf(rest[1]) : {}), ...(label !== undefined ? { label } : {}) }; if (!Object.keys(patch).length) throw new CliError("set <n> <from>-<to> [--label L]"); - const res = await updateTrailerBeat(project.dir, i, patch, { token }); + const res = await updateTrailerBeat(project.dir, i, patch, { token, reel }); did = `beat ${i + 1}: ${JSON.stringify(res.beat)}`; break; } case "remove": { const i = beatNo(rest[0]); - const res = await removeTrailerBeat(project.dir, i, { token }); + const res = await removeTrailerBeat(project.dir, i, { token, reel }); did = `removed beat ${i + 1} (${res.removed.id ?? `master ${res.removed.at}`})`; break; } @@ -160,30 +175,71 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const i = beatNo(rest[0]); if (!p.has("--to")) throw new CliError("move <n> --to <m>"); const to = beatNo(p.flags["--to"], "--to"); - await moveTrailerBeat(project.dir, i, to, { token }); + await moveTrailerBeat(project.dir, i, to, { token, reel }); did = `moved beat ${i + 1} to ${to + 1}`; break; } case "order": { - const res = await orderTrailerBeats(project.dir, manifest, { token }); + const res = await orderTrailerBeats(project.dir, manifest, { token, reel }); did = res.moved ? "the beats are in the cut's order now" : "the beats were already in the cut's order"; break; } case "limit": - await setTrailerSettings(project.dir, { limit: rest[0] === "default" ? null : limitOf(rest[0]) }, { token }); + await setTrailerSettings(project.dir, { limit: rest[0] === "default" ? null : limitOf(rest[0]) }, { token, reel }); did = "limit set"; break; case "xfade": - await setTrailerSettings(project.dir, { xfade: rest[0] === "default" ? null : Number(rest[0]) }, { token }); + await setTrailerSettings(project.dir, { xfade: rest[0] === "default" ? null : Number(rest[0]) }, { token, reel }); did = "crossfade set"; break; case "intro": if (!["on", "off"].includes(rest[0])) throw new CliError("intro on|off"); - await setTrailerSettings(project.dir, { intro: rest[0] === "on" }, { token }); + await setTrailerSettings(project.dir, { intro: rest[0] === "on" }, { token, reel }); did = `intro ${rest[0]}`; break; + case "title": { + const t = rest.join(" ").trim(); + if (!t) throw new CliError("title <text>|none"); + await setTrailerSettings(project.dir, { title: t === "none" ? null : t }, { token, reel }); + did = t === "none" ? "title cleared" : `title: ${t}`; + break; + } + case "take": { + const t = rest[0]; + if (!t) throw new CliError("take <take>|none: the take the reel is cut from (none: the last cut, else the latest master)"); + await setTrailerSettings(project.dir, { take: t === "none" ? null : t }, { token, reel }); + did = t === "none" ? "take unpinned" : `pinned to take ${t}`; + break; + } + case "verdict": { + const i = beatNo(rest[0]); + const v = rest[1]; + if (v !== "clear" && !BEAT_VERDICTS.includes(v)) throw new CliError(`verdict <n> ${BEAT_VERDICTS.join("|")}|clear`); + await updateTrailerBeat(project.dir, i, { verdict: v === "clear" ? null : v }, { token, reel }); + did = `beat ${i + 1}: ${v === "clear" ? "verdict cleared" : v}`; + break; + } + case "undo": { + const u = await undoTrailerBeats(project.dir, { token, reel }); + did = `undone: ${u.undone} (${u.left} undo point${u.left === 1 ? "" : "s"} left)`; + break; + } + case "reels": { + const reels = await listReels(project.dir); + if (p.has("--json")) out(JSON.stringify({ project: project.id, reels }, null, 2)); + else for (const x of reels) out(`${x.name.padEnd(16)} ${x.file.padEnd(32)} ${x.exists ? `${x.beats} beat(s)` : "(no file yet)"}${x.title ? ` "${x.title}"` : ""}${x.take ? ` take ${x.take}` : ""}${x.error ? ` ! ${x.error}` : ""}`); + return 0; + } + case "new-reel": { + const name = rest[0]; + if (!name) throw new CliError("new-reel <name> [--from <reel>] [--title T]"); + await createReel(project.dir, name, { from: p.has("--from") ? p.flags["--from"] : null, title: p.has("--title") ? p.flags["--title"] : null }); + did = `made the reel ${name} (${reelFileOf(name)})${p.has("--from") ? `, a copy of ${p.flags["--from"]}` : ""}`; + reel = name; + break; + } case "candidates": { - const doc = await readTrailerBeats(project.dir); + const doc = await readTrailerBeats(project.dir, { reel }); const cands = trailerCandidatesOf(manifest, doc.beats); if (!p.has("--add")) { if (p.has("--json")) out(JSON.stringify({ project: project.id, candidates: cands }, null, 2)); @@ -192,20 +248,22 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) return 0; } let tok = token; - for (const c of cands) tok = (await addTrailerBeat(project.dir, { id: c.id, start: c.start, end: c.end }, { token: tok, manifest })).token; + for (const c of cands) tok = (await addTrailerBeat(project.dir, { id: c.id, start: c.start, end: c.end }, { token: tok, manifest, reel })).token; did = `added ${cands.length} ★ beat(s)`; break; } default: throw new CliError(`unknown: trailer-beats ${verb}\n${TRAILER_BEATS_USAGE}`); } - const doc = await readTrailerBeats(project.dir); - const view = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(project.dir) : null }); + const doc = await readTrailerBeats(project.dir, { reel }); + const view = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(project.dir) : null, reel }); + const undo = await readReelUndo(project.dir, { reel }); if (p.has("--json")) { - out(JSON.stringify({ ok: true, project: project.id, ...(did ? { did } : {}), token: await beatsToken(project.dir), ...view }, null, 2)); + out(JSON.stringify({ ok: true, project: project.id, ...(did ? { did } : {}), token: await beatsToken(project.dir, reel), ...view, undo: undo.length }, null, 2)); return 0; } if (did) out(did); + if (reel !== DEFAULT_REEL || view.title) out(`reel ${reel}${view.title ? ` "${view.title}"` : ""} (${view.file})${view.take ? ` · cut from take ${view.take}` : ""}`); for (const line of viewLines(view)) out(line); return 0; } catch (e) { diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -4,6 +4,7 @@ // // umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) // [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json] +// umtool trailer <project> --reel <name> [--take <t>] [...] a beat reel (promo/<name>-beats.json) with its own settings // umtool trailer <project> --candidates [--json] the walk's ★ clips as beats import { readFile } from "node:fs/promises"; import path from "node:path"; @@ -12,6 +13,8 @@ import { kindMakesTakes } from "../projects/kinds.mjs"; import { takesDirOf } from "./takes.mjs"; import { readManifest } from "../projects/report.mjs"; import { candidateBeats, trailerCandidates } from "./trailerCandidates.mjs"; +import { pickReelTake, reelCuts, reelOutArg, takeMasters } from "./reelPlay.mjs"; +import { isReelId, readTrailerBeats, reelFileOf } from "./trailerBeats.mjs"; import { TRAILER_ESTIMATE_MB, TRAILER_XFADE_DEFAULT, @@ -37,6 +40,12 @@ export const TRAILER_USAGE = [ "(--out NAME: that name there; a path: exactly there) and <name>.trailer.json beside it, what was cut.", "--dry-run prints the mapping and writes nothing.", "", + "umtool trailer <project> --reel <name> [--take <t>] [--intro] [--xfade S] [...]: a BEAT REEL -- the beats of", + "promo/<name>-beats.json (the reel `trailer` is promo/trailer-beats.json), with that file's own intro and", + "crossfade unless a flag says otherwise, written to takes/<t>/out/<slug>.<name>.mp4 (the trailer reel:", + "<slug>.trailer.mp4). With no --take: the reel's pinned take, else the take it was last cut from, else the", + "latest take with a finished master (said). The Trailer page's Cut the trailer runs exactly this.", + "", "umtool trailer <project> --candidates [--json]: the clips starred (★) on the walk, in the cut's order, as beats", "over what each plays -- with --json exactly what --beats-json takes:", " umtool trailer <p> --take <t> --beats-json \"$(umtool trailer <p> --candidates --json)\"", @@ -45,7 +54,7 @@ export const TRAILER_USAGE = [ class CliError extends Error {} function parse(args) { - const valued = new Set(["--take", "--beats", "--beats-json", "--finale", "--xfade", "--out"]); + const valued = new Set(["--take", "--beats", "--beats-json", "--finale", "--xfade", "--out", "--reel"]); /** @type {Record<string, string>} */ const flags = {}; const positional = []; @@ -138,20 +147,51 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c } return 0; } - const take = p.flags["--take"]; + const json = p.has("--json"); + const reel = p.has("--reel") ? p.flags["--reel"] : null; + let take = p.flags["--take"] ?? null; + /** The reel's own settings, under the flags. */ + let reelSettings = /** @type {Record<string, any>} */ ({}); + let reelBeats = null; + let outArg = p.flags["--out"] ?? null; + if (reel !== null) { + if (!isReelId(reel)) throw new CliError(`--reel ${reel}: a reel name (lower case, digits and dashes)`); + if (p.has("--beats") || p.has("--beats-json")) throw new CliError("--reel reads the reel's own beats file: not with --beats or --beats-json"); + const doc = await readTrailerBeats(r.project.dir, { reel }); + if (!doc.exists) throw new CliError(`no reel ${reel}: ${reelFileOf(reel)} is not there (\`umtool trailer-beats ${r.project.id} new-reel ${reel}\`)`); + reelSettings = doc.settings ?? {}; + reelBeats = doc.beats; + const masters = await takeMasters(r.project.dir); + if (!take) { + const chosen = pickReelTake({ pinned: reelSettings.take ?? null, cuts: await reelCuts(masters, reel), masters }); + if (!chosen) throw new CliError(`no take of ${r.project.id} has a finished master to cut the reel from — render a take first`); + take = chosen.id; + if (!json) err(`trailer: the reel ${reel} from take ${take} (${chosen.why})`); + } + // The take's slug names the output (a take made by hand may not be in the listing). + const slug = masters.find((x) => x.id === take)?.slug + ?? (await readFile(path.join(takesDirOf(r.project.dir), take, "video.manifest.json"), "utf8").then((t) => JSON.parse(t).slug, () => null)); + if (!outArg && typeof slug === "string" && slug) outArg = reelOutArg(slug, reel); + } if (!take) throw new CliError("--take <t>: the finished take to cut the trailer from"); if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`); - const beats = await beatsOf(p); + let beats; + if (reelBeats) { + try { + beats = reelBeats.length ? parseBeats(reelBeats) : []; + } catch (e) { + throw new CliError(`${reelFileOf(reel)}: ${e instanceof Error ? e.message : e}`); + } + } else beats = await beatsOf(p); const takeDir = path.join(takesDirOf(r.project.dir), take); - const json = p.has("--json"); const slotFor = deps.slot ?? (await realSlot()); const res = await makeTrailer({ takeDir, beats, - intro: p.has("--intro"), + intro: p.has("--intro") || reelSettings.intro === true, finale: p.has("--finale") ? seconds(p, "--finale", null) : null, - xfade: seconds(p, "--xfade", TRAILER_XFADE_DEFAULT), - out: p.flags["--out"] ?? null, + xfade: seconds(p, "--xfade", typeof reelSettings.xfade === "number" ? reelSettings.xfade : TRAILER_XFADE_DEFAULT), + out: outArg, dryRun: p.has("--dry-run"), snap: !p.has("--no-snap"), ...(deps.measure ? { measure: deps.measure } : {}), @@ -159,12 +199,12 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c ...(deps.probe ? { probe: deps.probe } : {}), slot: (fn) => { if (!json) err(`trailer: encoding ${res0(beats)} in the heavy slot …`); - return slotFor(["umtool", "trailer", r.project.id, "--take", take])(fn); + return slotFor(["umtool", "trailer", r.project.id, ...(reel ? ["--reel", reel] : []), "--take", take])(fn); }, }); if (json) { log(JSON.stringify({ - project: r.project.id, take, out: res.dryRun ? null : res.outPath, record: res.dryRun ? null : res.recordPath, + project: r.project.id, ...(reel ? { reel } : {}), take, out: res.dryRun ? null : res.outPath, record: res.dryRun ? null : res.recordPath, wouldWrite: res.dryRun ? res.outPath : undefined, seconds: res.plan.total, encodeSeconds: res.encodeSeconds, pieces: res.plan.pieces, notes: res.plan.notes, }, null, 2)); diff --git a/umtool/lib/report/trailerCli.test.mjs b/umtool/lib/report/trailerCli.test.mjs @@ -113,3 +113,34 @@ test("umtool trailer: refusals exit 1 by name; usage mistakes exit 2", async () await rm(root, { recursive: true, force: true }); } }); + +test("umtool trailer --reel: the reel's own beats, crossfade and intro, written to <slug>.<reel>.mp4; no --take: the latest master", async () => { + const { root, reportsRoot, take } = await project(); + try { + const dir = path.join(reportsRoot, "proj"); + await writeFile(path.join(take, "take.json"), JSON.stringify({ id: "final", group: "takes", order: 1, label: "final", kind: "reference", preview: "preview.mp4" })); + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "promo", "teaser-beats.json"), JSON.stringify({ xfade: 0, intro: true, beats: [{ id: "c1", start: 55, end: 60 }] })); + const ran = []; + const o = io(); + const code = await trailerCommand(["proj", "--reel", "teaser", "--no-snap"], { reportsRoot, log: o.log, err: o.err, deps: deps(ran) }); + assert.equal(code, 0, o.errs.join("\n")); + assert.match(o.errs.join("\n"), /the reel teaser from take final \(latest master\)/); + assert.match(o.out.join("\n"), /wrote .*cut\.teaser\.mp4/); + const rec = JSON.parse(await readFile(path.join(take, "out", "cut.teaser.trailer.json"), "utf8")); + assert.equal(rec.xfade, 0); + assert.deepEqual(rec.pieces.map((p) => p.kind), ["intro", "clip"]); + // The trailer reel keeps its old name; a reel that is not there is said. + const o2 = io(); + assert.equal(await trailerCommand(["proj", "--reel", "nope", "--take", "final"], { reportsRoot, log: o2.log, err: o2.err, deps: deps([]) }), 2); + assert.match(o2.errs.join("\n"), /no reel nope: promo\/nope-beats\.json is not there/); + const o3 = io(); + assert.equal(await trailerCommand(["proj", "--reel", "teaser", "--beats-json", "[]"], { reportsRoot, log: o3.log, err: o3.err, deps: deps([]) }), 2); + await writeFile(path.join(dir, "promo", "trailer-beats.json"), JSON.stringify([{ id: "c1", start: 55, end: 58 }])); + const o4 = io(); + assert.equal(await trailerCommand(["proj", "--reel", "trailer", "--take", "final", "--no-snap"], { reportsRoot, log: o4.log, err: o4.err, deps: deps([]) }), 0, o4.errs.join("\n")); + assert.match(o4.out.join("\n"), /wrote .*cut\.trailer\.mp4/); + } finally { + await rm(root, { recursive: true, force: true }); + } +});