commit 7fa0c551f949ceed803661bf77ea02b4808b3e6f
parent 77882121b8ea9f1283c987d15c3188bbce00d51e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 16:08:03 -0500
Merge lane/beat-reels: play and walk a trailer like the cut, from the take's rendered master -- reels (promo/<name>-beats.json, the trailer reel at its old path), Play the reel (beats back to back on the master's own frames, the crossfade, the clock against the limit, notes on a beat), the walk (in/out handles, a verdict per beat, undo), Cut the trailer as a job with its local path; umtool trailer --reel, trailer-beats --reel and its new verbs
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
38 files changed, 3482 insertions(+), 130 deletions(-)
diff --git a/plans/spin-off-videos.md b/plans/spin-off-videos.md
@@ -142,7 +142,18 @@ Order 1 → 2 → 3, 4 alongside. 1 and 2 alone remove most of the hand work abo
rendered main first"** — so a reel gets **Play** (the cut's Play view over the reel's beats, from the master) and a
**walk** (the clip bench over each beat: in/out on the master's frames, notes, a verdict per beat), the same
surfaces, keys and notes as the cut's; a reel whose take has no rendered master says so and offers the render.
- Lane **`lane/beat-reels`** (started 2 Nov).
+ Lane **`lane/beat-reels`** (built 2 Nov, unmerged): reels are `promo/<name>-beats.json` (`trailer` unchanged), each
+ with its own limit, crossfade, intro, `title` and pinned `take`; `umtool trailer <p> --reel <name> [--take <t>]`
+ (output `<slug>.<name>.mp4`; no `--take`: pinned, else last cut, else the latest finished master) and `umtool
+ trailer-beats <p> --reel <name> … | reels | new-reel | undo | verdict | title | take`; every write an undo point
+ (`promo/.<file>.undo.json`). **Play the reel** (`/projects/<p>/trailer/play?reel=&take=`) and the **walk**
+ (`…/trailer/walk?beat=n`) read `lib/report/reelPlay.mjs`, which maps each beat with the trailer's own `planTrailer`
+ (edges as written); notes anchor to a beat (anchor kind `reel`, printed by `umtool notes` with the writer to use);
+ **Cut the trailer** is a job on umtool's runner (`POST /api/report/reel`), the result playing with its local path;
+ a reel with no rendered master says so and links the Takes page. Not done: the reels listed on the Takes page beside
+ their take; Play previewing the cut's snapped edges (it plays the edges as written; the cut moves each ≤ 1 s into its
+ pause and says so); a waveform on the reel walk; re-cutting a reel when its take is re-rendered (the panel marks a cut
+ older than its master); the video assistant on a reel note.
- **No umtool page plays a take's trailer, and take cards show no local paths** — lane 4 above; until then the
operator gets file paths (operator, 2 Nov: "tell me local file paths for output files").
- **Hand-written spin-off manifests** (`emberparadox/kirsche`'s first manifest was written from a take's, outside
diff --git a/umtool/app/api/report/reel/media/route.ts b/umtool/app/api/report/reel/media/route.ts
@@ -0,0 +1,50 @@
+import { realpath, stat } from "node:fs/promises";
+import path from "node:path";
+import { reelCuts, takeMasters } from "@/lib/report/reelPlay.mjs";
+import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { DEFAULT_REEL, isReelId } from "@/lib/report/trailerBeats.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A take's MASTER (`what=master`, what a reel's Play and walk seek through) or
+// a reel's CUT in that take (`what=cut&reel=<name>`), to a <video> element.
+// ?project&take&what&reel&v. Names, never paths: the take must be one the
+// listing returns and the file the one its slug and the reel name; `v` is the
+// video route's contract (the mtime it was told; only a match is cached).
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const take = url.searchParams.get("take") ?? "";
+ if (!isTakeId(take)) return new Response("take must be a take id", { status: 400 });
+ const what = url.searchParams.get("what") ?? "master";
+ if (what !== "master" && what !== "cut") return new Response("what is master or cut", { status: 400 });
+ const reel = url.searchParams.get("reel") || DEFAULT_REEL;
+ if (!isReelId(reel)) return new Response("reel is a reel name", { status: 400 });
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return new Response(r.error, { status: r.status });
+ const masters = await takeMasters(r.project.dir);
+ const t = masters.find((m) => m.id === take);
+ if (!t) return new Response("no such take", { status: 404 });
+ let abs: string | null = null;
+ if (what === "master") abs = t.master;
+ else abs = (await reelCuts([t], reel))[0]?.out ?? null;
+ if (!abs) return new Response(what === "master" ? `take ${take} has no master yet` : `the reel ${reel} has not been cut from take ${take}`, { status: 404 });
+ // The file's real path stays under the take's own directory's real path (its out/ may be a link to the media drive: that is followed, nothing else).
+ const real = await realpath(abs).catch(() => null);
+ const realOut = await realpath(path.join(t.dir, "out")).catch(() => null);
+ if (!real || !realOut || !(real.startsWith(`${realOut}${path.sep}`))) return new Response("not served", { status: 403 });
+ const st = await stat(real).catch(() => null);
+ if (!st?.isFile()) return new Response("gone", { status: 404 });
+ const mtime = String(Math.round(st.mtimeMs));
+ const fresh = url.searchParams.get("v") === mtime;
+ return rangeResponse(request, {
+ abs: real,
+ size: st.size,
+ headers: {
+ "content-type": "video/mp4",
+ "accept-ranges": "bytes",
+ "cache-control": fresh ? "private, max-age=3600, immutable" : "private, no-store",
+ "x-video-mtime": mtime,
+ },
+ });
+}
diff --git a/umtool/app/api/report/reel/route.ts b/umtool/app/api/report/reel/route.ts
@@ -0,0 +1,81 @@
+import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { refuseCaller } from "@/lib/report/caller";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { reelCutSteps, reelPlayView } from "@/lib/report/reelPlay.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { DEFAULT_REEL, isReelId, listReels } from "@/lib/report/trailerBeats.mjs";
+
+export const dynamic = "force-dynamic";
+
+// BEAT REELS (lane/beat-reels): a reel's beats played and walked from a take's
+// rendered master, and Cut the trailer as a job on umtool's runner.
+//
+// GET ?project=<id>&reel=<name>&take=<t> the reel on that take's master
+// (lib/report/reelPlay.mjs): each beat's
+// master span, the reel's cuts, the
+// takes with masters, the reels, and the
+// cut job running for this project, if any
+// GET ?job=<id>[&since=&sinceEvent=] that job, as the take jobs show one
+// POST { project, reel, take } cut it: `umtool trailer <p> --reel <r>
+// --take <t>` on the runner (one job at a
+// time; the CLI takes the heavy slot)
+// ?cancel=<job> stop it
+// The beats themselves are written through /api/report/trailer-beats, their one writer.
+
+const noStore = { "cache-control": "no-store" };
+const isCut = (kind: string) => /^trailer /.test(kind);
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ if (id) {
+ const job = getJob(id);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404 });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers: noStore });
+ }
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const reel = url.searchParams.get("reel") || DEFAULT_REEL;
+ if (!isReelId(reel)) return Response.json({ error: "reel is a reel name" }, { status: 400 });
+ const take = url.searchParams.get("take") || null;
+ if (take && !isTakeId(take)) return Response.json({ error: "take is a take id" }, { status: 400 });
+ try {
+ const [view, reels] = await Promise.all([reelPlayView(r.project, { reel, take }), listReels(r.project.dir)]);
+ const running = runningJob();
+ return Response.json(
+ { ...view, reels, job: running && running.project === r.project.id && isCut(running.kind) ? jobView(running) : null, busy: running && !isCut(running.kind) ? running.kind : null },
+ { headers: noStore },
+ );
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/reel");
+ if (refused) return refused;
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) return Response.json({ cancelled: cancelJob(cancel) });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "expected JSON" }, { status: 400 });
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const reel = typeof body.reel === "string" && body.reel ? body.reel : DEFAULT_REEL;
+ if (!isReelId(reel)) return Response.json({ error: "reel is a reel name" }, { status: 400 });
+ const take = String(body.take ?? "");
+ if (!isTakeId(take)) return Response.json({ error: "take is a take id: the take whose master the reel is cut from" }, { status: 400 });
+ const view = await reelPlayView(r.project, { reel, take });
+ if (view.noMaster) return Response.json({ error: view.noMaster.why }, { status: 400 });
+ if (!view.beats && !view.introAsked) return Response.json({ error: `the reel ${reel} has no beats yet` }, { status: 400 });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
+ const plan = reelCutSteps(r.project, reel, take, { umtoolDir: UMTOOL_DIR });
+ try {
+ const job = startJob(plan.kind, plan.steps, { project: r.project.id });
+ return Response.json({ ok: true, job: jobView(job) }, { headers: noStore });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 });
+ }
+}
diff --git a/umtool/app/api/report/trailer-beats/route.ts b/umtool/app/api/report/trailer-beats/route.ts
@@ -2,17 +2,23 @@ import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
import {
BeatsStale,
+ DEFAULT_REEL,
TRAILER_LIMITS,
addTrailerBeat,
beatsToken,
+ createReel,
introSecondsOf,
+ isReelId,
+ listReels,
moveTrailerBeat,
orderTrailerBeats,
+ readReelUndo,
readTrailerBeats,
removeTrailerBeat,
setTrailerSettings,
trailerCandidatesOf,
trailerView,
+ undoTrailerBeats,
updateTrailerBeat,
} from "@/lib/report/trailerBeats.mjs";
@@ -22,35 +28,55 @@ export const dynamic = "force-dynamic";
// through its one writer (lib/report/trailerBeats.mjs), the Trailer page's and
// Add to trailer's -- `umtool trailer-beats` is the CLI's twin.
//
-// GET ?project=<id> the view (each beat's length, the running length against
-// the limit, beats outside their clip, the cut's order), the
-// ★ candidates, the cut's clips, the platform limits, the token
-// POST { project, token, op, … }
+// Every call names a REEL (`reel`, default `trailer`: promo/trailer-beats.json;
+// any other: promo/<reel>-beats.json -- lane/beat-reels).
+//
+// GET ?project=<id>&reel=<name> the view (each beat's length, the running length
+// against the limit, beats outside their clip, the cut's
+// order), the ★ candidates, the cut's clips, the platform
+// limits, the token, the project's reels, the undo points
+// POST { project, reel?, token, op, … }
// add { beat: { id, start, end, label? } | { at, dur }, at? } (default: the cut's order)
-// set { index, patch: { start?, end?, at?, dur?, label? } }
+// set { index, patch: { start?, end?, at?, dur?, label?, verdict? } } verdict: confirmed | note | null
// remove { index }
// move { index, to }
// order {} the cut's order
-// settings { limit?, xfade?, intro? } null: the default again
+// settings { limit?, xfade?, intro?, title?, take? } null: the default again
+// undo {} the reel as it was before its last write
+// new-reel { name, from?, title? } a new reel (empty, or a copy of `from`)
// A stale token is a 409.
const noStore = { "cache-control": "no-store" };
-async function view(dir: string, manifest: Record<string, unknown>) {
- const doc = await readTrailerBeats(dir);
- const v = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(dir) : null });
+async function view(dir: string, manifest: Record<string, unknown>, reel: string) {
+ const doc = await readTrailerBeats(dir, { reel });
+ const v = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(dir) : null, reel });
const clips = ((manifest.timeline ?? []) as Record<string, unknown>[])
.filter((e) => e?.type === "clip")
.map((e) => ({ id: String(e.id), start: Number(e.cutStart ?? e.start), end: Number(e.cutEnd ?? e.end) }));
- return { ...v, candidates: trailerCandidatesOf(manifest, doc.beats), clips, limits: TRAILER_LIMITS, token: await beatsToken(dir), exists: doc.exists };
+ const undo = await readReelUndo(dir, { reel });
+ return {
+ ...v,
+ candidates: trailerCandidatesOf(manifest, doc.beats),
+ clips,
+ limits: TRAILER_LIMITS,
+ token: await beatsToken(dir, reel),
+ exists: doc.exists,
+ reels: await listReels(dir),
+ undo: { count: undo.length, last: undo.length ? undo[undo.length - 1].what : null },
+ };
}
+const reelOf = (v: unknown) => (typeof v === "string" && v ? v : DEFAULT_REEL);
+
export async function GET(request: Request) {
const url = new URL(request.url);
const r = await resolveReport(url.searchParams.get("project") ?? "");
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const reel = reelOf(url.searchParams.get("reel"));
+ if (!isReelId(reel)) return Response.json({ error: "reel is a reel name (lower case, digits and dashes)" }, { status: 400 });
try {
- return Response.json(await view(r.project.dir, r.manifest), { headers: noStore });
+ return Response.json(await view(r.project.dir, r.manifest, reel), { headers: noStore });
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
@@ -64,31 +90,45 @@ export async function POST(request: Request) {
const r = await resolveReport(String(body.project ?? ""));
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const dir = r.project.dir;
+ let reel = reelOf(body.reel);
+ if (!isReelId(reel)) return Response.json({ error: "reel is a reel name (lower case, digits and dashes)" }, { status: 400 });
const token = typeof body.token === "string" ? body.token : null;
try {
+ let did: Record<string, unknown> = {};
switch (body.op) {
case "add":
- await addTrailerBeat(dir, (body.beat ?? {}) as Record<string, unknown>, { token, at: typeof body.at === "number" ? body.at : null, manifest: r.manifest });
+ await addTrailerBeat(dir, (body.beat ?? {}) as Record<string, unknown>, { token, at: typeof body.at === "number" ? body.at : null, manifest: r.manifest, reel });
break;
case "set":
- await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token });
+ await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token, reel });
break;
case "remove":
- await removeTrailerBeat(dir, Number(body.index), { token });
+ await removeTrailerBeat(dir, Number(body.index), { token, reel });
break;
case "move":
- await moveTrailerBeat(dir, Number(body.index), Number(body.to), { token });
+ await moveTrailerBeat(dir, Number(body.index), Number(body.to), { token, reel });
break;
case "order":
- await orderTrailerBeats(dir, r.manifest, { token });
+ await orderTrailerBeats(dir, r.manifest, { token, reel });
break;
case "settings":
- await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro"].filter((k) => k in body).map((k) => [k, body[k]])), { token });
+ await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro", "title", "take"].filter((k) => k in body).map((k) => [k, body[k]])), { token, reel });
+ break;
+ case "undo": {
+ const u = await undoTrailerBeats(dir, { token, reel });
+ did = { undone: u.undone };
+ break;
+ }
+ case "new-reel": {
+ const name = String(body.name ?? "");
+ await createReel(dir, name, { from: typeof body.from === "string" && body.from ? body.from : null, title: typeof body.title === "string" ? body.title : null });
+ reel = name;
break;
+ }
default:
- return Response.json({ error: "op must be add, set, remove, move, order or settings" }, { status: 400 });
+ return Response.json({ error: "op must be add, set, remove, move, order, settings, undo or new-reel" }, { status: 400 });
}
- return Response.json({ ok: true, ...(await view(dir, r.manifest)) }, { headers: noStore });
+ return Response.json({ ok: true, ...did, ...(await view(dir, r.manifest, reel)) }, { headers: noStore });
} catch (e) {
if (e instanceof BeatsStale) return Response.json({ error: e.message, stale: true }, { status: 409 });
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
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/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -13,6 +13,8 @@ import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
import PlayCutPage from "./PlayCutPage";
import TakeWalkPage from "./TakeWalkPage";
+import ReelPlayPage from "./reel/ReelPlayPage";
+import ReelWalkPage from "./reel/ReelWalkPage";
import TrailerPage from "./TrailerPage";
import { isTakeId } from "@/lib/report/takes.mjs";
@@ -85,8 +87,16 @@ export default async function ProjectView({
if (rest.length === 1 && rest[0] === "clips") return <ClipDeckPage project={project} show={search.show} mode={search.mode} clip={search.clip} />;
// `/projects/<project>/play` -- the whole cut (or `?take=<id>`) played in
// the browser in its final look, no render, with notes taken as it plays.
- // `/projects/<project>/trailer` -- the trailer's beats (promo/trailer-beats.json).
- if (rest.length === 1 && rest[0] === "trailer") return <TrailerPage project={project} />;
+ // `/projects/<project>/trailer` -- the trailer's beats (promo/trailer-beats.json),
+ // or another beat reel's (`?reel=<name>`); `…/trailer/play` the reel played
+ // from a take's rendered master, `…/trailer/walk?beat=n` the bench over a beat.
+ if (rest.length === 1 && rest[0] === "trailer") return <TrailerPage project={project} reel={search.reel} />;
+ if (rest.length === 2 && rest[0] === "trailer" && rest[1] === "play") {
+ return <ReelPlayPage project={project} reel={search.reel} take={search.take} beat={search.beat} note={search.note} />;
+ }
+ if (rest.length === 2 && rest[0] === "trailer" && rest[1] === "walk") {
+ return <ReelWalkPage project={project} reel={search.reel} take={search.take} beat={search.beat} />;
+ }
if (rest.length === 1 && rest[0] === "play") return <PlayCutPage project={project} take={search.take} bare={search.cut === "1"} note={search.note} clip={search.clip} at={search.at} />;
return notFound();
}
diff --git a/umtool/components/projects/TrailerBeatsEditor.tsx b/umtool/components/projects/TrailerBeatsEditor.tsx
@@ -4,7 +4,9 @@ import { useCallback, useEffect, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
// The Trailer page's editor (TrailerPage.tsx): every write is POST
-// /api/report/trailer-beats, the one writer `umtool trailer-beats` uses too.
+// /api/report/trailer-beats, the one writer `umtool trailer-beats` uses too,
+// for ONE reel (`reel`: promo/<reel>-beats.json; `trailer` is
+// promo/trailer-beats.json). Each write is an undo point (Undo).
type Row = {
n: number;
@@ -15,6 +17,7 @@ type Row = {
at?: number;
dur?: number;
label: string | null;
+ verdict: "confirmed" | "note" | null;
seconds: number;
running: number;
over: boolean;
@@ -22,7 +25,12 @@ type Row = {
problems: string[];
};
type View = {
+ reel: string;
file: string;
+ title: string | null;
+ take: string | null;
+ confirmed: number;
+ undo: { count: number; last: string | null };
limit: number;
xfade: number;
intro: boolean;
@@ -49,7 +57,7 @@ const clock = (s: number) => {
const input =
"rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]";
-export default function TrailerBeatsEditor({ project }: { project: string }) {
+export default function TrailerBeatsEditor({ project, reel = "trailer" }: { project: string; reel?: string }) {
const [view, setView] = useState<View | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
@@ -58,11 +66,11 @@ export default function TrailerBeatsEditor({ project }: { project: string }) {
const [addTo, setAddTo] = useState("");
const load = useCallback(async () => {
- const r = await fetch(`/api/report/trailer-beats?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const r = await fetch(`/api/report/trailer-beats?project=${encodeURIComponent(project)}&reel=${encodeURIComponent(reel)}`, { cache: "no-store" });
const j = await r.json().catch(() => ({}));
if (!r.ok) setError(j.error ?? `HTTP ${r.status}`);
else setView(j as View);
- }, [project]);
+ }, [project, reel]);
useEffect(() => {
void load();
}, [load]);
@@ -74,7 +82,7 @@ export default function TrailerBeatsEditor({ project }: { project: string }) {
const r = await fetch("/api/report/trailer-beats", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, token: view?.token ?? null, op: name, ...args }),
+ body: JSON.stringify({ project, reel, token: view?.token ?? null, op: name, ...args }),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) {
@@ -83,6 +91,8 @@ export default function TrailerBeatsEditor({ project }: { project: string }) {
return false;
}
setView(j as View);
+ // The Cut panel and anything else reading this reel: it changed.
+ window.dispatchEvent(new CustomEvent("umtool:reel-written", { detail: { project, reel } }));
return true;
} finally {
setBusy(false);
@@ -114,6 +124,11 @@ export default function TrailerBeatsEditor({ project }: { project: string }) {
{view.over ? <span className="text-[var(--color-bad)]">over by {(view.total - view.limit).toFixed(1)} s</span> : `${view.remaining.toFixed(1)} s to spare`} · {view.rows.length} beat
{view.rows.length === 1 ? "" : "s"} · crossfade {view.xfade} s{view.intro ? ` · intro ${view.introSeconds ?? "?"} s` : ""}
</span>
+ {view.confirmed > 0 && (
+ <span data-testid="trailer-confirmed" className="text-[12px] text-[var(--color-dim)]">
+ {view.confirmed} confirmed on the walk
+ </span>
+ )}
{view.outside > 0 && (
<span data-testid="trailer-outside" className="text-[12px] text-[var(--color-bad)]">
{view.outside} beat{view.outside === 1 ? "" : "s"} to fix
@@ -169,6 +184,27 @@ export default function TrailerBeatsEditor({ project }: { project: string }) {
<input type="checkbox" data-testid="trailer-intro" checked={view.intro} disabled={busy} onChange={(e) => void op("settings", { intro: e.target.checked })} />
open on the brand intro
</label>
+ <label className="inline-flex items-center gap-1">
+ title
+ <input
+ data-testid="trailer-title"
+ defaultValue={view.title ?? ""}
+ key={`title-${view.title ?? ""}`}
+ placeholder={view.reel}
+ onKeyDown={(e) => e.key === "Enter" && void op("settings", { title: (e.target as HTMLInputElement).value || null })}
+ className={`${input} w-40`}
+ />
+ </label>
+ <button
+ type="button"
+ data-testid="trailer-undo"
+ disabled={busy || !view.undo?.count}
+ onClick={() => void op("undo")}
+ className={buttonVariants({ variant: "quiet", size: "sm" })}
+ title={view.undo?.last ? `undo: ${view.undo.last}` : "nothing to undo"}
+ >
+ Undo{view.undo?.last ? ` (${view.undo.last})` : ""}
+ </button>
<button type="button" data-testid="trailer-order" disabled={busy || view.inOrder} onClick={() => void op("order")} className={buttonVariants({ size: "sm" })} title="put the beats in the order the cut plays their clips">
{view.inOrder ? "in the cut's order" : "Order by the cut"}
</button>
@@ -244,8 +280,8 @@ export default function TrailerBeatsEditor({ project }: { project: string }) {
)}
</section>
<p className="text-[11px] text-[var(--color-dim)]">
- Cut it: <code className="font-mono">umtool trailer {project} --take <take>{view.intro ? " --intro" : ""} --beats <project>/{view.file} --xfade {view.xfade}</code> · the same edits:{" "}
- <code className="font-mono">umtool trailer-beats {project}</code>
+ Cut it here (above), or <code className="font-mono">umtool trailer {project} --reel {view.reel}{view.take ? ` --take ${view.take}` : ""}</code> · the same edits:{" "}
+ <code className="font-mono">umtool trailer-beats {project}{view.reel !== "trailer" ? ` --reel ${view.reel}` : ""}</code>
</p>
</div>
);
@@ -278,6 +314,11 @@ function BeatRow({ row: r, index: i, last, busy, op }: { row: Row; index: number
>
<span className="num w-5 text-right font-mono text-[var(--color-dim)]">{r.n}</span>
<span className="w-14 font-mono text-[var(--color-text)]">{r.kind === "clip" ? r.id : "master"}</span>
+ {r.verdict && (
+ <span data-beat-verdict={r.verdict} className="micro" title={r.verdict === "confirmed" ? "confirmed on the walk" : "a note on the walk"}>
+ {r.verdict === "confirmed" ? "✓" : "✎"}
+ </span>
+ )}
<input data-beat-from={r.n} value={from} onChange={(e) => setFrom(e.target.value)} onBlur={save} onKeyDown={(e) => e.key === "Enter" && save()} className={`${input} w-20`} title={r.kind === "clip" ? "source second it starts at" : "master second"} />
{r.kind === "clip" ? "–" : "for"}
<input data-beat-to={r.n} value={to} onChange={(e) => setTo(e.target.value)} onBlur={save} onKeyDown={(e) => e.key === "Enter" && save()} className={`${input} w-20`} title={r.kind === "clip" ? "source second it ends at" : "seconds"} />
diff --git a/umtool/components/projects/TrailerPage.tsx b/umtool/components/projects/TrailerPage.tsx
@@ -1,23 +1,56 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
-import { projectsHref } from "@/lib/hrefs";
+import { projectsHref, trailerHref } from "@/lib/hrefs";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import type { ProjectRef } from "@/lib/project-types";
+import { DEFAULT_REEL, isReelId, listReels } from "@/lib/report/trailerBeats.mjs";
+import { cn } from "@/lib/utils";
import TrailerBeatsEditor from "./TrailerBeatsEditor";
+import ReelCutPanel from "./reel/ReelCutPanel";
+import NewReel from "./reel/NewReel";
// `/projects/<project>/trailer` -- the trailer's beats (UI notes 2026-10-30,
// item 11): promo/trailer-beats.json, its running length against the
// platform's limit, the beats outside their clips, the cut's order, the walk's
-// ★ clips -- edited here, or by `umtool trailer-beats`. The trailer itself is
-// cut by `umtool trailer <p> --take <t> --beats <that file>`.
-export default async function TrailerPage({ project }: { project: ProjectRef }) {
- const back = await pieceHrefOfProject(project.id, { tab: "cut" });
+// ★ clips -- edited here, or by `umtool trailer-beats`. BEAT REELS
+// (lane/beat-reels): the project's other reels (`?reel=<name>`,
+// promo/<name>-beats.json), each played and walked from a take's rendered
+// master and cut as a job on the runner (ReelCutPanel.tsx) -- `umtool trailer
+// <p> --reel <name>` does the same from a terminal.
+export default async function TrailerPage({ project, reel = DEFAULT_REEL }: { project: ProjectRef; reel?: string }) {
+ const r = reel || DEFAULT_REEL;
+ if (!isReelId(r)) notFound();
+ const [back, reels] = await Promise.all([pieceHrefOfProject(project.id, { tab: "cut" }), listReels(project.dir)]);
+ if (r !== DEFAULT_REEL && !reels.some((x) => x.name === r && x.exists)) notFound();
return (
<BenchFrame
kind="trailer"
- top={<BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Trailer" here="beats" />}
+ top={<BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Trailer" here={r === DEFAULT_REEL ? "beats" : `reel ${r}`} />}
>
- <BenchBody workClassName="space-y-3">
- <TrailerBeatsEditor project={project.id} />
+ <BenchBody workClassName="space-y-3 overflow-y-auto">
+ <nav data-reels="" aria-label="The project's reels" className="flex flex-wrap items-center gap-1.5 text-[12px]">
+ <span className="micro">reels</span>
+ {reels.map((x) => (
+ <Link
+ key={x.name}
+ href={trailerHref(project.id, { reel: x.name })}
+ data-reel-tab={x.name}
+ aria-current={x.name === r ? "page" : undefined}
+ className={cn(
+ "rounded-[3px] border px-2 py-0.5 font-mono",
+ x.name === r ? "border-[var(--color-sel)] text-[var(--color-text)]" : "border-[var(--color-line)] text-[var(--color-dim)] hover:text-[var(--color-text)]",
+ )}
+ title={x.file}
+ >
+ {x.name}
+ {x.title ? ` — ${x.title}` : ""} <span className="text-[var(--color-dim)]">({x.exists ? x.beats : "no file"})</span>
+ </Link>
+ ))}
+ <NewReel project={project.id} reels={reels.filter((x) => x.exists).map((x) => x.name)} />
+ </nav>
+ <ReelCutPanel key={`cut-${r}`} project={project.id} reel={r} />
+ <TrailerBeatsEditor key={`beats-${r}`} project={project.id} reel={r} />
</BenchBody>
</BenchFrame>
);
diff --git a/umtool/components/projects/reel/NewReel.tsx b/umtool/components/projects/reel/NewReel.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { trailerHref } from "@/lib/hrefs";
+
+// New reel on the Trailer page: a name (promo/<name>-beats.json), empty or a
+// copy of another reel's beats, through the beats' one writer.
+export default function NewReel({ project, reels }: { project: string; reels: string[] }) {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState("");
+ const [from, setFrom] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const make = async () => {
+ setError(null);
+ const r = await fetch("/api/report/trailer-beats", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, reel: name, op: "new-reel", name, ...(from ? { from } : {}) }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ setError(String(j.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ setOpen(false);
+ setName("");
+ setFrom("");
+ router.push(trailerHref(project, { reel: name }));
+ router.refresh();
+ };
+ if (!open) {
+ return (
+ <button type="button" data-reel-new-open="" onClick={() => setOpen(true)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ + New reel
+ </button>
+ );
+ }
+ return (
+ <span data-reel-new="" className="inline-flex flex-wrap items-center gap-1.5">
+ <input
+ data-reel-new-name=""
+ autoFocus
+ value={name}
+ placeholder="teaser"
+ onChange={(e) => setName(e.target.value.toLowerCase())}
+ onKeyDown={(e) => e.key === "Enter" && void make()}
+ className="w-28 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)]"
+ />
+ <select data-reel-new-from="" value={from} onChange={(e) => setFrom(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px] text-[var(--color-text)]">
+ <option value="">empty</option>
+ {reels.map((r) => (
+ <option key={r} value={r}>
+ a copy of {r}
+ </option>
+ ))}
+ </select>
+ <button type="button" data-reel-new-make="" disabled={!/^[a-z0-9][a-z0-9-]{0,39}$/.test(name)} onClick={() => void make()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Make it
+ </button>
+ {error && <span role="alert" className="text-[var(--color-bad)]">{error}</span>}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/reel/ReelCutPanel.tsx b/umtool/components/projects/reel/ReelCutPanel.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { reelPlayHref, reelWalkHref, takesHref } from "@/lib/hrefs";
+import { clock, cutSrc, readReelView, type ReelJob, type ReelView } from "./reelTypes";
+
+// CUT THE TRAILER (lane/beat-reels) on the Trailer page: the reel's Play and
+// walk on the chosen take's master, and the cut itself as ONE job on umtool's
+// runner (POST /api/report/reel → `umtool trailer <p> --reel <r> --take <t>`,
+// which takes the machine's heavy slot; one job at a time; its log; Cancel).
+// The result plays here, with its LOCAL PATH (the operator reads output files
+// by path), and every earlier cut of the reel is listed by take.
+
+const fmtBytes = (n: number) => (n > 1e9 ? `${(n / 1e9).toFixed(2)} GB` : n > 1e6 ? `${(n / 1e6).toFixed(1)} MB` : `${Math.round(n / 1e3)} kB`);
+
+export default function ReelCutPanel({ project, reel }: { project: string; reel: string }) {
+ const [view, setView] = useState<ReelView | null>(null);
+ const [take, setTake] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [job, setJob] = useState<ReelJob | null>(null);
+ const [log, setLog] = useState<string[]>([]);
+ const since = useRef(0);
+ const logBox = useRef<HTMLPreElement | null>(null);
+ // The log follows its newest line.
+ useEffect(() => {
+ if (logBox.current) logBox.current.scrollTop = logBox.current.scrollHeight;
+ }, [log]);
+
+ const load = useCallback(async () => {
+ try {
+ const v = await readReelView(project, reel, take);
+ setView(v);
+ if (v.job && v.job.state === "running") setJob((j) => j ?? v.job ?? null);
+ setError(null);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ }, [project, reel, take]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ // The beats editor wrote: read the reel again (the running length, what maps).
+ useEffect(() => {
+ const on = () => void load();
+ window.addEventListener("umtool:reel-written", on);
+ return () => window.removeEventListener("umtool:reel-written", on);
+ }, [load]);
+
+ // Follow the job: its log, then the reel read again for the new cut.
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ let live = true;
+ const tick = async () => {
+ const r = await fetch(`/api/report/reel?job=${encodeURIComponent(job.id)}&since=${since.current}`, { cache: "no-store" }).catch(() => null);
+ const j = r && r.ok ? ((await r.json()) as ReelJob) : null;
+ if (!live || !j) return;
+ if (j.log?.length) setLog((l) => [...l, ...j.log].slice(-300));
+ since.current = j.next ?? since.current;
+ if (j.state !== "running") {
+ setJob(j);
+ void load();
+ }
+ };
+ const id = window.setInterval(() => void tick(), 1000);
+ void tick();
+ return () => {
+ live = false;
+ window.clearInterval(id);
+ };
+ }, [job, load]);
+
+ const cut = async () => {
+ if (!view?.take) return;
+ setError(null);
+ const r = await fetch("/api/report/reel", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, reel, take: view.take.id }) });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ setError(String(j.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ since.current = 0;
+ setLog([]);
+ setJob(j.job as ReelJob);
+ };
+ const cancel = async () => {
+ if (!job) return;
+ await fetch(`/api/report/reel?cancel=${encodeURIComponent(job.id)}`, { method: "POST" });
+ };
+
+ if (!view) return <section className="text-[12px] text-muted" data-reel-cut-panel="">{error ?? "reading the reel's takes…"}</section>;
+ const t = view.take?.id ?? null;
+ const running = job?.state === "running";
+ const here = t ? view.cuts.find((c) => c.take === t) ?? null : null;
+ return (
+ <section data-reel-cut-panel={reel} className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <div className="flex flex-wrap items-center gap-2 text-[12px]">
+ <h2 className="micro m-0">play · walk · cut — from a rendered master</h2>
+ {view.noMaster ? (
+ <span data-reel-no-master="" className="text-[var(--color-dim)]">
+ {view.noMaster.why}.{" "}
+ <Link href={takesHref(project)} className="ink-link" data-reel-render-link="">
+ Render a take
+ </Link>
+ </span>
+ ) : (
+ <>
+ <label className="inline-flex items-center gap-1">
+ take
+ <select
+ data-reel-cut-take=""
+ value={t ?? ""}
+ onChange={(e) => setTake(e.target.value)}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px] text-[var(--color-text)]"
+ >
+ {view.takes.filter((x) => x.built).map((x) => (
+ <option key={x.id} value={x.id}>
+ {x.id}
+ {x.rendering ? " (rendering)" : ""}
+ </option>
+ ))}
+ </select>
+ <span className="text-[var(--color-dim)]">({view.take?.why})</span>
+ </label>
+ <Link href={reelPlayHref(project, { reel, take: t })} data-reel-play-link="" className={buttonVariants({ variant: "go", size: "sm" })}>
+ Play the reel
+ </Link>
+ <Link href={reelWalkHref(project, { reel, take: t, beat: 1 })} data-reel-walk-link="" className={buttonVariants({ size: "sm" })}>
+ Walk it
+ </Link>
+ <button type="button" data-reel-cut="" disabled={running || !!view.busy || !(view.beats || view.introAsked)} onClick={() => void cut()} className={buttonVariants({ size: "sm" })} title={view.busy ? `the runner is busy: ${view.busy}` : `umtool trailer ${project} --reel ${reel} --take ${t}`}>
+ {running ? "Cutting…" : "Cut the trailer"}
+ </button>
+ {running && (
+ <button type="button" data-reel-cancel="" onClick={() => void cancel()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ )}
+ <span className="text-[var(--color-dim)]">
+ {view.rows?.filter((r) => r.piece).length ?? 0} of {view.beats} beat{view.beats === 1 ? "" : "s"} play from it · {clock(view.total ?? 0)}
+ </span>
+ </>
+ )}
+ {view.busy && !running && <span className="text-[var(--color-dim)]">the runner is busy ({view.busy})</span>}
+ {error && (
+ <span role="alert" data-reel-cut-error="" className="text-[var(--color-bad)]">
+ {error}
+ </span>
+ )}
+ </div>
+ {job && (
+ <div data-reel-job={job.state} className="space-y-1">
+ <p className="m-0 text-[11.5px] text-[var(--color-text)]">
+ {job.state === "running" ? "cutting" : job.state === "done" ? "cut" : `failed${job.error ? `: ${job.error}` : ""}`} — {job.kind}
+ </p>
+ <pre ref={logBox} data-reel-job-log="" className="m-0 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-[var(--color-ink)] px-2 py-1 font-mono text-[10.5px] text-[var(--color-dim)]">
+ {log.join("\n") || "…"}
+ </pre>
+ </div>
+ )}
+ {here && t && (
+ <div data-reel-result={here.take} className="space-y-1">
+ <video key={`${here.take}:${here.mtimeMs}`} controls preload="metadata" src={cutSrc(project, here.take, reel, here.mtimeMs)} className="max-h-[360px] w-full max-w-[640px] rounded bg-black" data-reel-result-video="" />
+ <p className="m-0 text-[11.5px]">
+ <span className="font-mono text-[var(--color-text)]" data-reel-result-path="">
+ {here.out}
+ </span>{" "}
+ <span className="text-[var(--color-dim)]">
+ · {here.seconds !== null ? clock(here.seconds) : "?"} · {fmtBytes(here.size)} · cut {new Date(here.builtAt).toLocaleString()}
+ {here.encodeSeconds !== null ? ` in ${Math.round(here.encodeSeconds)} s` : ""}
+ {here.stale ? " · OLDER than the master (re-rendered since): cut it again" : ""}
+ </span>
+ </p>
+ {here.record && <p className="m-0 font-mono text-[10.5px] text-[var(--color-dim)]">{here.record}</p>}
+ </div>
+ )}
+ {view.cuts.filter((c) => c.take !== t).length > 0 && (
+ <details className="text-[11px]">
+ <summary className="cursor-pointer text-[var(--color-dim)]">earlier cuts of this reel</summary>
+ <ul className="m-0 list-none space-y-0.5 p-0">
+ {view.cuts
+ .filter((c) => c.take !== t)
+ .map((c) => (
+ <li key={c.out} data-reel-earlier={c.take} className="font-mono">
+ {c.take}: {c.out} <span className="text-[var(--color-dim)]">({c.seconds !== null ? clock(c.seconds) : "?"}, {new Date(c.builtAt).toLocaleString()})</span>
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/reel/ReelPlay.tsx b/umtool/components/projects/reel/ReelPlay.tsx
@@ -0,0 +1,553 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedNotes } from "@/components/notes/NotesProvider";
+import { NoteThread } from "@/components/notes/NoteThread";
+import type { CutAsk, Note } from "@/lib/annotations/types";
+import { reelPlayHref, reelWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
+import { cn } from "@/lib/utils";
+import { clock, itemAt, masterOfSource, masterSrc, readReelView, reelItems, sourceClock, sourceOfMaster, type ReelRow, type ReelView } from "./reelTypes";
+import { useReelPlayer } from "./useReelPlayer";
+
+// ---------------------------------------------------------------------------
+// A BEAT REEL'S PLAY VIEW (`/projects/<p>/trailer/play?reel=&take=`, lane
+// beat-reels): the reel's beats played back to back from the chosen take's
+// RENDERED MASTER -- the master's own frames, so the deck's chrome is the
+// final render's and nothing is built (the preview is seeks). Each beat is the
+// span `umtool trailer` cuts (lib/report/reelPlay.mjs, the trailer's own
+// planTrailer, the edges as written), the trailer's crossfade dissolved in the
+// browser (useReelPlayer.ts), the running clock against the platform limit.
+//
+// The Play view's keys: Space play/pause, K pause, N/P the next/previous beat,
+// ←/→ two seconds, [ ] the previous/next note, M a note on the beat on screen,
+// E walk this beat (the bench over it, on the master's frames), ? the keys.
+// A note is anchored to the beat (kind "reel": the reel, the beat, the reel
+// second, the master second, the clip and its source second, the take);
+// `umtool notes <project>` prints it with the writer that acts on it.
+// ---------------------------------------------------------------------------
+
+const SKIP_S = 2;
+const ASKS: { id: CutAsk; label: string; key: string }[] = [
+ { id: "trim", label: "Trim", key: "t" },
+ { id: "cut", label: "Cut", key: "c" },
+ { id: "move", label: "Move", key: "v" },
+ { id: "fact", label: "Fact", key: "f" },
+ { id: "look", label: "Look", key: "l" },
+ { id: "other", label: "Other", key: "o" },
+];
+type ReelAnchor = { kind: "reel"; reel: string; beat: number; t: number; masterT?: number; entry?: string; sourceT?: number; take?: string; ask?: CutAsk };
+
+export default function ReelPlay({ initial, initialBeat = null, initialNote = null }: { initial: ReelView; initialBeat?: number | null; initialNote?: string | null }) {
+ const router = useRouter();
+ const [view, setView] = useState<ReelView>(initial);
+ const [error, setError] = useState<string | null>(null);
+ const project = view.project;
+ const reel = view.reel;
+ const take = view.take?.id ?? null;
+ const items = useMemo(() => reelItems(view), [view]);
+ const vids = useRef<(HTMLVideoElement | null)[]>([null, null]);
+ const player = useReelPlayer(items, view.xfade, vids);
+ const { t, cur, playing } = player;
+ const total = view.total ?? 0;
+ const item = items[cur] ?? null;
+ const row = item?.row ?? null;
+ const [videoSeconds, setVideoSeconds] = useState<number | null>(null);
+
+ const reload = useCallback(async () => {
+ try {
+ setView(await readReelView(project, reel, take));
+ setError(null);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ }, [project, reel, take]);
+
+ // `?beat=n` (the walk's Back to the reel): start on that beat.
+ const started = useRef(false);
+ useEffect(() => {
+ if (started.current || !items.length) return;
+ started.current = true;
+ if (initialBeat) {
+ const it = items.find((x) => x.n === initialBeat);
+ if (it) player.seek(it.at + 0.001);
+ }
+ }, [items, initialBeat, player]);
+
+ const beatIndex = useCallback((d: 1 | -1) => {
+ const e = player.now();
+ const i = e.cur + d;
+ if (d < 0 && items[e.cur] && e.t - items[e.cur].at > 1) return e.cur;
+ return Math.max(0, Math.min(items.length - 1, i));
+ }, [items, player]);
+ const next = useCallback(() => {
+ const i = beatIndex(1);
+ if (items[i]) player.seek(items[i].at + (i > 0 && !items[i].seamless ? view.xfade : 0) + 0.001);
+ }, [beatIndex, items, player, view.xfade]);
+ const prev = useCallback(() => {
+ const i = beatIndex(-1);
+ if (items[i]) player.seek(items[i].at + 0.001);
+ }, [beatIndex, items, player]);
+
+ // ---- the notes ------------------------------------------------------------------
+ const notes = useSharedNotes({ project });
+ const mine = useMemo(
+ () => notes.notes.filter((n) => n.anchor.kind === "reel" && (n.anchor as ReelAnchor).reel === reel),
+ [notes.notes, reel],
+ );
+ /** A note's reel second now: by its clip and source second when a beat still holds it, else by its beat, else its t. */
+ const noteT = useCallback(
+ (a: ReelAnchor) => {
+ if (a.entry && a.sourceT !== undefined) {
+ const it = items.find((x) => {
+ const s = x.row?.id === a.entry ? x.row?.piece?.source : null;
+ return !!s && a.sourceT! >= s.start - 0.05 && a.sourceT! <= s.end + 0.05;
+ });
+ const m = it?.row ? masterOfSource(it.row, a.sourceT) : null;
+ if (it && m !== null) return Math.max(it.at, Math.min(it.at + it.dur, it.at + (m - it.mStart)));
+ }
+ const byBeat = items.find((x) => x.n === a.beat);
+ if (byBeat && a.masterT !== undefined && a.masterT >= byBeat.mStart && a.masterT <= byBeat.mEnd) return byBeat.at + (a.masterT - byBeat.mStart);
+ return byBeat ? byBeat.at : a.t;
+ },
+ [items],
+ );
+ const sorted = useMemo(() => [...mine].sort((a, b) => noteT(a.anchor as ReelAnchor) - noteT(b.anchor as ReelAnchor)), [mine, noteT]);
+ const [drafting, setDrafting] = useState<ReelAnchor | null>(null);
+ const resume = useRef(false);
+ const noteHere = useCallback(() => {
+ const e = player.now();
+ const it = items[e.cur];
+ if (!it?.row) return;
+ resume.current = e.playing;
+ if (e.playing) player.setPlaying(false);
+ const masterT = it.mStart + (e.t - it.at);
+ const src = sourceOfMaster(it.row, masterT);
+ setDrafting({
+ kind: "reel",
+ reel,
+ beat: it.n,
+ t: Math.round(e.t * 100) / 100,
+ masterT: Math.round(masterT * 100) / 100,
+ ...(it.row.id ? { entry: it.row.id } : {}),
+ ...(src !== null ? { sourceT: Math.round(src * 100) / 100 } : {}),
+ ...(take ? { take } : {}),
+ });
+ }, [items, player, reel, take]);
+ const closeDraft = useCallback(() => {
+ setDrafting(null);
+ if (resume.current) {
+ resume.current = false;
+ player.setPlaying(true);
+ }
+ }, [player]);
+ const stepNote = useCallback(
+ (d: 1 | -1) => {
+ const now = player.now().t;
+ const ts = sorted.map((n) => noteT(n.anchor as ReelAnchor));
+ const to = d > 0 ? ts.find((x) => x > now + 0.05) : [...ts].reverse().find((x) => x < now - 0.05);
+ if (to !== undefined) player.seek(to);
+ },
+ [sorted, noteT, player],
+ );
+ const sought = useRef(false);
+ useEffect(() => {
+ if (sought.current || !initialNote) return;
+ const n = mine.find((x) => x.id === initialNote);
+ if (!n) return;
+ sought.current = true;
+ player.seek(noteT(n.anchor as ReelAnchor));
+ }, [initialNote, mine, noteT, player]);
+
+ // ---- walk this beat ---------------------------------------------------------------
+ const walkHere = useCallback(() => {
+ const it = items[player.now().cur];
+ if (!it?.row) return;
+ router.push(reelWalkHref(project, { reel, take, beat: it.n }));
+ }, [items, player, router, project, reel, take]);
+
+ // ---- the keys ----------------------------------------------------------------------
+ const [help, setHelp] = useState(false);
+ useEffect(() => {
+ const onKey = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (ev.key === "Escape") {
+ setHelp(false);
+ return;
+ }
+ if (tgt && (tgt.closest("input, textarea, select, [contenteditable=true]") || ev.metaKey || ev.ctrlKey || ev.altKey)) return;
+ const k = ev.key;
+ if (k === " ") player.setPlaying(!player.now().playing);
+ else if (k === "k" || k === "K") player.setPlaying(false);
+ else if (k === "n" || k === "N") next();
+ else if (k === "p" || k === "P") prev();
+ else if (k === "ArrowRight") player.seek(player.now().t + SKIP_S);
+ else if (k === "ArrowLeft") player.seek(player.now().t - SKIP_S);
+ else if (k === "[") stepNote(-1);
+ else if (k === "]") stepNote(1);
+ else if (k === "m" || k === "M") noteHere();
+ else if (k === "e" || k === "E") walkHere();
+ else if (k === "?") setHelp((h) => !h);
+ else return;
+ ev.preventDefault();
+ };
+ const onUp = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (ev.key === " " && !tgt?.closest("input, textarea, select, [contenteditable=true]")) ev.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("keyup", onUp);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("keyup", onUp);
+ };
+ }, [player, next, prev, stepNote, noteHere, walkHere]);
+
+ // ---- no master: said, and the render offered (never started from here) ----------
+ if (view.noMaster || !take) {
+ return (
+ <main className="deck-main flex-1 space-y-3 p-4" data-reel-play="" data-reel-no-master="">
+ <p data-reel-no-master-why="" className="m-0 text-[13px] text-text">
+ {view.noMaster?.why ?? "no take to play"}
+ </p>
+ <p className="m-0 text-[12px] text-text-2">
+ A reel is cut from a rendered take, so it plays only once one is rendered. Nothing renders from here:{" "}
+ <Link href={takesHref(project)} data-reel-render-link="" className="ink-link">
+ render a take on the Takes page
+ </Link>
+ {view.noMaster?.take ? (
+ <>
+ {" "}
+ (<span className="font-mono">{view.noMaster.take}</span> is the newest), or <code className="font-mono">umtool take {project} --id {view.noMaster.take} --rebuild</code>
+ </>
+ ) : null}
+ , then come back.
+ </p>
+ <Link href={trailerHref(project, { reel })} className="text-[12px] ink-link">
+ ← the reel's beats
+ </Link>
+ </main>
+ );
+ }
+
+ const over = total >= view.limit;
+ const mismatch = videoSeconds !== null && view.masterSeconds !== undefined && Math.abs(videoSeconds - view.masterSeconds) > 0.2;
+ const rows = view.rows ?? [];
+ const unplayable = rows.filter((r) => !r.piece);
+ const masterT = item ? item.mStart + (t - item.at) : 0;
+ const srcNow = row ? sourceOfMaster(row, masterT) : null;
+ const src = masterSrc(project, take, view.take?.masterMtimeMs);
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col lg:grid lg:grid-cols-[minmax(0,1fr)_minmax(300px,26%)]" data-reel-play="" data-reel={reel} data-reel-take={take} data-reel-state={playing ? "playing" : "paused"} data-reel-t={t.toFixed(2)} data-reel-beat={item?.n ?? ""}>
+ <main className="deck-main min-h-0 space-y-2 overflow-y-auto p-4">
+ <div className="relative mx-auto aspect-video w-full max-w-[1100px] overflow-hidden rounded-[3px] bg-black" data-reel-player="">
+ {[0, 1].map((k) => (
+ <video
+ key={k}
+ ref={(el) => {
+ vids.current[k] = el;
+ }}
+ src={src}
+ preload="auto"
+ playsInline
+ data-reel-video={k}
+ onLoadedMetadata={(e) => k === 0 && setVideoSeconds((e.target as HTMLVideoElement).duration)}
+ className="absolute inset-0 h-full w-full object-contain"
+ style={{ opacity: k === 0 ? 1 : 0 }}
+ onClick={() => player.setPlaying(!player.now().playing)}
+ />
+ ))}
+ </div>
+ {/* ---- the transport ---- */}
+ <div className="flex flex-wrap items-center gap-2 text-[12px]">
+ <button type="button" data-reel-prev="" onClick={prev} className={buttonVariants({ variant: "quiet", size: "sm" })} title="P">
+ ‹ prev
+ </button>
+ <button type="button" data-reel-toggle="" onClick={() => player.setPlaying(!playing)} className={buttonVariants({ variant: "go", size: "sm" })} title="Space">
+ {playing ? "Pause" : "Play"}
+ </button>
+ <button type="button" data-reel-next="" onClick={next} className={buttonVariants({ variant: "quiet", size: "sm" })} title="N">
+ next ›
+ </button>
+ <span data-reel-clock="" className={cn("num font-mono text-[14px]", over ? "text-reject-text" : "text-text")}>
+ {clock(t)} / {clock(total)}
+ </span>
+ <span data-reel-limit="" className="text-text-2">
+ limit {clock(view.limit)} · {over ? <b className="text-reject-text">over by {(total - view.limit).toFixed(1)} s</b> : `${(view.limit - total).toFixed(1)} s to spare`} · crossfade {view.xfade} s
+ </span>
+ <span className="ml-auto flex items-center gap-2">
+ <button type="button" data-reel-note="" onClick={noteHere} className={buttonVariants({ size: "sm" })} title="M">
+ Note at {clock(t)}
+ </button>
+ <button type="button" data-reel-walk-here="" onClick={walkHere} disabled={!row} className={buttonVariants({ size: "sm" })} title="E">
+ Walk this beat
+ </button>
+ </span>
+ </div>
+ <ReelStrip items={items} total={total} limit={view.limit} t={t} cur={cur} notes={sorted.map((n) => ({ id: n.id, t: noteT(n.anchor as ReelAnchor) }))} onSeek={player.seek} />
+ {mismatch && (
+ <p role="alert" data-reel-mismatch="" className="m-0 text-[12px] text-reject-text">
+ The master is {videoSeconds?.toFixed(2)} s but its build records describe {view.masterSeconds?.toFixed(2)} s: it is not the build these spans are from (rendered again since?).
+ </p>
+ )}
+ {/* ---- now ---- */}
+ {row ? (
+ <section data-reel-now={row.n} className="space-y-1 rounded-[3px] border border-seam bg-panel px-3 py-2">
+ <p className="m-0 flex flex-wrap items-baseline gap-2 text-[12px]">
+ <span className="font-mono text-text">
+ beat {row.n} · {row.id ?? "master"}
+ </span>
+ {row.verdict && <span data-reel-now-verdict={row.verdict} className="micro">{row.verdict === "confirmed" ? "✓ confirmed" : "noted"}</span>}
+ <span className="num font-mono text-text-2" data-reel-now-source="">
+ {srcNow !== null ? `source ${sourceClock(srcNow)}` : ""} · master {clock(masterT)}
+ </span>
+ {row.date && <span className="text-muted">{row.date}</span>}
+ {row.channel && <span className="text-muted">{row.channel}{row.video ? `/${row.video}` : ""}</span>}
+ </p>
+ {row.quote && <p className="m-0 font-serif text-[14px] leading-snug text-text">“{row.quote}”</p>}
+ </section>
+ ) : item ? (
+ <p className="m-0 text-[12px] text-text-2">the brand intro</p>
+ ) : null}
+ {unplayable.length > 0 && (
+ <section data-reel-unplayable={unplayable.length} className="space-y-0.5 text-[12px] text-reject-text">
+ {unplayable.map((r) => (
+ <p key={r.n} className="m-0">
+ beat {r.n} ({r.id ?? "master"}) does not play from take {take}: {r.problem}
+ </p>
+ ))}
+ </section>
+ )}
+ {error && <p role="alert" className="m-0 text-[12px] text-reject-text">{error}</p>}
+ {help && <KeysHelp />}
+ </main>
+ <aside className="flex min-h-0 flex-col gap-3 overflow-y-auto border-t border-seam p-4 lg:border-l lg:border-t-0" data-reel-side="">
+ <section className="space-y-1 text-[12px]">
+ <p className="m-0 text-text">
+ <span className="font-mono">{reel}</span>
+ {view.title ? ` — ${view.title}` : ""} · {rows.length} beat{rows.length === 1 ? "" : "s"}
+ </p>
+ <label className="flex items-center gap-1 text-text-2">
+ from take
+ <select
+ data-reel-take-pick=""
+ value={take}
+ onChange={(e) => router.push(reelPlayHref(project, { reel, take: e.target.value }))}
+ className="rounded border border-seam-2 bg-ground px-1 py-0.5 font-mono text-[11px] text-text"
+ >
+ {view.takes.filter((x) => x.built || x.id === take).map((x) => (
+ <option key={x.id} value={x.id}>
+ {x.id}
+ {x.rendering ? " (rendering)" : ""}
+ </option>
+ ))}
+ </select>
+ <span className="text-muted">({view.take?.why})</span>
+ </label>
+ <p className="m-0 break-all font-mono text-[11px] text-muted" data-reel-master-path="">
+ {view.take?.master}
+ </p>
+ <p className="m-0 text-[11px] text-text-2">
+ The edges as written; the cut moves each clip beat's into the nearest pause (≤ 1 s), and says so.{" "}
+ <Link href={trailerHref(project, { reel })} className="ink-link" data-reel-beats-link="">
+ Edit the beats · Cut the trailer
+ </Link>
+ </p>
+ </section>
+ <section className="space-y-1.5" data-reel-notes={sorted.length}>
+ <h2 className="micro m-0">notes on this reel — {sorted.length}</h2>
+ {drafting && (
+ <Composer
+ anchor={drafting}
+ busy={notes.busy}
+ onCancel={closeDraft}
+ onSave={async (text, ask) => {
+ const n = await notes.write({ op: "add", text, anchor: { ...drafting, ...(ask ? { ask } : {}) } });
+ if (n) closeDraft();
+ }}
+ />
+ )}
+ {sorted.map((n: Note) => {
+ const a = n.anchor as ReelAnchor;
+ return (
+ <div key={n.id} data-reel-note-row={n.id} className="rounded-[3px] border border-seam px-2 py-1">
+ <NoteThread
+ note={n}
+ write={notes.write}
+ busy={notes.busy}
+ head={
+ <button type="button" onClick={() => player.seek(noteT(a))} className="font-mono text-[11px] text-signal-text">
+ {clock(noteT(a))} · beat {a.beat}
+ {a.entry ? ` · ${a.entry}` : ""}
+ </button>
+ }
+ />
+ </div>
+ );
+ })}
+ <p className="m-0 text-[11px] text-muted">
+ Claude Code reads these with <code className="font-mono text-text-2">umtool notes {project}</code>.
+ </p>
+ </section>
+ {(view.planNotes?.length ?? 0) > 0 && (
+ <section className="space-y-0.5 text-[11px] text-text-2" data-reel-plan-notes="">
+ <h2 className="micro m-0">the mapping says</h2>
+ {view.planNotes!.map((x, i) => (
+ <p key={i} className="m-0">
+ {x}
+ </p>
+ ))}
+ </section>
+ )}
+ <button type="button" onClick={() => void reload()} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Read the reel again
+ </button>
+ </aside>
+ </div>
+ );
+}
+
+/** The reel as film: each beat a cell as long as it plays, the limit, the notes' pins, the playhead. */
+export function ReelStrip({
+ items,
+ total,
+ limit,
+ t,
+ cur,
+ notes,
+ onSeek,
+}: {
+ items: ReturnType<typeof reelItems>;
+ total: number;
+ limit: number;
+ t: number;
+ cur: number;
+ notes: { id: string; t: number }[];
+ onSeek: (t: number) => void;
+}) {
+ const span = Math.max(total, limit) || 1;
+ const pct = (x: number) => `${(Math.max(0, Math.min(span, x)) / span) * 100}%`;
+ return (
+ <div
+ data-reel-strip=""
+ className="relative h-12 w-full cursor-pointer select-none rounded-[3px] border border-seam bg-ground"
+ onClick={(e) => {
+ const r = (e.currentTarget as HTMLDivElement).getBoundingClientRect();
+ onSeek(((e.clientX - r.left) / r.width) * span);
+ }}
+ >
+ {items.map((it, i) => (
+ <div
+ key={it.key}
+ data-reel-cell={it.n}
+ aria-current={i === cur ? "true" : undefined}
+ title={it.row ? `beat ${it.n} · ${it.row.id ?? "master"} · ${it.dur.toFixed(1)} s` : `intro · ${it.dur.toFixed(1)} s`}
+ className={cn(
+ "absolute top-1 bottom-4 overflow-hidden rounded-[2px] border px-1 text-[10px] leading-[1.6]",
+ i === cur ? "border-signal bg-panel-2 text-text" : "border-seam-2 bg-panel text-text-2",
+ it.row?.verdict === "confirmed" && "border-b-2 border-b-[var(--color-ok,#4fbf6a)]",
+ )}
+ style={{ left: pct(it.at), width: `calc(${pct(it.dur)} - 1px)` }}
+ >
+ {it.row ? `${it.n} ${it.row.id ?? ""}` : "intro"}
+ </div>
+ ))}
+ <div data-reel-strip-limit="" className="absolute top-0 bottom-0 w-px bg-reject-text" style={{ left: pct(limit) }} title={`limit ${clock(limit)}`} />
+ {notes.map((n) => (
+ <div key={n.id} data-reel-pin={n.id} className="absolute bottom-0 h-3 w-1.5 -translate-x-1/2 rounded-t-[2px] bg-signal" style={{ left: pct(n.t) }} />
+ ))}
+ <div data-reel-playhead="" className="pointer-events-none absolute top-0 bottom-0 w-0.5 bg-signal" style={{ left: pct(t) }} />
+ </div>
+ );
+}
+
+function KeysHelp() {
+ const rows: [string, string][] = [
+ ["Space", "play / pause"],
+ ["N / P", "next / previous beat"],
+ ["← / →", "2 seconds"],
+ ["[ / ]", "previous / next note"],
+ ["M", "a note on the beat on screen"],
+ ["E", "walk this beat (its edges on the master)"],
+ ];
+ return (
+ <section data-reel-keys="" className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 rounded-[3px] border border-seam px-3 py-2 text-[12px]">
+ {rows.map(([k, v]) => (
+ <span key={k} className="contents">
+ <kbd className="font-mono text-text">{k}</kbd>
+ <span className="text-text-2">{v}</span>
+ </span>
+ ))}
+ </section>
+ );
+}
+
+/** The note being written: where, its words, what it asks for, Save note (the Play view's composer). */
+export function Composer({ anchor, busy, onCancel, onSave }: { anchor: ReelAnchor; busy: boolean; onCancel: () => void; onSave: (text: string, ask: CutAsk | null) => void | Promise<void> }) {
+ const [text, setText] = useState("");
+ const [ask, setAsk] = useState<CutAsk | null>(null);
+ const save = () => {
+ if (text.trim()) void onSave(text, ask);
+ };
+ return (
+ <div className="space-y-1.5" data-reel-composer="">
+ <p className="m-0 font-mono text-[12px] text-text" data-reel-note-at={anchor.t}>
+ Note at {clock(anchor.t)} · beat {anchor.beat}
+ {anchor.entry ? <span className="text-muted"> · {anchor.entry}</span> : null}
+ </p>
+ <textarea
+ autoFocus
+ rows={2}
+ value={text}
+ data-testid="reel-note-input"
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ } else if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
+ e.preventDefault();
+ save();
+ } else if (e.altKey) {
+ const k = ASKS.find((x) => x.key === e.key.toLowerCase() || e.code === `Key${x.key.toUpperCase()}`);
+ if (k) {
+ e.preventDefault();
+ setAsk((c) => (c === k.id ? null : k.id));
+ }
+ }
+ }}
+ placeholder="What to change in this beat"
+ className="block w-full resize-y rounded-[3px] border border-seam-2 bg-ground px-2 py-1.5 text-[13px] text-text outline-none focus:border-signal"
+ />
+ <div className="flex flex-wrap gap-1" role="group" aria-label="What it asks for">
+ {ASKS.map((k) => (
+ <button
+ key={k.id}
+ type="button"
+ aria-pressed={ask === k.id}
+ data-reel-ask={k.id}
+ title={`Alt+${k.key.toUpperCase()}`}
+ onClick={() => setAsk((c) => (c === k.id ? null : k.id))}
+ className={cn("rounded-[2px] border px-1.5 py-px text-[11.5px]", ask === k.id ? "border-text-2 bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text")}
+ >
+ {k.label}
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center gap-2">
+ <button type="button" data-reel-note-save="" disabled={busy || !text.trim()} onClick={save} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Save note
+ </button>
+ <button type="button" onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ <span className="ml-auto text-[11px] text-muted">Enter saves · Esc closes</span>
+ </div>
+ </div>
+ );
+}
+
+export type { ReelAnchor, ReelRow };
diff --git a/umtool/components/projects/reel/ReelPlayPage.tsx b/umtool/components/projects/reel/ReelPlayPage.tsx
@@ -0,0 +1,49 @@
+import { notFound } from "next/navigation";
+import { NotesProvider } from "@/components/notes/NotesProvider";
+import { projectsHref, trailerHref } from "@/lib/hrefs";
+import type { ProjectRef } from "@/lib/project-types";
+import { reelPlayView } from "@/lib/report/reelPlay.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { DEFAULT_REEL, isReelId } from "@/lib/report/trailerBeats.mjs";
+import { BenchFrame, BenchTop } from "../bench/BenchShell";
+import ReelPlay from "./ReelPlay";
+import type { ReelView } from "./reelTypes";
+
+// `/projects/<project>/trailer/play?reel=<name>&take=<t>&beat=<n>` -- a beat
+// reel played from a take's rendered master (ReelPlay.tsx). The server reads
+// the reel on the master (lib/report/reelPlay.mjs); nothing here renders.
+export default async function ReelPlayPage({
+ project,
+ reel = DEFAULT_REEL,
+ take,
+ beat,
+ note,
+}: {
+ project: ProjectRef;
+ reel?: string;
+ take?: string;
+ beat?: string;
+ note?: string;
+}) {
+ const r = reel || DEFAULT_REEL;
+ if (!isReelId(r) || (take && !isTakeId(take))) notFound();
+ const view = (await reelPlayView(project, { reel: r, take: take || null })) as ReelView;
+ return (
+ <BenchFrame
+ kind="reel-play"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "Projects" }]}
+ back={{ href: trailerHref(project.id, { reel: r }), label: `${project.name} · ${r}` }}
+ kind="Play the reel"
+ here={view.take ? `${r} · take ${view.take.id}` : `${r} · no master`}
+ note={view.title ?? undefined}
+ />
+ }
+ >
+ <NotesProvider target={{ project: project.id }}>
+ <ReelPlay key={`${r}:${view.take?.id ?? ""}`} initial={view} initialBeat={Number(beat) > 0 ? Number(beat) : null} initialNote={note ?? null} />
+ </NotesProvider>
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/reel/ReelWalk.tsx b/umtool/components/projects/reel/ReelWalk.tsx
@@ -0,0 +1,459 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedNotes } from "@/components/notes/NotesProvider";
+import { NoteThread } from "@/components/notes/NoteThread";
+import type { Note } from "@/lib/annotations/types";
+import { reelPlayHref, reelWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
+import { cn } from "@/lib/utils";
+import { Composer, type ReelAnchor } from "./ReelPlay";
+import { clock, masterSrc, r2, readReelView, reelWrite, sourceClock, sourceOfMaster, type ReelRow, type ReelView } from "./reelTypes";
+
+// ---------------------------------------------------------------------------
+// A BEAT REEL'S WALK (`/projects/<p>/trailer/walk?reel=&take=&beat=n`, lane
+// beat-reels): the bench over one beat, on the take's RENDERED MASTER -- the
+// final render's frames, the deck's chrome included -- with the clip bench's
+// handles and keys:
+//
+// [ ] the in edge back / forward 0.05 s (Shift: 0.5 s)
+// , . the out edge back / forward 0.05 s (Shift: 0.5 s)
+// I O the in / out edge at the playhead
+// Space play the beat (in to out) / stop
+// Enter save the edges R put them back as saved
+// Y confirm the beat (its edges saved too) and walk on
+// M a note on the beat (its verdict becomes "note")
+// U undo the reel's last write
+// N P the next / previous beat B back to the reel's Play, at this beat
+//
+// A handle is a master second; a clip beat is written in its clip's SOURCE
+// seconds (what promo/<reel>-beats.json holds), mapped back through the take's
+// build record (gaps.mjs sourceAtOffset, the trailer's own mapper). Every save
+// is one write through the beats' one writer (POST /api/report/trailer-beats),
+// and every write an undo point.
+// ---------------------------------------------------------------------------
+
+const STEP = 0.05;
+const BIG = 0.5;
+
+export default function ReelWalk({ initial, beat }: { initial: ReelView; beat: number }) {
+ const router = useRouter();
+ const [view, setView] = useState<ReelView>(initial);
+ const project = view.project;
+ const reel = view.reel;
+ const take = view.take?.id ?? null;
+ const rows = useMemo(() => view.rows ?? [], [view.rows]);
+ const row = rows.find((r) => r.n === beat) ?? null;
+ const idx = row ? rows.indexOf(row) : -1;
+ const prevRow = idx > 0 ? rows[idx - 1] : null;
+ const nextRow = idx >= 0 && idx < rows.length - 1 ? rows[idx + 1] : null;
+ const fps = view.fps ?? 30;
+
+ const saved = useMemo(() => (row?.asked ? { from: row.asked.start, to: row.asked.end } : null), [row?.asked]);
+ const [sel, setSel] = useState<{ from: number; to: number } | null>(saved);
+ const savedKey = `${row?.asked?.start}|${row?.asked?.end}`;
+ useEffect(() => {
+ setSel(saved);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [savedKey, beat]);
+ const [msg, setMsg] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const video = useRef<HTMLVideoElement | null>(null);
+ const [head, setHead] = useState(0);
+ const stopAt = useRef<number | null>(null);
+ const [playing, setPlaying] = useState(false);
+
+ const dirty = !!(sel && row?.asked && (Math.abs(sel.from - row.asked.start) > 0.004 || Math.abs(sel.to - row.asked.end) > 0.004));
+ const lim = row?.limits ?? null;
+
+ /** The visible window: the beat with room either side, inside what its segment plays. */
+ const vis = useMemo(() => {
+ if (!row?.asked || !lim) return { from: 0, to: 1 };
+ // From the SAVED edges only: a window that followed the handle being dragged would move under it.
+ const pad = Math.max(3, (row.asked.end - row.asked.start) * 0.4);
+ const from = Math.max(lim.start, row.asked.start - pad);
+ const to = Math.min(lim.end, row.asked.end + pad);
+ return { from, to: Math.max(to, from + 0.5) };
+ }, [row?.asked, lim]);
+
+ const reload = useCallback(async () => {
+ try {
+ setView(await readReelView(project, reel, take));
+ } catch (e) {
+ setMsg(e instanceof Error ? e.message : String(e));
+ }
+ }, [project, reel, take]);
+
+ const showFrame = useCallback((t: number) => {
+ const v = video.current;
+ if (!v) return;
+ v.pause();
+ setPlaying(false);
+ stopAt.current = null;
+ v.currentTime = Math.max(0, t);
+ setHead(t);
+ }, []);
+
+ const clamp = useCallback(
+ (s: { from: number; to: number }) => {
+ if (!lim) return s;
+ const minLen = 2 / fps;
+ let from = Math.max(lim.start, Math.min(lim.end - minLen, s.from));
+ let to = Math.min(lim.end, Math.max(from + minLen, s.to));
+ from = Math.round(from * 1000) / 1000;
+ to = Math.round(to * 1000) / 1000;
+ return { from, to };
+ },
+ [lim, fps],
+ );
+ const move = useCallback(
+ (which: "from" | "to", to: number) => {
+ setSel((cur) => {
+ if (!cur) return cur;
+ const next = clamp(which === "from" ? { ...cur, from: to } : { ...cur, to });
+ showFrame(which === "from" ? next.from : next.to - 1 / fps);
+ return next;
+ });
+ },
+ [clamp, showFrame, fps],
+ );
+ const nudge = useCallback((which: "from" | "to", by: number) => {
+ setSel((cur) => {
+ if (!cur) return cur;
+ const next = clamp(which === "from" ? { ...cur, from: cur.from + by } : { ...cur, to: cur.to + by });
+ showFrame(which === "from" ? next.from : next.to - 1 / fps);
+ return next;
+ });
+ }, [clamp, showFrame, fps]);
+
+ const playBeat = useCallback(() => {
+ const v = video.current;
+ if (!v || !sel) return;
+ if (!v.paused) {
+ v.pause();
+ setPlaying(false);
+ stopAt.current = null;
+ return;
+ }
+ v.currentTime = sel.from;
+ stopAt.current = sel.to;
+ setPlaying(true);
+ void v.play().catch(() => setPlaying(false));
+ }, [sel]);
+
+ useEffect(() => {
+ let raf = 0;
+ const tick = () => {
+ raf = requestAnimationFrame(tick);
+ const v = video.current;
+ if (!v) return;
+ setHead(v.currentTime);
+ if (stopAt.current !== null && v.currentTime >= stopAt.current) {
+ v.pause();
+ stopAt.current = null;
+ setPlaying(false);
+ }
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, []);
+
+ // ---- the writes ---------------------------------------------------------------------
+ const write = useCallback(
+ async (op: string, args: Record<string, unknown>, said: string) => {
+ setBusy(true);
+ setMsg(null);
+ try {
+ const r = await reelWrite(project, reel, view.token, op, args);
+ if (!r.ok) {
+ setMsg(r.error);
+ if (r.stale) await reload();
+ return false;
+ }
+ setMsg(r.undone ? `undone: ${r.undone}` : said);
+ await reload();
+ return true;
+ } finally {
+ setBusy(false);
+ }
+ },
+ [project, reel, view.token, reload],
+ );
+ const edgesPatch = useCallback(() => {
+ if (!row || !sel) return null;
+ if (row.kind === "clip") {
+ const a = sourceOfMaster(row, sel.from);
+ const b = sourceOfMaster(row, sel.to, "end");
+ if (a === null || b === null) return null;
+ return { start: r2(a), end: r2(b) };
+ }
+ return { at: r2(sel.from), dur: r2(sel.to - sel.from) };
+ }, [row, sel]);
+ const save = useCallback(async () => {
+ const p = edgesPatch();
+ if (!row || !p || !dirty) return true;
+ return write("set", { index: row.n - 1, patch: p }, `saved — beat ${row.n} ${"start" in p ? `${p.start}–${p.end}` : `at ${p.at} for ${p.dur} s`} (U undoes it)`);
+ }, [edgesPatch, row, dirty, write]);
+ const confirm = useCallback(async () => {
+ if (!row) return;
+ const p = dirty ? edgesPatch() : null;
+ const ok = await write("set", { index: row.n - 1, patch: { ...(p ?? {}), verdict: "confirmed" } }, `beat ${row.n} confirmed`);
+ if (ok && nextRow) router.push(reelWalkHref(project, { reel, take, beat: nextRow.n }));
+ }, [row, dirty, edgesPatch, write, nextRow, router, project, reel, take]);
+ const clearVerdict = useCallback(() => row && void write("set", { index: row.n - 1, patch: { verdict: null } }, `beat ${row.n}: verdict cleared`), [row, write]);
+ const undo = useCallback(() => void write("undo", {}, "undone"), [write]);
+
+ // ---- notes ---------------------------------------------------------------------------
+ const notes = useSharedNotes({ project });
+ const mine = useMemo(
+ () => notes.notes.filter((n) => n.anchor.kind === "reel" && (n.anchor as ReelAnchor).reel === reel && (row?.id ? (n.anchor as ReelAnchor).entry === row.id || (n.anchor as ReelAnchor).beat === row.n : (n.anchor as ReelAnchor).beat === beat)),
+ [notes.notes, reel, row?.id, row?.n, beat],
+ );
+ const [drafting, setDrafting] = useState<ReelAnchor | null>(null);
+ const noteHere = useCallback(() => {
+ if (!row) return;
+ const v = video.current;
+ const m = v ? v.currentTime : (sel?.from ?? 0);
+ const src = sourceOfMaster(row, m);
+ const at = row.piece ? row.piece.at + Math.max(0, m - row.piece.master.start) : 0;
+ setDrafting({ kind: "reel", reel, beat: row.n, t: r2(at), masterT: r2(m), ...(row.id ? { entry: row.id } : {}), ...(src !== null ? { sourceT: r2(src) } : {}), ...(take ? { take } : {}) });
+ }, [row, sel?.from, reel, take]);
+
+ const goBack = useCallback(() => router.push(reelPlayHref(project, { reel, take, beat })), [router, project, reel, take, beat]);
+
+ // ---- keys ------------------------------------------------------------------------------
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement | null;
+ if (el && el.closest("input, textarea, select, [contenteditable=true]")) return;
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
+ const step = e.shiftKey ? BIG : STEP;
+ switch (e.key) {
+ case "[":
+ case "{": nudge("from", -step); break;
+ case "]":
+ case "}": nudge("from", step); break;
+ case ",":
+ case "<": nudge("to", -step); break;
+ case ".":
+ case ">": nudge("to", step); break;
+ case "i":
+ case "I": move("from", video.current?.currentTime ?? 0); break;
+ case "o":
+ case "O": move("to", video.current?.currentTime ?? 0); break;
+ case " ": playBeat(); break;
+ case "Enter": void save(); break;
+ case "r":
+ case "R": setSel(saved); break;
+ case "y":
+ case "Y": void confirm(); break;
+ case "m":
+ case "M": noteHere(); break;
+ case "u":
+ case "U": undo(); break;
+ case "b":
+ case "B": goBack(); break;
+ case "n":
+ case "N": if (nextRow) router.push(reelWalkHref(project, { reel, take, beat: nextRow.n })); break;
+ case "p":
+ case "P": if (prevRow) router.push(reelWalkHref(project, { reel, take, beat: prevRow.n })); break;
+ default: return;
+ }
+ e.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [nudge, move, playBeat, save, saved, confirm, noteHere, undo, goBack, nextRow, prevRow, router, project, reel, take]);
+
+ if (view.noMaster || !take) {
+ return (
+ <main className="deck-main flex-1 space-y-2 p-4" data-reel-walk="" data-reel-no-master="">
+ <p className="m-0 text-[13px] text-text" data-reel-no-master-why="">{view.noMaster?.why ?? "no take to walk"}</p>
+ <Link href={takesHref(project)} className="text-[12px] ink-link" data-reel-render-link="">
+ render a take on the Takes page
+ </Link>
+ </main>
+ );
+ }
+ if (!row) {
+ return (
+ <main className="deck-main flex-1 p-4" data-reel-walk="">
+ <p className="m-0 text-[13px] text-text">The reel {reel} has no beat {beat}. <Link href={trailerHref(project, { reel })} className="ink-link">Its beats</Link></p>
+ </main>
+ );
+ }
+
+ const pct = (x: number) => `${((Math.max(vis.from, Math.min(vis.to, x)) - vis.from) / (vis.to - vis.from)) * 100}%`;
+ const srcFrom = sel ? sourceOfMaster(row, sel.from) : null;
+ const srcTo = sel ? sourceOfMaster(row, sel.to, "end") : null;
+ const srcHead = sourceOfMaster(row, head);
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col lg:grid lg:grid-cols-[minmax(0,1fr)_minmax(300px,26%)]" data-reel-walk="" data-reel={reel} data-reel-take={take} data-reel-beat={row.n} data-reel-dirty={dirty ? "1" : "0"} data-reel-verdict={row.verdict ?? ""}>
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <main className="deck-main min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
+ <div className="relative mx-auto aspect-video w-full max-w-[1000px] overflow-hidden rounded-[3px] bg-black">
+ <video
+ ref={video}
+ src={masterSrc(project, take, view.take?.masterMtimeMs)}
+ preload="auto"
+ playsInline
+ data-reel-walk-video=""
+ onLoadedMetadata={() => sel && showFrame(sel.from)}
+ className="absolute inset-0 h-full w-full object-contain"
+ />
+ </div>
+ {/* ---- the edges on the master ---- */}
+ <div
+ data-reel-track=""
+ className="relative h-14 w-full select-none rounded-[3px] border border-seam bg-ground"
+ onClick={(e) => {
+ if ((e.target as HTMLElement).closest("[data-reel-handle]")) return;
+ const r = (e.currentTarget as HTMLDivElement).getBoundingClientRect();
+ showFrame(vis.from + ((e.clientX - r.left) / r.width) * (vis.to - vis.from));
+ }}
+ >
+ {row.piece && (
+ <div
+ data-reel-played=""
+ title="what the cut plays: the master's crossfades kept out"
+ className="absolute top-8 bottom-1 rounded-[2px] bg-panel-2"
+ style={{ left: pct(row.piece.master.start), width: `calc(${pct(row.piece.master.end)} - ${pct(row.piece.master.start)})` }}
+ />
+ )}
+ {sel && (
+ <div
+ data-reel-sel=""
+ className={cn("absolute top-1 bottom-7 rounded-[2px] border", dirty ? "border-[var(--color-dirty,#e0a020)] bg-[var(--color-dirty,#e0a020)]/15" : "border-signal bg-signal/15")}
+ style={{ left: pct(sel.from), width: `calc(${pct(sel.to)} - ${pct(sel.from)})` }}
+ />
+ )}
+ {sel &&
+ (["from", "to"] as const).map((which) => (
+ <Handle key={which} which={which} at={which === "from" ? sel.from : sel.to} pct={pct} vis={vis} onMove={(t) => move(which, t)} />
+ ))}
+ <div data-reel-walk-head="" className="pointer-events-none absolute top-0 bottom-0 w-0.5 bg-text" style={{ left: pct(head) }} />
+ </div>
+ <div className="flex flex-wrap items-center gap-2 text-[12px]">
+ <span className="num font-mono text-text" data-reel-edges="">
+ in {clock(sel?.from)} · out {clock(sel?.to)} · {sel ? (sel.to - sel.from).toFixed(2) : "—"} s (master)
+ </span>
+ {row.kind === "clip" && (
+ <span className="num font-mono text-text-2" data-reel-source-edges="">
+ source {sourceClock(srcFrom)} – {sourceClock(srcTo)}
+ </span>
+ )}
+ <span className="num font-mono text-muted" data-reel-head="">
+ ▸ {clock(head)}{srcHead !== null ? ` · source ${sourceClock(srcHead)}` : ""}
+ </span>
+ {dirty && <b className="text-[var(--color-dirty,#e0a020)]">unsaved — Enter saves, R puts back</b>}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" data-reel-play-beat="" onClick={playBeat} className={buttonVariants({ size: "sm" })}>
+ {playing ? "Stop" : "Play the beat"}
+ </button>
+ <button type="button" data-reel-save="" disabled={!dirty || busy} onClick={() => void save()} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Save edges
+ </button>
+ <button type="button" data-reel-reset="" disabled={!dirty} onClick={() => setSel(saved)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Put back
+ </button>
+ <button type="button" data-reel-undo="" disabled={busy} onClick={undo} className={buttonVariants({ variant: "quiet", size: "sm" })} title="U: the reel as it was before its last write">
+ Undo last write
+ </button>
+ {msg && <span data-reel-msg="" className="text-[12px] text-text-2">{msg}</span>}
+ </div>
+ <section className="space-y-1 rounded-[3px] border border-seam bg-panel px-3 py-2" data-reel-beat-quote="">
+ <p className="m-0 flex flex-wrap items-baseline gap-2 text-[12px]">
+ <span className="font-mono text-text">beat {row.n} · {row.id ?? "master"}</span>
+ {row.date && <span className="text-muted">{row.date}</span>}
+ {row.channel && <span className="text-muted">{row.channel}{row.video ? `/${row.video}` : ""}</span>}
+ {row.limits?.source && <span className="text-muted">its segment plays source {sourceClock(row.limits.source.start)}–{sourceClock(row.limits.source.end)}</span>}
+ </p>
+ {row.quote && <p className="m-0 font-serif text-[14px] leading-snug text-text">“{row.quote}”</p>}
+ {row.problem && <p className="m-0 text-[12px] text-reject-text">{row.problem}</p>}
+ </section>
+ <p className="m-0 text-[11px] text-muted">
+ [ ] in · , . out (Shift 0.5 s) · I O at the playhead · Space plays the beat · Enter saves · Y confirms · M notes · U undoes · N P beats · B back to the reel
+ </p>
+ </main>
+ {/* ---- the verdict ---- */}
+ <div data-verdict-bar="" className="flex shrink-0 flex-wrap items-center gap-2 border-t border-seam bg-ground px-4 pb-3 pt-2.5">
+ <p className="m-0 basis-full text-[14px] text-text">
+ Is beat {row.n} right as the trailer plays it? <b className="font-semibold">Confirm writes its edges and walks on.</b>
+ {row.verdict && <span className="ml-2 text-[12px] text-text-2" data-reel-verdict-now={row.verdict}>now: {row.verdict === "confirmed" ? "✓ confirmed" : "noted"}</span>}
+ </p>
+ <button type="button" data-reel-confirm="" disabled={busy} onClick={() => void confirm()} className={buttonVariants({ variant: "go", size: "md" })}>
+ Confirm (Y)
+ </button>
+ <button type="button" data-reel-note-beat="" onClick={noteHere} className={buttonVariants({ size: "md" })}>
+ Note (M)
+ </button>
+ {row.verdict && (
+ <button type="button" data-reel-clear-verdict="" disabled={busy} onClick={clearVerdict} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Clear verdict
+ </button>
+ )}
+ <span className="ml-auto flex items-center gap-2 text-[12px]">
+ {prevRow && <Link href={reelWalkHref(project, { reel, take, beat: prevRow.n })} data-reel-walk-prev="" className="ink-link">‹ beat {prevRow.n}</Link>}
+ <Link href={reelPlayHref(project, { reel, take, beat: row.n })} data-reel-back="" className="ink-link">Back to the reel (B)</Link>
+ {nextRow && <Link href={reelWalkHref(project, { reel, take, beat: nextRow.n })} data-reel-walk-next="" className="ink-link">beat {nextRow.n} ›</Link>}
+ </span>
+ </div>
+ </div>
+ <aside className="flex min-h-0 flex-col gap-2 overflow-y-auto border-t border-seam p-4 lg:border-l lg:border-t-0">
+ <h2 className="micro m-0">notes on beat {row.n} — {mine.length}</h2>
+ {drafting && (
+ <Composer
+ anchor={drafting}
+ busy={notes.busy || busy}
+ onCancel={() => setDrafting(null)}
+ onSave={async (text, ask) => {
+ const n = await notes.write({ op: "add", text, anchor: { ...drafting, ...(ask ? { ask } : {}) } });
+ if (!n) return;
+ setDrafting(null);
+ if (row.verdict !== "confirmed") await write("set", { index: row.n - 1, patch: { verdict: "note" } }, `noted beat ${row.n}`);
+ }}
+ />
+ )}
+ {mine.map((n: Note) => (
+ <div key={n.id} data-reel-note-row={n.id} className="rounded-[3px] border border-seam px-2 py-1">
+ <NoteThread note={n} write={notes.write} busy={notes.busy} head={<span className="font-mono text-[11px] text-muted">beat {(n.anchor as ReelAnchor).beat}</span>} />
+ </div>
+ ))}
+ <p className="m-0 break-all font-mono text-[11px] text-muted">{view.file} · take {take}</p>
+ </aside>
+ </div>
+ );
+}
+
+function Handle({ which, at, pct, vis, onMove }: { which: "from" | "to"; at: number; pct: (x: number) => string; vis: { from: number; to: number }; onMove: (t: number) => void }) {
+ const drag = useRef<{ rect: DOMRect } | null>(null);
+ return (
+ <div
+ role="slider"
+ aria-label={which === "from" ? "in edge" : "out edge"}
+ aria-valuenow={Number(at.toFixed(2))}
+ data-reel-handle={which}
+ tabIndex={0}
+ className="absolute top-0 bottom-6 z-10 w-2.5 -translate-x-1/2 cursor-ew-resize rounded-[2px] bg-signal"
+ style={{ left: pct(at) }}
+ onPointerDown={(e) => {
+ const track = (e.currentTarget.parentElement as HTMLDivElement).getBoundingClientRect();
+ drag.current = { rect: track };
+ e.currentTarget.setPointerCapture(e.pointerId);
+ }}
+ onPointerMove={(e) => {
+ if (!drag.current) return;
+ const r = drag.current.rect;
+ onMove(vis.from + ((e.clientX - r.left) / r.width) * (vis.to - vis.from));
+ }}
+ onPointerUp={(e) => {
+ drag.current = null;
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ }}
+ />
+ );
+}
diff --git a/umtool/components/projects/reel/ReelWalkPage.tsx b/umtool/components/projects/reel/ReelWalkPage.tsx
@@ -0,0 +1,53 @@
+import { notFound } from "next/navigation";
+import { NotesProvider } from "@/components/notes/NotesProvider";
+import { projectsHref, reelPlayHref, reelWalkHref } from "@/lib/hrefs";
+import type { ProjectRef } from "@/lib/project-types";
+import { reelPlayView } from "@/lib/report/reelPlay.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { DEFAULT_REEL, isReelId } from "@/lib/report/trailerBeats.mjs";
+import { BenchFrame, BenchTop } from "../bench/BenchShell";
+import ReelWalk from "./ReelWalk";
+import type { ReelView } from "./reelTypes";
+
+// `/projects/<project>/trailer/walk?reel=<name>&take=<t>&beat=<n>` -- the
+// bench over one beat of a reel, on the take's rendered master (ReelWalk.tsx).
+export default async function ReelWalkPage({
+ project,
+ reel = DEFAULT_REEL,
+ take,
+ beat,
+}: {
+ project: ProjectRef;
+ reel?: string;
+ take?: string;
+ beat?: string;
+}) {
+ const r = reel || DEFAULT_REEL;
+ if (!isReelId(r) || (take && !isTakeId(take))) notFound();
+ const n = Number(beat) > 0 ? Math.floor(Number(beat)) : 1;
+ const view = (await reelPlayView(project, { reel: r, take: take || null })) as ReelView;
+ const rows = view.rows ?? [];
+ const i = rows.findIndex((x) => x.n === n);
+ const t = view.take?.id ?? null;
+ return (
+ <BenchFrame
+ kind="reel-walk"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "Projects" }]}
+ back={{ href: reelPlayHref(project.id, { reel: r, take: t, beat: n }), label: `${project.name} · ${r}` }}
+ kind="Reel walk"
+ here={`beat ${n}${rows[i]?.id ? ` · ${rows[i].id}` : ""}`}
+ pos={i >= 0 ? { index: i + 1, total: rows.length, of: "beats" } : null}
+ prev={i > 0 ? { href: reelWalkHref(project.id, { reel: r, take: t, beat: rows[i - 1].n }), label: `beat ${rows[i - 1].n}` } : null}
+ next={i >= 0 && i < rows.length - 1 ? { href: reelWalkHref(project.id, { reel: r, take: t, beat: rows[i + 1].n }), label: `beat ${rows[i + 1].n}` } : null}
+ note={view.take ? `take ${view.take.id} · ${rows.filter((x) => x.verdict === "confirmed").length} of ${rows.length} confirmed` : "no master"}
+ />
+ }
+ >
+ <NotesProvider target={{ project: project.id }}>
+ <ReelWalk key={`${r}:${t ?? ""}:${n}`} initial={view} beat={n} />
+ </NotesProvider>
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/reel/reelTypes.ts b/umtool/components/projects/reel/reelTypes.ts
@@ -0,0 +1,180 @@
+// What a beat reel's Play view, walk and Cut panel read: GET /api/report/reel
+// (lib/report/reelPlay.mjs reelPlayView, plus the reels and the cut job).
+// Types and pure helpers only, so a client and a server page both import it.
+import { sourceAtOffset, offsetIn } from "umtool-report-to-video/gaps";
+
+export type ReelPiece = {
+ at: number;
+ master: { start: number; end: number; duration: number };
+ frames: { start: number; count: number };
+ seamless: boolean;
+ moved: unknown;
+ source: { start: number; end: number } | null;
+};
+
+export type ReelRow = {
+ n: number;
+ kind: "clip" | "raw";
+ id: string | null;
+ label: string | null;
+ verdict: "confirmed" | "note" | null;
+ beat: { start?: number; end?: number; at?: number; dur?: number };
+ problem: string | null;
+ piece: ReelPiece | null;
+ asked: { start: number; end: number } | null;
+ limits: { start: number; end: number; source: { start: number; end: number } | null } | null;
+ map: { segStart: number; recStart: number; gaps: { from: number; to: number }[] } | null;
+ quote: string | null;
+ title: string | null;
+ channel: string | null;
+ video: string | null;
+ date: string | null;
+};
+
+export type ReelCut = {
+ take: string;
+ out: string;
+ size: number;
+ mtimeMs: number;
+ record: string | null;
+ builtAt: string;
+ seconds: number | null;
+ encodeSeconds: number | null;
+ notes: number;
+ stale: boolean;
+};
+
+export type ReelJob = {
+ id: string;
+ kind: string;
+ state: "running" | "done" | "failed";
+ startedAt: number;
+ endedAt: number | null;
+ error: string | null;
+ log: string[];
+ next: number;
+};
+
+export type ReelListing = { name: string; file: string; exists: boolean; beats: number; title: string | null; limit: number; take: string | null; error: string | null };
+
+export type ReelView = {
+ project: string;
+ reel: string;
+ file: string;
+ title: string | null;
+ limit: number;
+ xfade: number;
+ introAsked: boolean;
+ pinned: string | null;
+ token: string | null;
+ beats: number;
+ takes: { id: string; label: string; built: boolean; rendering: boolean; draft: boolean; master: string | null; masterMtimeMs: number | null }[];
+ cuts: ReelCut[];
+ take: { id: string; why: string; label: string; slug?: string; master?: string; masterMtimeMs?: number | null; rendering?: boolean } | null;
+ noMaster: { why: string; take: string | null } | null;
+ fps?: number;
+ transition?: number;
+ masterSeconds?: number;
+ intro?: { at: number; master: { start: number; end: number; duration: number } } | null;
+ total?: number;
+ rows?: ReelRow[];
+ planNotes?: string[];
+ reels?: ReelListing[];
+ job?: ReelJob | null;
+ busy?: string | null;
+ error?: string;
+};
+
+/** One run of the master the player plays: the intro, or a beat that maps. */
+export type ReelItem = { key: string; n: number; at: number; mStart: number; mEnd: number; dur: number; seamless: boolean; row: ReelRow | null };
+
+/** The pieces in reel order. */
+export function reelItems(view: ReelView): ReelItem[] {
+ const out: ReelItem[] = [];
+ if (view.intro) out.push({ key: "intro", n: 0, at: view.intro.at, mStart: view.intro.master.start, mEnd: view.intro.master.end, dur: view.intro.master.duration, seamless: false, row: null });
+ for (const r of view.rows ?? []) {
+ if (!r.piece) continue;
+ out.push({ key: `b${r.n}`, n: r.n, at: r.piece.at, mStart: r.piece.master.start, mEnd: r.piece.master.end, dur: r.piece.master.duration, seamless: r.piece.seamless, row: r });
+ }
+ return out;
+}
+
+/** The item playing at reel second t: the last one started by then. */
+export function itemAt(items: ReelItem[], t: number): number {
+ let k = 0;
+ for (let i = 0; i < items.length; i += 1) if (items[i].at <= t + 1e-6) k = i;
+ return k;
+}
+
+/**
+ * A master second as the source second it plays (a clip beat), through the
+ * build record's gaps -- gaps.mjs, the cut's own mapper. At a gap's join the
+ * master shows the material AFTER the gap, which is where a START edge there
+ * begins; an END edge there ends the material BEFORE it (`edge: "end"`: the
+ * gap's own start), or a round trip would stretch the beat across the gap.
+ */
+export function sourceOfMaster(row: ReelRow, masterT: number, edge: "start" | "end" = "start"): number | null {
+ if (!row.map) return null;
+ const off = masterT - row.map.segStart;
+ if (edge === "end" && off > 0.002) return sourceAtOffset(off - 0.002, row.map.recStart, row.map.gaps) + 0.002;
+ return sourceAtOffset(off, row.map.recStart, row.map.gaps);
+}
+
+/** A source second as the master second it plays at. */
+export function masterOfSource(row: ReelRow, src: number): number | null {
+ if (!row.map) return null;
+ return row.map.segStart + offsetIn(src, row.map.recStart, row.map.gaps);
+}
+
+export const r2 = (n: number) => Math.round(n * 100) / 100;
+
+/** m:ss.s */
+export function clock(s: number | null | undefined): string {
+ if (s == null || !Number.isFinite(s)) return "—";
+ const neg = s < 0;
+ const a = Math.abs(s);
+ const m = Math.floor(a / 60);
+ const r = a - m * 60;
+ return `${neg ? "−" : ""}${m}:${r < 10 ? "0" : ""}${r.toFixed(1)}`;
+}
+
+/** h:mm:ss.s for a source second (a stream is hours long). */
+export function sourceClock(s: number | null | undefined): string {
+ if (s == null || !Number.isFinite(s)) return "—";
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s - h * 3600) / 60);
+ const r = s - h * 3600 - m * 60;
+ return `${h ? `${h}:` : ""}${h && m < 10 ? "0" : ""}${m}:${r < 10 ? "0" : ""}${r.toFixed(2)}`;
+}
+
+export const masterSrc = (project: string, take: string, mtime: number | null | undefined) =>
+ `/api/report/reel/media?${new URLSearchParams({ project, take, what: "master", ...(mtime ? { v: String(mtime) } : {}) })}`;
+export const cutSrc = (project: string, take: string, reel: string, mtime: number | null | undefined) =>
+ `/api/report/reel/media?${new URLSearchParams({ project, take, what: "cut", reel, ...(mtime ? { v: String(mtime) } : {}) })}`;
+
+/** GET the reel's view. */
+export async function readReelView(project: string, reel: string, take: string | null): Promise<ReelView> {
+ const q = new URLSearchParams({ project, reel, ...(take ? { take } : {}) });
+ const r = await fetch(`/api/report/reel?${q}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as ReelView;
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ return j;
+}
+
+/** One write to the reel's beats through their one writer (POST /api/report/trailer-beats). */
+export async function reelWrite(
+ project: string,
+ reel: string,
+ token: string | null,
+ op: string,
+ args: Record<string, unknown> = {},
+): Promise<{ ok: true; token: string | null; undone?: string } | { ok: false; error: string; stale: boolean }> {
+ const r = await fetch("/api/report/trailer-beats", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, reel, token, op, ...args }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) return { ok: false, error: j.stale ? "the reel changed since this page read it — read again; try again" : String(j.error ?? `HTTP ${r.status}`), stale: !!j.stale };
+ return { ok: true, token: j.token ?? null, ...(j.undone ? { undone: j.undone } : {}) };
+}
diff --git a/umtool/components/projects/reel/useReelPlayer.ts b/umtool/components/projects/reel/useReelPlayer.ts
@@ -0,0 +1,216 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { itemAt, type ReelItem } from "./reelTypes";
+
+// THE REEL'S PLAYER: a reel's runs of the master played back to back on one
+// reel clock, the trailer's crossfades previewed. Two <video> elements on the
+// same master take turns: while one plays a run, the other waits seeked to the
+// next one's first frame; at the join it starts and fades up over the reel's
+// crossfade (picture by opacity, sound by volume) -- the dissolve the cut
+// encodes. A SEAMLESS piece (the plan's: the master plays on from the one
+// before) stays on the same element, so its frames follow with no seek.
+//
+// The clock is the active element's currentTime mapped through its run:
+// t = item.at + (currentTime − item.mStart). Nothing is decoded here that the
+// browser does not: it is seeks of one file.
+
+export type ReelPlayer = {
+ t: number;
+ cur: number;
+ playing: boolean;
+ /** Which element shows run `i` (0 or 1). */
+ laneOf: (i: number) => 0 | 1;
+ setPlaying: (on: boolean) => void;
+ seek: (t: number) => void;
+ /** The live clock, read without waiting for a render. */
+ now: () => { t: number; cur: number; playing: boolean };
+ /** Play [from, to) of reel time and stop (a beat's audition). */
+ playSpan: (from: number, to: number) => void;
+};
+
+export function useReelPlayer(items: ReelItem[], xfade: number, vids: React.RefObject<(HTMLVideoElement | null)[]>): ReelPlayer {
+ const [ui, setUi] = useState({ t: 0, cur: 0, playing: false });
+ const live = useRef({ t: 0, cur: 0, playing: false, stopAt: null as number | null });
+ const lanes = useMemo(() => {
+ const out: (0 | 1)[] = [];
+ items.forEach((it, i) => {
+ out.push(i === 0 ? 0 : it.seamless ? out[i - 1] : out[i - 1] === 0 ? 1 : 0);
+ });
+ return out;
+ }, [items]);
+ const laneOf = useCallback((i: number) => lanes[i] ?? 0, [lanes]);
+ const total = items.length ? items[items.length - 1].at + items[items.length - 1].dur : 0;
+
+ const el = useCallback((i: number) => vids.current?.[lanes[i] ?? 0] ?? null, [vids, lanes]);
+ const show = useCallback(
+ (cur: number, incoming: number | null, p: number) => {
+ const vs = vids.current ?? [];
+ const a = lanes[cur] ?? 0;
+ for (let k = 0; k < 2; k += 1) {
+ const v = vs[k];
+ if (!v) continue;
+ if (k === a) {
+ v.style.opacity = "1";
+ v.style.zIndex = "1";
+ v.volume = Math.max(0, Math.min(1, incoming === null ? 1 : 1 - p));
+ } else if (incoming !== null && lanes[incoming] === k) {
+ v.style.opacity = String(Math.max(0, Math.min(1, p)));
+ v.style.zIndex = "2";
+ v.volume = Math.max(0, Math.min(1, p));
+ } else {
+ v.style.opacity = "0";
+ v.style.zIndex = "0";
+ }
+ }
+ },
+ [vids, lanes],
+ );
+ /** Seek the element of run `i` to reel second t inside it. */
+ const place = useCallback(
+ (i: number, t: number) => {
+ const it = items[i];
+ const v = el(i);
+ if (!it || !v) return;
+ const want = it.mStart + Math.max(0, Math.min(it.dur, t - it.at));
+ if (Math.abs(v.currentTime - want) > 0.04) v.currentTime = want;
+ },
+ [items, el],
+ );
+ /** The next run, waiting on its own element at its first frame. */
+ const cue = useCallback(
+ (i: number) => {
+ const nx = items[i + 1];
+ if (!nx || nx.seamless) return;
+ const v = el(i + 1);
+ if (!v) return;
+ v.pause();
+ if (Math.abs(v.currentTime - nx.mStart) > 0.04) v.currentTime = nx.mStart;
+ },
+ [items, el],
+ );
+
+ const publish = useCallback(() => setUi({ t: live.current.t, cur: live.current.cur, playing: live.current.playing }), []);
+
+ const seek = useCallback(
+ (t: number) => {
+ if (!items.length) return;
+ const tt = Math.max(0, Math.min(total, t));
+ const i = itemAt(items, tt);
+ live.current.t = tt;
+ live.current.cur = i;
+ for (const v of vids.current ?? []) v?.pause();
+ place(i, tt);
+ cue(i);
+ show(i, null, 0);
+ if (live.current.playing) void el(i)?.play().catch(() => {});
+ publish();
+ },
+ [items, total, place, cue, show, el, vids, publish],
+ );
+
+ const setPlaying = useCallback(
+ (on: boolean) => {
+ if (!items.length) return;
+ live.current.playing = on;
+ if (!on) {
+ live.current.stopAt = null;
+ for (const v of vids.current ?? []) v?.pause();
+ } else {
+ if (live.current.t >= total - 0.05) seek(0);
+ const i = live.current.cur;
+ place(i, live.current.t);
+ void el(i)?.play().catch(() => {
+ live.current.playing = false;
+ publish();
+ });
+ }
+ publish();
+ },
+ [items, total, vids, place, el, seek, publish],
+ );
+
+ const playSpan = useCallback(
+ (from: number, to: number) => {
+ live.current.stopAt = to;
+ seek(from);
+ live.current.playing = true;
+ void el(itemAt(items, from))?.play().catch(() => {});
+ publish();
+ live.current.stopAt = to;
+ },
+ [seek, el, items, publish],
+ );
+
+ // The loop: the clock from the active element, the join and its crossfade.
+ useEffect(() => {
+ let raf = 0;
+ let last = 0;
+ const tick = (ms: number) => {
+ raf = requestAnimationFrame(tick);
+ const L = live.current;
+ if (!L.playing || !items.length) return;
+ const i = L.cur;
+ const it = items[i];
+ const v = el(i);
+ if (!it || !v) return;
+ let t = it.at + (v.currentTime - it.mStart);
+ const nx = items[i + 1];
+ // Past the run's end (or the element stopped at the file's end): the next run is current.
+ if (v.currentTime >= it.mEnd - 1e-3 || v.ended) {
+ if (!nx) {
+ L.playing = false;
+ L.t = total;
+ v.pause();
+ publish();
+ return;
+ }
+ L.cur = i + 1;
+ const nv = el(i + 1);
+ if (nx.seamless) {
+ // The same element plays on into it.
+ } else if (nv) {
+ if (nv.paused) {
+ place(i + 1, Math.max(nx.at, t));
+ void nv.play().catch(() => {});
+ }
+ v.pause();
+ }
+ cue(i + 1);
+ show(i + 1, null, 0);
+ t = Math.max(t, nx.at);
+ } else if (nx && !nx.seamless && t >= nx.at - 1e-3) {
+ // Inside the crossfade: the next run started, fading up over the reel's xfade.
+ const nv = el(i + 1);
+ if (nv && nv.paused) {
+ place(i + 1, t);
+ void nv.play().catch(() => {});
+ }
+ show(i, i + 1, xfade > 0 ? (t - nx.at) / xfade : 1);
+ } else show(i, null, 0);
+ L.t = Math.max(0, t);
+ if (L.stopAt !== null && L.t >= L.stopAt) {
+ L.stopAt = null;
+ L.playing = false;
+ for (const x of vids.current ?? []) x?.pause();
+ publish();
+ return;
+ }
+ if (ms - last > 90) {
+ last = ms;
+ publish();
+ }
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [items, xfade, total, el, place, cue, show, vids, publish]);
+
+ // A new reel (a write, another take): back to where the clock was, on the new runs.
+ useEffect(() => {
+ seek(Math.min(live.current.t, total));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [items]);
+
+ const now = useCallback(() => ({ t: live.current.t, cur: live.current.cur, playing: live.current.playing }), []);
+ return { t: ui.t, cur: ui.cur, playing: ui.playing, laneOf, setPlaying, seek, now, playSpan };
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -61,8 +61,8 @@ Inbox cannot disagree about what is wrong with one.
| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) |
| `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
| `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
-| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) |
-| `trailer-beats <project> [ls] [--json]` · `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, what `trailer --beats` reads): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips ([knobs.md](knobs.md#the-trailers-beats)) |
+| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade and intro, written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) |
+| `trailer-beats <project> [ls] [--json]` · `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]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; every write an undo point ([knobs.md](knobs.md#the-trailers-beats)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
| `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -721,6 +721,28 @@ length here ([report-video.md](report-video.md#trailer-from-the-master)).
| move, remove, the cut's order | ↑ ↓ **remove**; **Order by the cut** | `move <n> --to <m>` · `remove <n>` · `order` | `{op: "move", index, to}` · `{op: "remove", index}` · `{op: "order"}` |
| the limit, the crossfade, the intro | **limit** (a platform, or seconds), **crossfade**, **open on the brand intro** | `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok\|default>` · `xfade <s>` · `intro on\|off` | `{op: "settings", limit?, xfade?, intro?}` |
| the walk's ★ clips | **★ from the walk**: each **Add** | `umtool trailer-beats <p> candidates [--add]` | `GET` (`candidates`) |
+| undo the last write (every write is an undo point) | **Undo** (the beats); **Undo last write** / `U` (the reel's walk) | `umtool trailer-beats <p> undo` | `{op: "undo"}` |
+
+### Beat reels: more than one, played, walked and cut from the master
+
+A project has as many reels as it wants -- the X trailer, a teaser, a "Kirsche-first" cut -- each its own file,
+`promo/<name>-beats.json` (`trailer` is `promo/trailer-beats.json`, its path unchanged), with its own limit, crossfade,
+intro, `title` and `take` (the take it is cut from, pinned; else the take it was last cut from, else the latest take
+with a finished master). Every command and route above takes the reel (`--reel <name>`, `reel` in the body or query;
+default `trailer`). A reel is PLAYED and WALKED from a take's **rendered master** (`takes/<t>/out/<slug>.mp4`): each
+beat is the span `umtool trailer` cuts (`lib/report/reelPlay.mjs`, the trailer's own `planTrailer` over the take's
+build records, the edges as written), so the chrome on screen is the final render's and the preview is seeks, not a
+build. A reel whose takes have no master says so and links the render (the Takes page); nothing renders on its own.
+Its cut is `takes/<t>/out/<slug>.<name>.mp4` (the trailer reel: `<slug>.trailer.mp4`), with `<…>.trailer.json` beside it.
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the reels; a new one (empty, or a copy) | the Trailer page's **reels** row, **+ New reel** | `umtool trailer-beats <p> reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` | `GET /api/report/trailer-beats` (`reels`) · `{op: "new-reel", name, from?, title?}` |
+| a reel's title, the take it is cut from | **title** | `trailer-beats <p> --reel R title <text>\|none` · `take <t>\|none` | `{op: "settings", title?, take?}` |
+| play the reel from a take's master: the crossfades, the clock against the limit, the strip of beats; `M` a note on the beat on screen (anchor `reel`), `E` walk it, `N`/`P` beats, `[`/`]` notes | **Play the reel** → `/projects/<p>/trailer/play?reel=&take=` (the take picker) | `umtool notes <p>` reads the notes | `GET /api/report/reel?project&reel&take` · the master: `GET /api/report/reel/media?project&take&what=master` |
+| walk a beat: in/out handles on the master's frames (`[` `]` in, `,` `.` out, Shift 0.5 s; `I`/`O` at the playhead), saved in the clip's source seconds (`Enter`), the clip's quote and source clock, `B` back to the reel | **Walk it** / `E` → `/projects/<p>/trailer/walk?reel=&take=&beat=n` | `trailer-beats <p> --reel R set <n> <from>-<to>` | `{op: "set", index, patch: {start, end}}` |
+| a beat's verdict: `confirmed` (Y, and on to the next) or `note` (a note left on it) | the walk's **Confirm (Y)** · **Note (M)** · **Clear verdict** | `trailer-beats <p> --reel R verdict <n> confirmed\|note\|clear` | `{op: "set", index, patch: {verdict}}` |
+| cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path | the Trailer page's **Cut the trailer** | `umtool trailer <p> --reel <name> [--take <t>]` | `POST /api/report/reel {project, reel, take}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` |
## Takes: relabel, supersede, cancel, delete, fork as variant, compare
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1381,6 +1381,32 @@ records each piece's master span, its source seconds (as asked and as cut), the
master it came from and the encode time. The command prints the mapped spans and the total
length; `--dry-run` prints them and writes nothing, and `--json` is for agents.
+### Beat reels
+
+A project may have several reels -- the X trailer, a teaser, a cut that opens on one speaker --
+each a beats file of its own, `promo/<name>-beats.json` (the reel `trailer` is
+`promo/trailer-beats.json`), with its own limit, crossfade, intro, title and the take it is cut
+from. `umtool trailer <project> --reel <name> [--take <t>]` cuts one with its own settings to
+`takes/<t>/out/<slug>.<name>.mp4` (the trailer reel keeps `<slug>.trailer.mp4`); with no `--take`
+it uses the reel's pinned take, else the take it was last cut from, else the latest take with a
+finished master, and says which. `umtool trailer-beats <project> --reel <name> …` edits one, and
+`reels` / `new-reel <name> [--from <reel>]` list and make them.
+
+The Trailer page (`/projects/<p>/trailer?reel=<name>`) plays and walks a reel from a take's
+rendered master, as the cut's Play and walk do for the cut. Each beat is mapped by the same
+`planTrailer` the cut uses (`lib/report/reelPlay.mjs`), with the edges as written: the cut then
+moves each edge into its pause, as above. **Play the reel** (`…/trailer/play`) plays the beats
+back to back, the reel's crossfade dissolved in the browser. It shows the running clock against
+the limit and a strip of the beats, and takes notes anchored to a beat (`M`; the `reel` anchor,
+which `umtool notes` prints with the writer to use). **Walk it** (`…/trailer/walk?beat=n`) is the
+bench over one beat. Its in/out handles and nudge keys work on the master's frames, and a save
+writes the clip's source seconds. Each beat gets a verdict (`confirmed`, or `note`). Every write
+goes through the one writer and leaves an undo point (`U`, **Undo**, `trailer-beats … undo`).
+**Cut the trailer** runs `umtool trailer --reel` as a job on umtool's runner (the heavy slot, its
+log, Cancel), and the file then plays on the page with its local path. A cancelled cut leaves no
+half-made file: it is written beside the output and renamed only when the encode is done. A reel whose take has no
+master says so and links the Takes page to render one. Nothing renders on its own.
+
## Montages (`render.montage`)
A cut of one phrase said many times — every "slow news day" — is a montage, and
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -51,6 +51,7 @@ import { makeMarksFixture } from "./marks-fixture.mjs";
import { makeLivePreviewFixture } from "./live-preview-fixture.mjs";
import { makePlayCutFixture } from "./play-cut-fixture.mjs";
import { makeCutEditingFixture } from "./cut-editing-fixture.mjs";
+import { makeReelFixture } from "./reel-fixture.mjs";
import { makeIntakeFixture } from "./intake-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
@@ -1901,6 +1902,9 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out
// Editing the cut (UI notes 2026-10-30): sections, flash-forward, the trailer's beats, take housekeeping
// (cut-sections, cut-flash, trailer-beats and take-housekeeping specs).
makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// Beat reels (lane/beat-reels): a take with a synthesized rendered master and its build records,
+// two reels; and a project whose only take has no master (reel-play.spec.ts).
+makeReelFixture({ reports, deckManifest });
// The intake (UI notes 2026-10-30, items 13, 14, 16): the candidates inbox, the source backlog, Add post (intake specs).
makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut,
diff --git a/umtool/e2e/fixtures/reel-fixture.mjs b/umtool/e2e/fixtures/reel-fixture.mjs
@@ -0,0 +1,96 @@
+// BEAT REELS (lane/beat-reels): a project with a take that HAS a rendered
+// master, so a reel plays, walks and cuts from it (reel-play.spec.ts).
+//
+// reel-fixture six clips c01–c06 on vid1 (1.5 s each, 1+2i – 2.5+2i)
+// and takes/draft-1, built: its master
+// out/reel-fixture.mp4 is SYNTHESIZED (testsrc 320×180,
+// 30 fps, a 440 Hz tone, 10.5 s = 315 frames), with the
+// build records `umtool trailer` maps through --
+// out/sourced/schedule.json (each clip a 2.0 s segment,
+// 0.3 s dissolves: c0k starts at 1.7·(k−1)) and
+// segments/<id>.cut.json (each cut from 0.25 s before its
+// clip). Two reels: promo/trailer-beats.json (c01 1–2.5,
+// c03 5–6.5, c05 9–10.4: 3.8 s with the 0.3 s crossfades,
+// every edge clear of the master's own dissolves)
+// and promo/teaser-beats.json (c02 alone, titled).
+// WRITES promo/ and takes/draft-1/out/ (a cut): the spec
+// puts both back before each test.
+// reel-none-fixture the same cut, its one take a DRAFT with no master: a
+// reel says so and offers the render.
+//
+// Synthetic, like every fixture.
+import { spawnSync } from "node:child_process";
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const json = (doc, indent = 2) => JSON.stringify(doc, null, indent) + "\n";
+const write = (dir, name, text) => {
+ mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ writeFileSync(path.join(dir, name), text);
+};
+
+export const REEL_SEG = 2.0;
+export const REEL_XFADE = 0.3;
+export const REEL_TOTAL = 5 * (REEL_SEG - REEL_XFADE) + REEL_SEG; // 10.5
+
+const clips = () =>
+ ["c01", "c02", "c03", "c04", "c05", "c06"].map((id, i) => ({
+ type: "clip",
+ id,
+ video: "vid1",
+ start: 1 + i * 2,
+ end: 2.5 + i * 2,
+ cite: 1 + i * 2,
+ citeUrl: `https://archive.example/?v=testchan%2Fvid1&t=${1 + i * 2}`,
+ lock: true,
+ title: "The Fixture Stream",
+ date: "2026-10-27",
+ quote: `the words of ${id}`,
+ }));
+
+const take = (id, { draft = false } = {}) => ({
+ id, group: "takes", order: 1, label: `${id}: the reel fixture's take`, kind: "reference", summary: "", changes: [],
+ preview: "preview.mp4", seconds: draft ? null : REEL_TOTAL, builtAt: draft ? null : "2026-11-02T12:00:00.000Z",
+ style: null, patch: null, window: "full", ...(draft ? { draft: true } : {}),
+});
+
+/**
+ * @param {{ reports: string, deckManifest: Function }} o
+ */
+export function makeReelFixture({ reports, deckManifest }) {
+ const dir = path.join(reports, "reel-fixture");
+ const m = deckManifest("reel-fixture", "The Reel Fixture", clips());
+ write(dir, "video.manifest.json", json(m));
+ const takeDir = path.join(dir, "takes", "draft-1");
+ // The take's own manifest: a small, fast encode for the trailer's one pass.
+ const tm = { ...m, render: { ...m.render, width: 320, height: 180, fps: 30, crf: 32, preset: "ultrafast", audioBitrate: "64k" } };
+ write(takeDir, "video.manifest.json", json(tm));
+ write(takeDir, "take.json", json(take("draft-1")));
+ const out = path.join(takeDir, "out");
+ mkdirSync(path.join(out, "sourced", "segments"), { recursive: true });
+ const r = spawnSync("ffmpeg", [
+ "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc=size=320x180:rate=30:duration=${REEL_TOTAL}`,
+ "-f", "lavfi", "-i", `sine=frequency=440:duration=${REEL_TOTAL}`,
+ "-map", "0:v", "-map", "1:a", "-t", String(REEL_TOTAL),
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "15", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-ar", "48000", "-ac", "2", "-movflags", "+faststart",
+ path.join(out, "reel-fixture.mp4"),
+ ], { encoding: "utf8" });
+ if (r.status !== 0) throw new Error(`ffmpeg failed: ${r.stderr || r.status}`);
+ const segments = clips().map((c, i) => ({ id: c.id, type: "clip", start: Number((i * (REEL_SEG - REEL_XFADE)).toFixed(3)), duration: REEL_SEG }));
+ write(out, path.join("sourced", "schedule.json"), json({ version: 1, kind: "deck", fps: 30, transition: REEL_XFADE, total: REEL_TOTAL, segments }));
+ for (const c of clips()) write(out, path.join("sourced", "segments", `${c.id}.cut.json`), json({ version: 1, id: c.id, start: c.start - 0.25, end: c.start - 0.25 + REEL_SEG }));
+ write(dir, path.join("promo", "trailer-beats.json"), json([
+ { id: "c01", start: 1, end: 2.5 },
+ { id: "c03", start: 5, end: 6.5 },
+ { id: "c05", start: 9, end: 10.4 },
+ ], 1));
+ write(dir, path.join("promo", "teaser-beats.json"), json({ title: "The teaser", beats: [{ id: "c02", start: 3, end: 4.5 }] }));
+
+ const none = path.join(reports, "reel-none-fixture");
+ write(none, "video.manifest.json", json(deckManifest("reel-none-fixture", "The Reel None Fixture", clips())));
+ write(path.join(none, "takes", "draft-1"), "take.json", json(take("draft-1", { draft: true })));
+ write(none, path.join("promo", "trailer-beats.json"), json([{ id: "c01", start: 1, end: 2.5 }]));
+ return { dir, none };
+}
diff --git a/umtool/e2e/reel-play.spec.ts b/umtool/e2e/reel-play.spec.ts
@@ -0,0 +1,195 @@
+import { test, expect, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// BEAT REELS (lane/beat-reels): "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."
+//
+// reel-fixture takes/draft-1 with a synthesized rendered master (10.5 s,
+// six 2.0 s segments, 0.3 s dissolves) and its build
+// records; promo/trailer-beats.json c01 1–2.5, c03 5–6.5,
+// c05 9–10.4 (3.8 s); promo/teaser-beats.json c02 alone.
+// WRITES promo/, notes.json and a cut in draft-1/out:
+// each test starts from the fixture's.
+// reel-none-fixture its one take a draft with no master.
+//
+// The reel's Play (from the master, the crossfade, the clock against the
+// limit, a note on a beat), its walk (handles and nudges on the master's
+// frames, written in source seconds through the one writer, an undo point per
+// write, Confirm walks on, Back to the reel), Cut the trailer as a job with
+// the result's local path, and the no-master state. Fixture:
+// e2e/fixtures/reel-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIR = path.join(HERE, "..", ".e2e-song", "reports", "reel-fixture");
+const PROJECT = "reports/reel-fixture";
+const PROMO = path.join(DIR, "promo");
+const OUT = path.join(DIR, "takes", "draft-1", "out");
+const NOTES = path.join(DIR, "notes.json");
+
+const beatsOf = (reel = "trailer") => {
+ const d = JSON.parse(readFileSync(path.join(PROMO, `${reel}-beats.json`), "utf8"));
+ return (Array.isArray(d) ? d : d.beats) as { id?: string; start?: number; end?: number; verdict?: string }[];
+};
+const root = (page: Page) => page.locator("[data-reel-play]");
+
+test.beforeAll(() => {
+ for (const f of ["trailer-beats.json", "teaser-beats.json"]) {
+ const p = path.join(PROMO, f);
+ if (!existsSync(`${p}.pristine`)) copyFileSync(p, `${p}.pristine`);
+ }
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ for (const f of readdirSync(PROMO)) {
+ if (f.endsWith(".pristine")) copyFileSync(path.join(PROMO, f), path.join(PROMO, f.replace(/\.pristine$/, "")));
+ else if (!/^(trailer|teaser)-beats\.json$/.test(f)) rmSync(path.join(PROMO, f), { force: true });
+ }
+ for (const f of readdirSync(OUT)) if (/\.(trailer|teaser)\.(mp4|json)$/.test(f) || f.endsWith(".trailer.json")) rmSync(path.join(OUT, f), { force: true });
+ rmSync(NOTES, { force: true });
+});
+
+test("the Trailer page lists the reels; a reel plays from the take's rendered master, beat after beat, against the limit; a note lands on its beat", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.trailerHref(PROJECT));
+ await expect(page.locator("[data-reel-tab='trailer']")).toContainText("trailer (3)");
+ await expect(page.locator("[data-reel-tab='teaser']")).toContainText("teaser — The teaser (1)");
+ const panel = page.locator("[data-reel-cut-panel='trailer']");
+ await expect(panel).toContainText("(latest master)");
+ await expect(panel).toContainText("3 of 3 beats play from it · 0:03.8");
+ await panel.locator("[data-reel-play-link]").click();
+
+ await expect(root(page)).toHaveAttribute("data-reel-take", "draft-1");
+ await expect(root(page)).toHaveAttribute("data-reel-state", "paused");
+ await expect(page.locator("[data-reel-cell]")).toHaveCount(3);
+ await expect(page.locator("[data-reel-clock]")).toHaveText("0:00.0 / 0:03.8");
+ await expect(page.locator("[data-reel-limit]")).toContainText("limit 2:20.0 · 136.2 s to spare · crossfade 0.3 s");
+ await expect(page.locator("[data-reel-master-path]")).toHaveText(path.join(OUT, "reel-fixture.mp4"));
+ await expect(page.locator("[data-reel-now='1']")).toContainText("beat 1 · c01");
+ await expect(page.locator("[data-reel-now='1']")).toContainText("the words of c01");
+
+ // Plays through: beat 2 (into the crossfade), then 3, and stops at the reel's end.
+ await page.locator("[data-reel-toggle]").click();
+ await expect(root(page)).toHaveAttribute("data-reel-state", "playing");
+ await expect(root(page)).toHaveAttribute("data-reel-beat", "2", { timeout: 15_000 });
+ await expect(root(page)).toHaveAttribute("data-reel-beat", "3", { timeout: 15_000 });
+ await expect(root(page)).toHaveAttribute("data-reel-state", "paused", { timeout: 15_000 });
+ expect(Number(await root(page).getAttribute("data-reel-t"))).toBeGreaterThan(3.6);
+
+ // The keys: P back a beat, N on; M a note on the beat on screen.
+ await page.keyboard.press("p");
+ await expect(root(page)).toHaveAttribute("data-reel-beat", "3");
+ await page.keyboard.press("p");
+ await expect(root(page)).toHaveAttribute("data-reel-beat", "2");
+ await page.keyboard.press("m");
+ await expect(page.locator("[data-reel-composer]")).toContainText("beat 2 · c03");
+ await page.getByTestId("reel-note-input").fill("end it on the word");
+ await page.locator("[data-reel-ask='trim']").click();
+ await page.getByTestId("reel-note-input").press("Enter");
+ await expect(page.locator("[data-reel-note-row]")).toHaveCount(1);
+ await expect(page.locator("[data-reel-pin]")).toHaveCount(1);
+ const notes = JSON.parse(readFileSync(NOTES, "utf8")).notes;
+ expect(notes[0].anchor).toMatchObject({ kind: "reel", reel: "trailer", beat: 2, entry: "c03", take: "draft-1", ask: "trim" });
+ expect(notes[0].anchor.sourceT).toBeGreaterThanOrEqual(5);
+ await page.screenshot({ path: test.info().outputPath("reel-play.png") });
+
+ // E: the walk on the beat on screen.
+ await page.keyboard.press("e");
+ await expect(page).toHaveURL(/\/trailer\/walk\?take=draft-1&beat=2/);
+ await expect(page.locator("[data-reel-walk]")).toHaveAttribute("data-reel-beat", "2");
+});
+
+test("the walk: in/out on the master's frames, written in source seconds through the one writer; each write an undo point; Confirm walks on; Back to the reel", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.reelWalkHref(PROJECT, { beat: 2 }));
+ const walk = page.locator("[data-reel-walk]");
+ await expect(walk).toHaveAttribute("data-reel-beat", "2");
+ await expect(walk).toHaveAttribute("data-reel-dirty", "0");
+ await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:05.00 – 0:06.50");
+ await expect(page.locator("[data-reel-beat-quote]")).toContainText("the words of c03");
+ await expect(page.locator("[data-reel-handle]")).toHaveCount(2);
+
+ // ] twice: the in edge 0.1 s later; . with Shift: the out edge 0.5 s later -- held to the clip's cut (6.75).
+ await page.keyboard.press("]");
+ await page.keyboard.press("]");
+ await page.keyboard.press("Shift+.");
+ await expect(walk).toHaveAttribute("data-reel-dirty", "1");
+ await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:05.10 – 0:06.75");
+ await page.keyboard.press("Enter");
+ await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5.1, end: 6.75 });
+ await expect(walk).toHaveAttribute("data-reel-dirty", "0");
+ await expect(page.locator("[data-reel-msg]")).toContainText("saved — beat 2 5.1–6.75");
+
+ // A handle dragged: the in edge back to the segment's start (the clip's cut, 4.75).
+ const track = await page.locator("[data-reel-track]").boundingBox();
+ const h = await page.locator("[data-reel-handle='from']").boundingBox();
+ await page.mouse.move(h!.x + h!.width / 2, h!.y + h!.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(track!.x + 2, h!.y + h!.height / 2, { steps: 5 });
+ await page.mouse.up();
+ await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:04.75 – 0:06.75");
+ await page.locator("[data-reel-save]").click();
+ await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 4.75, end: 6.75 });
+ await page.screenshot({ path: test.info().outputPath("reel-walk.png") });
+
+ // U: the last write undone, then the one before.
+ await page.keyboard.press("u");
+ await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5.1, end: 6.75 });
+ await page.locator("[data-reel-undo]").click();
+ await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5, end: 6.5 });
+ await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:05.00 – 0:06.50");
+
+ // Y: confirmed, and on to beat 3; B back to the reel's Play at that beat.
+ await page.keyboard.press("y");
+ await expect(page).toHaveURL(/beat=3/);
+ await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5, end: 6.5, verdict: "confirmed" });
+ await expect(page.locator("[data-reel-walk]")).toHaveAttribute("data-reel-beat", "3");
+ await page.keyboard.press("b");
+ await expect(page).toHaveURL(/\/trailer\/play\?.*beat=3/);
+ await expect(root(page)).toHaveAttribute("data-reel-beat", "3");
+ await expect(page.locator("[data-reel-cell='2']")).toHaveClass(/border-b-2/);
+ // The beats page says it too.
+ await page.goto(urls.trailerHref(PROJECT));
+ await expect(page.getByTestId("trailer-confirmed")).toHaveText("1 confirmed on the walk");
+ await expect(page.locator("[data-beat='2'] [data-beat-verdict='confirmed']")).toHaveCount(1);
+});
+
+test("Cut the trailer: a job on the runner, its log, the result playing on the page with its local path; a new reel", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.trailerHref(PROJECT, { reel: "teaser" }));
+ const panel = page.locator("[data-reel-cut-panel='teaser']");
+ await expect(panel.locator("[data-reel-cut]")).toBeEnabled();
+ await panel.locator("[data-reel-cut]").click();
+ await expect(panel.locator("[data-reel-job]")).toBeVisible();
+ await expect(panel.locator("[data-reel-job]")).toHaveAttribute("data-reel-job", "done", { timeout: 90_000 });
+ await expect(panel.locator("[data-reel-job-log]")).toContainText("trailer reports/reel-fixture --reel teaser --take draft-1");
+ const out = path.join(OUT, "reel-fixture.teaser.mp4");
+ await expect(panel.locator("[data-reel-result-path]")).toHaveText(out);
+ expect(existsSync(out)).toBe(true);
+ expect(existsSync(path.join(OUT, "reel-fixture.teaser.trailer.json"))).toBe(true);
+ await expect(panel.locator("[data-reel-result-video]")).toHaveAttribute("src", /what=cut&reel=teaser/);
+ // The trailer reel's file is untouched by the teaser's cut.
+ expect(existsSync(path.join(OUT, "reel-fixture.trailer.mp4"))).toBe(false);
+
+ // + New reel: a copy of the trailer, its own file, listed.
+ await page.locator("[data-reel-new-open]").click();
+ await page.locator("[data-reel-new-name]").fill("x-first");
+ await page.locator("[data-reel-new-from]").selectOption("trailer");
+ await page.locator("[data-reel-new-make]").click();
+ await expect(page).toHaveURL(/reel=x-first/);
+ await expect(page.locator("[data-reel-tab='x-first']")).toContainText("x-first (3)");
+ expect(beatsOf("x-first").map((b) => b.id)).toEqual(["c01", "c03", "c05"]);
+});
+
+test("no rendered master: the reel says so and offers the render -- nothing renders from here", async ({ page }) => {
+ await page.goto(urls.reelPlayHref("reports/reel-none-fixture"));
+ await expect(page.locator("[data-reel-no-master-why]")).toContainText("no take has a finished master yet");
+ await expect(page.locator("[data-reel-render-link]")).toHaveAttribute("href", urls.takesHref("reports/reel-none-fixture"));
+ await page.goto(urls.trailerHref("reports/reel-none-fixture"));
+ await expect(page.locator("[data-reel-cut-panel] [data-reel-no-master]")).toContainText("render a take first");
+ await expect(page.locator("[data-reel-cut]")).toHaveCount(0);
+});
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 });
+ }
+});
diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs
@@ -65,6 +65,7 @@
// this module, so the umtool app can import it without the gate in its bundle.
import { execFile } from "node:child_process";
+import { rmSync } from "node:fs";
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
@@ -677,17 +678,37 @@ export async function makeTrailer({
const tmp = path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}.${process.pid}.tmp.mp4`);
argv[argv.length - 1] = tmp;
let encodeSeconds = null;
- await slot(async () => {
- const t0 = now();
- try {
- await run(argv);
- await rename(tmp, outPath);
- } catch (err) {
- await rm(tmp, { force: true });
- throw err;
- }
- encodeSeconds = r3((now() - t0) / 1000);
+ // Cancelled (the Trailer page's Cancel signals the job's process group): the
+ // half-made file goes with it. Exits as the signal would when nothing else
+ // here listens for it.
+ const onSignal = ["SIGTERM", "SIGINT", "SIGHUP"].map((sig) => {
+ const alone = process.listenerCount(sig) === 0;
+ const h = () => {
+ try {
+ rmSync(tmp, { force: true });
+ } catch {
+ // gone already
+ }
+ if (alone) process.exit(128 + (sig === "SIGINT" ? 2 : sig === "SIGHUP" ? 1 : 15));
+ };
+ process.once(sig, h);
+ return /** @type {const} */ ([sig, h]);
});
+ try {
+ await slot(async () => {
+ const t0 = now();
+ try {
+ await run(argv);
+ await rename(tmp, outPath);
+ } catch (err) {
+ await rm(tmp, { force: true });
+ throw err;
+ }
+ encodeSeconds = r3((now() - t0) / 1000);
+ });
+ } finally {
+ for (const [sig, h] of onSignal) process.off(sig, h);
+ }
record.builtAt = new Date(now()).toISOString();
record.encodeSeconds = encodeSeconds;
record.out = outPath;