Archilyzer · Source

archilyzer

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

commit 66f4df9e663f86a3e6af708e266e689fcd42a25c
parent 69999996d2e4e527e61e751cd24e0dc595d6a88f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 15:42:06 -0500

umtool: a beat reel's Play and walk from a take's rendered master, and Cut the trailer as a job -- Play the reel (the beats back to back on the master's own frames, the crossfade dissolved in the browser, the clock against the limit, the strip, a note on a beat), the walk (in/out handles and nudge keys on the master's frames, saved in source seconds through the one writer, a verdict per beat, undo, back to the reel), the cut on umtool's runner (heavy slot, log, Cancel) playing with its local path; the Trailer page lists the reels and makes new ones; no master: said, and the render linked

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

Diffstat:
Aumtool/app/api/report/reel/media/route.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/reel/route.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/trailer-beats/route.ts | 78+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mumtool/components/projects/ProjectView.tsx | 14++++++++++++--
Mumtool/components/projects/TrailerBeatsEditor.tsx | 55++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/components/projects/TrailerPage.tsx | 49+++++++++++++++++++++++++++++++++++++++++--------
Aumtool/components/projects/reel/NewReel.tsx | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/ReelCutPanel.tsx | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/ReelPlay.tsx | 553+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/ReelPlayPage.tsx | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/ReelWalk.tsx | 459+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/ReelWalkPage.tsx | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/reelTypes.ts | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/reel/useReelPlayer.ts | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 2061 insertions(+), 36 deletions(-)

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/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 &lt;take&gt;{view.intro ? " --intro" : ""} --beats &lt;project&gt;/{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&apos;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">&ldquo;{row.quote}&rdquo;</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&apos;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">&ldquo;{row.quote}&rdquo;</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 }; +}