"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 { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs"; import { fileSpans } from "@/lib/report/fileMedia.mjs"; import type { ReelBenchData } from "@/lib/report/reelBenchData"; import { cn } from "@/lib/utils"; import { beatGapsOf, editGaps, gapWalls } from "umtool-report-to-video/gaps"; import { BenchWaveBox, GapTools } from "../bench/BenchWave"; import { renderedFileMedia, type Span } from "../bench/benchMedia"; import { ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom } from "../bench/GapsZoom"; import { useRenderEdges } from "../bench/RenderGhosts"; import { TightenButtons, useEdgeTools, type BenchWord } from "../bench/TightenTools"; import { useBenchPlayer } from "../bench/useBenchPlayer"; import { useGapEditor, type GapOp } from "../bench/useGapEditor"; import { usePeaks } from "../bench/usePeaks"; import { Composer, type ReelAnchor } from "./ReelPlay"; import { BeatStatusBar, SourceBanner } from "./ReelSource"; import { CHANGED_STATES, clock, r2, readReelView, reelWrite, sourceClock, type ReelRow, type ReelView } from "./reelTypes"; // --------------------------------------------------------------------------- // A BEAT REEL'S WALK (`/projects/

/trailer/walk?reel=&take=&beat=n`, // lane/reel-bench): the reel's own editor, on the take's RENDERED MASTER -- // the final frames, the chrome burned in -- built from the clip bench's parts // (components/projects/bench/): the waveform with its zoom (ruler, detail, // overview), the handles and nudges, a beat's GAPS (Alt + drag, Cut gap, // Hear it, Undo), tighten to the sentence and snap an edge to a pause, the // playback engine (decoded audio, exact stops, the speeds) and notes on the // beat. What plays is the master through the build record's map // (bench/benchMedia.ts renderedFileMedia); what is edited is the beat, in its // clip's SOURCE seconds, through the beats' one writer (POST // /api/report/trailer-beats) -- every write an undo point. // // [ ] in edge back / on 0.05 s (Shift 0.5 s) , . out edge // I O in / out at the playhead Space play the beat (its gaps skipped) // Enter save the edges R put them back as saved // Y confirm (the edges too) and walk on M X a note on the beat // U undo the reel's last write N P next / previous beat // B back to the reel's Play z Z f F zoom g G gaps - = speed // --------------------------------------------------------------------------- const STEP = 0.05; const BIG = 0.5; const RATES = [0.75, 1, 1.25, 1.5, 2] as const; type Cue = { start: number; end: number; text: string; endsSentence: boolean }; export default function ReelBench({ initial, changed = false }: { initial: ReelBenchData; changed?: boolean }) { const router = useRouter(); const [view, setView] = useState(initial.view); // A refresh from the server (a fix on a beat that did not map) is the view now. useEffect(() => setView(initial.view), [initial.view]); const project = view.project; const reel = view.reel; const take = view.take?.id ?? null; const beat = initial.beat; const all = useMemo(() => view.rows ?? [], [view.rows]); // `changed`: the walk visits only the beats the take changed under the reel (the one on screen either way). const rows = useMemo(() => (changed ? all.filter((r) => r.n === beat || (r.status && CHANGED_STATES.includes(r.status.state))) : all), [all, changed, beat]); 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 isClip = row?.kind === "clip"; if (view.noMaster || !take) { return (

{view.noMaster?.why ?? "no take to walk"}

render a take on the Takes page
); } if (!row || !initial.media) { return (
{row && router.refresh()} />}

{row ? `Beat ${beat} does not play from take ${take}'s master: ${row.problem ?? "it does not map"}.` : `The reel ${reel} has no beat ${beat}.`}{" "} Its beats

); } return ; } /** The saved beat as source seconds: a clip beat's start–end, a master beat's at–at+dur. */ const savedOf = (row: ReelRow): Span => row.kind === "clip" ? { from: Number(row.beat.start), to: Number(row.beat.end) } : { from: Number(row.beat.at), to: Number(row.beat.at) + Number(row.beat.dur) }; function BeatEditor({ view, setView, row, data, prevRow, nextRow, fps, isClip, router, changed, }: { view: ReelView; setView: (v: ReelView) => void; row: ReelRow; data: ReelBenchData; prevRow: ReelRow | null; nextRow: ReelRow | null; fps: number; isClip: boolean; router: ReturnType; changed: boolean; }) { const project = view.project; const reel = view.reel; const take = view.take!.id; const m = data.media!; const media = useMemo(() => renderedFileMedia({ project, path: m.path, v: m.v, map: m.map, span: m.span }), [project, m.path, m.v, m.map, m.span]); const span = m.span; const saved = savedOf(row); const gaps = useMemo(() => (isClip ? (row.beat.gaps ?? []) : []), [isClip, row.beat.gaps]); const [sel, setSel] = useState(saved); const savedKey = `${saved.from}|${saved.to}`; useEffect(() => setSel(saved), [savedKey]); // eslint-disable-line react-hooks/exhaustive-deps const [msg, setMsg] = useState(null); const [busy, setBusy] = useState(false); const [rate, setRate] = useState(1); const video = useRef(null); const dirty = Math.abs(sel.from - saved.from) > 0.004 || Math.abs(sel.to - saved.to) > 0.004; const cues: Cue[] = data.cues; // ---- the writes: the beats' one writer, its token, an undo point each ------------------ const token = useRef(view.token); token.current = view.token; const lastSaved = useRef | null>(null); const reload = useCallback(async () => { try { setView(await readReelView(project, reel, take)); } catch (e) { setMsg(e instanceof Error ? e.message : String(e)); } }, [project, reel, take, setView]); const write = useCallback( async (op: string, args: Record, said: string | null) => { setBusy(true); try { // The take this edit is made against: the writer anchors the beat to it (reelAnchor.mjs). const r = await reelWrite(project, reel, token.current, op, { ...args, take }); if (!r.ok) { setMsg(r.error); if (r.stale) await reload(); return false; } token.current = r.token; if (said !== null) setMsg(r.undone ? `undone: ${r.undone}` : said); await reload(); return true; } finally { setBusy(false); } }, [project, reel, reload, take], ); /** A patch in the bench's words (start/end source seconds, gaps, verdict) as the beat's. */ const save = useCallback( (patch: Record) => { const p: Record = {}; if (patch.start !== undefined || patch.end !== undefined) { const a = Number(patch.start ?? sel.from); const b = Number(patch.end ?? sel.to); if (isClip) Object.assign(p, { start: r2(a), end: r2(b) }); else Object.assign(p, { at: r2(a), dur: r2(b - a) }); } if (patch.gaps !== undefined) p.gaps = patch.gaps; if (patch.verdict !== undefined) p.verdict = patch.verdict; lastSaved.current = null; const what = [p.start !== undefined || p.at !== undefined ? "edges" : null, p.gaps !== undefined ? "gaps" : null, p.verdict !== undefined ? `verdict ${p.verdict ?? "cleared"}` : null].filter(Boolean).join(", "); return write("set", { index: row.n - 1, patch: p }, `saved beat ${row.n}: ${what} (U undoes it)`); }, [write, row.n, isClip, sel.from, sel.to], ); // ---- playback: the master through the map; a beat's gaps skipped ------------------------- const gapsRef = useRef(gaps); gapsRef.current = gaps; const muteRef = useRef(null); const { play, stopPlayback, playhead, playInfo, audio, showAt, playing } = useBenchPlayer({ media, video, rate, gapsRef, muteRef, warm: sel }); const playheadRef = useRef(null); playheadRef.current = playhead; const peaks = usePeaks(media); // ---- the edges: dragged, nudged, at the playhead -- held to what the master rendered ------ const [atLimit, setAtLimit] = useState<"start" | "end" | null>(null); const clamp = useCallback( (s: Span) => { const minLen = Math.max(2 / fps, gaps.length ? 0.6 : 0); let from = Math.max(span.from, Math.min(span.to - minLen, s.from)); let to = Math.min(span.to, Math.max(from + minLen, s.to)); from = Math.round(from * 1000) / 1000; to = Math.round(to * 1000) / 1000; setAtLimit(s.from < span.from - 1e-3 ? "start" : s.to > span.to + 1e-3 ? "end" : null); return { from, to }; }, [span.from, span.to, fps, gaps.length], ); const onSel = useCallback( (next: Span, dragging: boolean, edge?: "start" | "end" | null) => { const c = clamp(next); setSel(c); if (dragging) return; if (edge === "end") void play(Math.max(c.from, c.to - 4), c.to); else if (edge === "start") void play(c.from, Math.min(c.to, c.from + 4)); }, [clamp, play], ); const nudge = useCallback((which: "from" | "to", by: number) => onSel(which === "from" ? { ...sel, from: sel.from + by } : { ...sel, to: sel.to + by }, false, which === "from" ? "start" : "end"), [onSel, sel]); const edgeAtPlayhead = useCallback( (which: "from" | "to") => { const t = playheadRef.current; if (t == null) { setMsg("no playhead yet — play, or click the waveform"); return; } onSel(which === "from" ? { ...sel, from: t } : { ...sel, to: t }, false, which === "from" ? "start" : "end"); }, [onSel, sel], ); const saveEdges = useCallback(async () => (dirty ? save({ start: sel.from, end: sel.to }) : true), [dirty, save, sel.from, sel.to]); // ---- gaps: the clip bench's editor, writing the beat's list ------------------------------- const gapRefusal = useCallback( (next: Span[]) => { try { beatGapsOf({ start: saved.from, end: saved.to, gaps: next }, "the beat"); } catch (e) { return (e instanceof Error ? e.message : String(e)).replace(/^the beat: /, ""); } // A gap the master already cut out of the clip leaves nothing there to cut. for (const g of next) if (!fileSpans(m.map, [g], 1 / fps).length) return `${g.from}–${g.to} lies inside a gap the master already cut out of ${row.id} — nothing of it plays there to cut`; return null; }, [saved.from, saved.to, m.map, fps, row.id], ); const gap = useGapEditor({ key: `${reel}:${row.n}`, gaps, span: saved, refusal: gapRefusal, write: (_op: GapOp, next: Span[]) => save({ gaps: next }), said: (next) => { const kept = saved.to - saved.from - next.reduce((s, g) => s + (g.to - g.from), 0); return `the beat plays ${kept.toFixed(2)} s, one beat of jump cuts`; }, setNote: setMsg, fmt: sourceClock, }); // ---- tighten / snap: the clip bench's tools over the beat ------------------------------- const clipLike = useMemo( () => ({ id: row.id ?? `beat-${row.n}`, start: saved.from, end: saved.to, cutStart: null, cutEnd: null, muteFrom: null, cite: null, citeUrl: null, gaps: m.map.gaps }), [row.id, row.n, saved.from, saved.to, m.map.gaps], ); const render = useRenderEdges(project, clipLike, sel, take); const edgeTools = useEdgeTools({ project, clip: clipLike, video: data.clip?.video ?? "", sel, playhead, cues, silences: isClip ? (render?.silences ?? null) : null, lo: span.from, hi: span.to, save: (p) => save(p), lastSaved, play, setNote: setMsg, }); // ---- the zoom, and the words close in ------------------------------------------------------ const zoom = useWaveZoom(span); const [nearWords, setNearWords] = useState<{ key: string; words: BenchWord[] | null } | null>(null); const close = zoom.vis.to - zoom.vis.from <= DETAIL_SPAN; const wordsKey = close && isClip && data.clip ? `${row.id}|${Math.floor(zoom.vis.from / 10) * 10}|${Math.ceil(zoom.vis.to / 10) * 10}` : null; useEffect(() => { if (!wordsKey || nearWords?.key === wordsKey || !data.clip) return; let live = true; const [, a, b] = wordsKey.split("|"); const q = new URLSearchParams({ project, clip: data.clip.id, from: a, to: b, video: data.clip.video }); fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" }) .then((r) => (r.ok ? (r.json() as Promise<{ words?: BenchWord[] | null }>) : null)) .then((j) => live && setNearWords({ key: wordsKey, words: j?.words ?? null })) .catch(() => live && setNearWords({ key: wordsKey, words: null })); return () => { live = false; }; }, [wordsKey, nearWords?.key, project, data.clip]); // ---- the verdict, notes, undo, the walk ---------------------------------------------------- const go = useCallback((n: number) => router.push(reelWalkHref(project, { reel, take, beat: n, changed })), [router, project, reel, take, changed]); const confirm = useCallback(async () => { const ok = await save({ verdict: "confirmed", ...(dirty ? { start: sel.from, end: sel.to } : {}) }); if (ok && nextRow) go(nextRow.n); }, [save, dirty, sel.from, sel.to, nextRow, go]); const undo = useCallback(() => void write("undo", {}, "undone"), [write]); const goBack = useCallback(() => router.push(reelPlayHref(project, { reel, take, beat: row.n })), [router, project, reel, take, row.n]); 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 === row.n)), [notes.notes, reel, row.id, row.n], ); const [drafting, setDrafting] = useState(null); const noteHere = useCallback(() => { const src = playheadRef.current ?? sel.from; const masterT = media.clockOf(src); const at = row.piece ? row.piece.at + Math.max(0, masterT - row.piece.master.start) : 0; setDrafting({ kind: "reel", reel, beat: row.n, t: r2(at), masterT: r2(masterT), ...(row.id ? { entry: row.id, sourceT: r2(src) } : {}), take }); }, [sel.from, media, row.piece, row.n, row.id, reel, take]); // ---- 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; const ph = playheadRef.current; const inView = ph != null && ph >= zoom.vis.from && ph <= zoom.vis.to ? ph : null; 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": edgeAtPlayhead("from"); break; case "o": case "O": edgeAtPlayhead("to"); break; case " ": if (playing) stopPlayback(); else void play(sel.from, sel.to); break; case "Enter": void saveEdges(); break; case "r": case "R": setSel(saved); break; case "y": case "Y": void confirm(); break; case "m": case "M": case "x": case "X": noteHere(); break; case "u": case "U": undo(); break; case "b": case "B": goBack(); break; case "n": case "N": if (nextRow) go(nextRow.n); break; case "p": case "P": if (prevRow) go(prevRow.n); break; case "z": zoom.zoomIn(inView); break; case "Z": zoom.zoomOut(inView); break; case "f": zoom.fit(); break; case "F": zoom.to(gap.sel ?? sel); break; case "g": if (!isClip) return; if (gap.sel) void gap.cut(); else gap.setPick((v) => !v); break; case "G": if (!isClip) return; gap.removeAt(ph); break; case "-": case "_": setRate((r) => RATES[Math.max(0, RATES.indexOf(r as (typeof RATES)[number]) - 1)] ?? 1); break; case "=": case "+": setRate((r) => RATES[Math.min(RATES.length - 1, RATES.indexOf(r as (typeof RATES)[number]) + 1)] ?? 1); break; case "Escape": if (gap.pick || gap.sel) { gap.setPick(false); gap.setSel(null); break; } return; default: return; } e.preventDefault(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [nudge, edgeAtPlayhead, playing, stopPlayback, play, sel, saveEdges, saved, confirm, noteHere, undo, goBack, nextRow, prevRow, go, zoom, gap, isClip]); const zspan = Math.max(1e-6, zoom.vis.to - zoom.vis.from); const zpct = (t: number) => `${((Math.min(zoom.vis.to, Math.max(zoom.vis.from, t)) - zoom.vis.from) / zspan) * 100}%`; const fmt = isClip ? sourceClock : clock; const kept = sel.to - sel.from - gaps.reduce((s, g) => s + Math.max(0, Math.min(g.to, sel.to) - Math.max(g.from, sel.from)), 0); const masterGaps = isClip ? m.map.gaps.filter((g) => g.to > span.from && g.from < span.to) : []; // Where a gap cannot go in the beat, drawn as on the clip bench (lane/clip-fixes): the beat's // edges and the keep bands, the clip rule's (gaps.mjs gapWalls), said as the beat's. The // master's own gaps are drawn below, each with its title. const walls = useMemo(() => { if (!isClip) return null; const w = gapWalls({ type: "clip", id: row.id ?? "beat", start: saved.from, end: saved.to, gaps }); return { ...w, whose: "beat", zones: w.zones.map((z) => ({ ...z, why: z.why.replace("the clip's", "the beat's") })) }; }, [isClip, row.id, saved.from, saved.to, gaps]); const confirmedCount = (view.rows ?? []).filter((x) => x.verdict === "confirmed").length; return (
`${g.from}-${g.to}`).join(",")} >
void reload()} />
{/* ---- the edges, in source seconds, and what the master plays of them ---- */}
{isClip ? "source " : "master "} {fmt(sel.from)} – {fmt(sel.to)} {kept.toFixed(2)} s{gaps.length ? ` (${gaps.length} gap${gaps.length === 1 ? "" : "s"} out)` : ""} · master {clock(media.clockOf(sel.from))}–{clock(media.clockOf(sel.to))} ▸ {playhead != null ? fmt(playhead) : "—"} {dirty && unsaved — Enter saves, R puts back} {atLimit && ( that is the {atLimit === "start" ? "start" : "end"} of what the master rendered for {row.id ?? "this beat"} ({fmt(span.from)}–{fmt(span.to)}) — a beat cannot reach past it; render a take with a wider window )}
{/* ---- the instrument: the clip bench's waveform, zoom and gaps ---- */}
{zoom.zoomed && } {/* What the master already left out of the clip (its render's gaps): nothing plays there. */} {masterGaps.map((g) => (
))} {zoom.zoomed && }
{isClip ? ( ) : ( a master beat is master seconds: only a clip beat has gaps )} {isClip && }
{audio.state === "ready" ? "exact playback" : audio.state === "loading" ? "decoding the audio…" : audio.state === "failed" ? `the picture plays instead — ${audio.why}` : null} {msg && {msg}}

beat {row.n} · {row.id ?? "master"} {row.date && {row.date}} {row.channel && {row.channel}{row.video ? `/${row.video}` : ""}} {isClip && its segment plays source {sourceClock(span.from)}–{sourceClock(span.to)}}

{row.quote &&

“{row.quote}”

} {row.problem &&

{row.problem}

}

[ ] 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 · z Z f F zoom · g (or Alt + drag) a gap, G puts one back · - = speed

{/* ---- the verdict ---- */}

Is beat {row.n} right as the trailer plays it? Confirm writes its edges and walks on. {row.verdict && ( now: {row.verdict === "confirmed" ? "✓ confirmed" : "noted"} )} {confirmedCount} of {(view.rows ?? []).length} confirmed

{row.verdict && ( )} {prevRow && ( ‹ beat {prevRow.n} )} Back to the reel (B) {nextRow && ( beat {nextRow.n} › )}
); }