Archilyzer · Source

archilyzer

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

commit 4889d6add278c2cb1610a8007a72edc72dc76ea3
parent 7fa0c551f949ceed803661bf77ea02b4808b3e6f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 17:55:51 -0500

Merge lane/reel-bench: the reel's walk is its own editor on the clip bench's parts, and reels track their source -- the walk's primitives shared (a media adapter: the source window or "use a file", a rendered file mapped onto source seconds; the playback engine, peaks, the gap editor, the waveform box), the trailer walk on the master's waveform and zoom with handles, nudges, tighten/snap, exact playback and notes; a beat's gaps (cut, played and counted as a clip's gap); each beat's anchor, a reel history sidecar, each beat classified against the take it plays now (the reel's line, walk only the changed beats, clamp/re-point/remove); trailer-beats status/anchor/clamp/repoint/history/gap

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

Diffstat:
Mplans/spin-off-videos.md | 36++++++++++++++++++++++++++++++++++--
Mumtool/app/api/report/audio/route.ts | 42+++++++++++++++++++++++++++++++++++++-----
Aumtool/app/api/report/file/route.ts | 28++++++++++++++++++++++++++++
Mumtool/app/api/report/peaks/route.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mumtool/app/api/report/trailer-beats/route.ts | 23++++++++++++++++++++---
Mumtool/components/projects/ClipBench.tsx | 977++++++-------------------------------------------------------------------------
Mumtool/components/projects/ProjectView.tsx | 2+-
Aumtool/components/projects/bench/BenchWave.tsx | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/benchMedia.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/useBenchPlayer.ts | 539+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/useGapEditor.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/bench/usePeaks.ts | 29+++++++++++++++++++++++++++++
Aumtool/components/projects/reel/ReelBench.tsx | 622+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/reel/ReelCutPanel.tsx | 1+
Mumtool/components/projects/reel/ReelPlay.tsx | 13++++++++-----
Aumtool/components/projects/reel/ReelSource.tsx | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dumtool/components/projects/reel/ReelWalk.tsx | 459-------------------------------------------------------------------------------
Mumtool/components/projects/reel/ReelWalkPage.tsx | 35+++++++++++++++++++++++++----------
Mumtool/components/projects/reel/reelTypes.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/components/projects/reel/useReelPlayer.ts | 12++++++++----
Mumtool/docs/cli.md | 2+-
Mumtool/docs/knobs.md | 26++++++++++++++++++++++++--
Mumtool/docs/report-video.md | 22++++++++++++++++++++--
Mumtool/e2e/reel-play.spec.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/hrefs.ts | 6+++---
Aumtool/lib/report/fileMedia.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/projectFile.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelAnchor.mjs | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelAnchor.test.mjs | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelBenchData.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelHistory.mjs | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/reelPlay.mjs | 47++++++++++++++++++++++++++++++++++++++++-------
Mumtool/lib/report/trailerBeats.mjs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/trailerBeats.test.mjs | 29+++++++++++++++++++++++++++++
Mumtool/lib/report/trailerBeatsCli.mjs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/report/trailerBeatsCli.test.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerCli.mjs | 6+++++-
Mumtool/report-to-video/gaps.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/trailer-gaps.test.mjs | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/trailer.mjs | 116++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
40 files changed, 3589 insertions(+), 1486 deletions(-)

diff --git a/plans/spin-off-videos.md b/plans/spin-off-videos.md @@ -152,14 +152,46 @@ Order 1 → 2 → 3, 4 alongside. 1 and 2 alone remove most of the hand work abo **Cut the trailer** is a job on umtool's runner (`POST /api/report/reel`), the result playing with its local path; a reel with no rendered master says so and links the Takes page. Not done: the reels listed on the Takes page beside their take; Play previewing the cut's snapped edges (it plays the edges as written; the cut moves each ≤ 1 s into its - pause and says so); a waveform on the reel walk; re-cutting a reel when its take is re-rendered (the panel marks a cut - older than its master); the video assistant on a reel note. + pause and says so); ~~a waveform on the reel walk~~ (lane/reel-bench: the walk is its own editor on the clip bench's + parts); re-cutting a reel when its take is re-rendered (the panel marks a cut older than its master, and since + lane/reel-bench one older than its reel); the video assistant on a reel note. - **No umtool page plays a take's trailer, and take cards show no local paths** — lane 4 above; until then the operator gets file paths (operator, 2 Nov: "tell me local file paths for output files"). - **Hand-written spin-off manifests** (`emberparadox/kirsche`'s first manifest was written from a take's, outside umtool's writers — against the standing rule) — lane 2's `umtool spinoff` through `scaffoldReportVideo`'s `timeline` is the fix. +## Reels track their source (lane/reel-bench, 2 Nov) + +A reel is an edit of a rendered master that keeps changing -- a new take, a clip's edges moved, a clip taken out, +the chrome or fx over a clip changed. The model: + +- **The address is source seconds; the anchor is provenance.** A beat is `{ id, start, end, gaps? }` in its clip's + source seconds -- what survives a re-render. Its `anchor` (written by the one writer when a beat is added or edited + against a take: the walk always is, the CLI with `--take`, `anchor --take` for a whole reel) records what it was cut + against: the take, its build (`take.json` `builtAt`), the master's mtime, the source span the clip's segment played + (its cut record's `start`/`end`/`gaps`), the segment's `segKey`, a fingerprint of the chrome and fx over the segment + (the schedule's entry and the receipts/zoom it carries, timed from the segment's start, so a clip that only moved in + the master is not "changed"), and the master span it resolved to (`lib/report/reelAnchor.mjs`). +- **Each beat is classified on load** against the take the reel plays now: unchanged · rerendered (the clip + identical: still good) · edges (the clip's edges or gaps moved; the beat still fits: old vs new) · look (chrome/fx + changed) · clipped (the new limits cut into it: clamp, or re-place) · orphan (the clip is gone: remove, or re-point) + · unanchored. The reel's line says "cut against draft-6; take draft-7 changes beat 7"; the walk can visit only the + changed beats (`?changed=1`); `umtool trailer-beats … status [--json]` is the same reading for an agent, with + `clamp`, `repoint`, `remove` and `anchor` the fixes. +- **History**: every write and undo appends to `promo/<name>-beats.history.json` (old/new per field per beat, adds, + removes, order, settings, the take written against; 200 entries, newest last), modelled on + `common/lib/metadataHistory.ts`. Undo points stay what puts a reel back (40, on disk, across sessions). +- **Cuts name what they read**: a cut's record carries the take's build, the master's mtime and the reel's version + (`reelVersion`: seconds, gaps, crossfade, intro -- not verdicts, labels or anchors), so a cut older than its master + or its reel is said, not guessed from file times. +- Proved on a copy of Kirsche: anchored to draft-6, read against draft-7 (kf3c's end 2773.55 → 2776.07) -- beat 7 + (kf3c) flagged "clip's edges moved", the other 14 "re-rendered, same"; the receipts over kf3e moved 2.5 s in the + master and were (rightly) not flagged. + +Not done: re-placing a clipped beat by its words (a fuzzy find of its old span's cues in the clip's new extent); a +"changed" marker on Play the reel's strip cells; status for a reel's beats on the Trailer page's rows. + ## Open - ~~**The prep cwd dependence**~~ (fixed in `lane/take-writers`): not `projectCache`/`windowsFor` — `lib/paths.mjs`'s diff --git a/umtool/app/api/report/audio/route.ts b/umtool/app/api/report/audio/route.ts @@ -1,8 +1,9 @@ import { spawn } from "node:child_process"; import { stat } from "node:fs/promises"; import { - absOf, ensureWindowFile, notModified, pickWindow, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, + absOf, ensureWindowFile, notModified, pickWindow, resolveClip, resolveReport, windowCacheControl, windowEtag, windowVersion, windowsFor, } from "@/lib/report/serve.mjs"; +import { resolveProjectFile } from "@/lib/report/projectFile.mjs"; import { MAX_DECODE_SPAN, wavHeader } from "@/lib/report/playback.mjs"; import { FFMPEG_BIN } from "umtool-report-to-video/build-video"; @@ -33,6 +34,7 @@ const CHANNELS = 2; export async function GET(request: Request) { const url = new URL(request.url); + if (url.searchParams.get("path")) return fileAudio(request, url); // `take` (the Play view playing a take): the take's clip, its window as the take has it -- as /api/report/raw. const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "", { take: url.searchParams.get("take") || null, @@ -78,6 +80,37 @@ export async function GET(request: Request) { ); } + return wavOf(request, { abs, seek: from - win.from, from, to, headers: { ...cache, "x-window": win.name } }); +} + +/** + * "Use a file" (lane/reel-bench): `?project&path&from&to` -- the sound of a + * span of a rendered FILE of the project, on the file's clock + * (lib/report/projectFile.mjs says what may be read). + */ +async function fileAudio(request: Request, url: URL) { + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const f = await resolveProjectFile(r.project, url.searchParams.get("path") ?? ""); + if ("error" in f) return Response.json({ error: f.error }, { status: f.status }); + const from = Math.max(0, Number(url.searchParams.get("from") ?? 0)); + const to = Number(url.searchParams.get("to") ?? from + MAX_DECODE_SPAN); + if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) return Response.json({ error: "bad span" }, { status: 400 }); + if (to - from > MAX_DECODE_SPAN + 0.5) { + return Response.json({ error: `asked for ${Math.round(to - from)} s; the bench decodes at most ${MAX_DECODE_SPAN} s at once` }, { status: 400 }); + } + const etag = `"af-${f.mtimeMs}-${f.size}"`; + const cache = { "cache-control": url.searchParams.get("v") === String(f.mtimeMs) ? "private, max-age=3600, immutable" : "private, no-cache", etag }; + if (notModified(request, etag)) return new Response(null, { status: 304, headers: cache }); + return wavOf(request, { abs: f.abs, seek: from, from, to, headers: { ...cache, "x-file": f.rel } }); +} + +/** + * [from, to) of `abs` -- `seek` seconds into the file -- decoded by the + * build's ffmpeg to 16-bit PCM WAV; `x-audio-from`/`x-audio-to` say what was + * decoded, on the caller's clock (`from`). + */ +async function wavOf(request: Request, { abs, seek, from, to, headers }: { abs: string; seek: number; from: number; to: number; headers: Record<string, string> }) { // Input seeking with a decode is sample-accurate in ffmpeg: it seeks to the // keyframe before and discards up to the requested time. The build's ffmpeg // (FFMPEG_BIN), so an override reaches this decode too; killed when the @@ -87,7 +120,7 @@ export async function GET(request: Request) { const code = await new Promise<number>((resolve) => { const ff = spawn(FFMPEG_BIN, [ "-nostdin", "-v", "error", - "-ss", (from - win.from).toFixed(6), + "-ss", seek.toFixed(6), "-i", abs, "-t", (to - from).toFixed(6), "-map", "a:0", @@ -124,14 +157,13 @@ export async function GET(request: Request) { return new Response(body, { headers: { "content-type": "audio/wav", - // Cached as hard as the raw file is: immutable under the current `v`, else revalidated. - ...cache, + // Cached as hard as the file is: immutable under the current `v`, else revalidated. + ...headers, // What was actually decoded, in absolute source seconds: the client // places the buffer on the source clock from these, not from what it // asked for. "x-audio-from": String(from), "x-audio-to": String(from + dataBytes / frameBytes / RATE), - "x-window": win.name, }, }); } diff --git a/umtool/app/api/report/file/route.ts b/umtool/app/api/report/file/route.ts @@ -0,0 +1,28 @@ +import { resolveProjectFile } from "@/lib/report/projectFile.mjs"; +import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// A rendered FILE of the project to a <video> element ("use a file", +// lane/reel-bench): ?project&path&v, `path` relative to the project +// (lib/report/projectFile.mjs says what may be served). `v` is the video +// route's contract: the mtime the client was told (`x-video-mtime`); only a +// match is cached, so a re-render under the same name is a new file. +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 new Response(r.error, { status: r.status }); + const f = await resolveProjectFile(r.project, url.searchParams.get("path") ?? ""); + if ("error" in f) return new Response(f.error, { status: f.status }); + const fresh = url.searchParams.get("v") === String(f.mtimeMs); + return rangeResponse(request, { + abs: f.abs, + size: f.size, + headers: { + "content-type": /\.(m4a|mp3|wav)$/i.test(f.rel) ? "audio/mp4" : "video/mp4", + "accept-ranges": "bytes", + "cache-control": fresh ? "private, max-age=3600, immutable" : "private, no-store", + "x-video-mtime": String(f.mtimeMs), + }, + }); +} diff --git a/umtool/app/api/report/peaks/route.ts b/umtool/app/api/report/peaks/route.ts @@ -1,8 +1,9 @@ import { stat } from "node:fs/promises"; import { - absOf, ensureWindowFile, notModified, pickWindow, projectCache, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor, + absOf, ensureWindowFile, notModified, pickWindow, projectCache, resolveClip, resolveReport, windowCacheControl, windowEtag, windowVersion, windowsFor, } from "@/lib/report/serve.mjs"; import { ENV_RATE, analyseMedia } from "@/lib/media"; +import { resolveProjectFile } from "@/lib/report/projectFile.mjs"; export const dynamic = "force-dynamic"; @@ -17,8 +18,59 @@ export const dynamic = "force-dynamic"; // keyed by the file's version, not its name (serve.mjs, "A REPLACED FILE IS A // NEW FILE"): a refetch writes new bytes under the same window name. +/** The envelope as `buckets` min/max pairs over [i0, i1) of it. */ +function bucketsOf(env: ArrayLike<number>, i0: number, i1: number, buckets: number) { + const n = Math.max(1, i1 - i0); + const min: number[] = []; + const max: number[] = []; + for (let b = 0; b < buckets; b += 1) { + const a = i0 + Math.floor((b / buckets) * n); + const z = Math.max(a + 1, i0 + Math.floor(((b + 1) / buckets) * n)); + let p = 0; + for (let i = a; i < z && i < i1; i += 1) if (env[i] > p) p = env[i]; + max.push(p); + min.push(-p); + } + return { min, max }; +} + +/** + * "Use a file" (lane/reel-bench): `?project&path&from&to&n&v` -- the envelope + * of a span of a rendered FILE of the project, on the FILE's clock (the + * bench maps it onto the source; components/projects/bench/benchMedia.ts). + * The whole file is analysed once and cached (analyseMedia, keyed by its + * path, mtime and size); a span is a slice of that. + */ +async function filePeaks(request: Request, url: URL) { + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const f = await resolveProjectFile(r.project, url.searchParams.get("path") ?? ""); + if ("error" in f) return Response.json({ error: f.error }, { status: f.status }); + const buckets = Math.max(64, Math.min(4000, Number(url.searchParams.get("n") ?? 1200))); + const fromQ = Number(url.searchParams.get("from") ?? 0); + const toQ = Number(url.searchParams.get("to") ?? Number.POSITIVE_INFINITY); + if (!Number.isFinite(fromQ) || !(toQ > fromQ)) return Response.json({ error: "bad span" }, { status: 400 }); + const etag = `"pf-${f.mtimeMs}-${f.size}-${fromQ}-${toQ}-${buckets}"`; + const cache = { "cache-control": url.searchParams.get("v") === String(f.mtimeMs) ? "private, max-age=3600, immutable" : "private, no-cache", etag }; + if (notModified(request, etag)) return new Response(null, { status: 304, headers: cache }); + let analysis; + try { + analysis = await analyseMedia(f.abs); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); + } + const env = analysis.peak; + const i0 = Math.max(0, Math.min(env.length, Math.floor(fromQ * ENV_RATE))); + const i1 = Math.max(i0, Math.min(env.length, Math.ceil(Math.min(toQ, env.length / ENV_RATE) * ENV_RATE))); + return Response.json( + { from: i0 / ENV_RATE, to: i1 / ENV_RATE, duration: analysis.duration, path: f.rel, ...bucketsOf(env, i0, i1, buckets) }, + { headers: cache }, + ); +} + export async function GET(request: Request) { const url = new URL(request.url); + if (url.searchParams.get("path")) return filePeaks(request, url); // `take` (walk a take): the take's clip, its window as the take has it -- as /raw. const take = url.searchParams.get("take") || null; const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "", { take }); @@ -54,19 +106,10 @@ export async function GET(request: Request) { const env = analysis.peak; const n = env.length; - const min: number[] = []; - const max: number[] = []; - for (let b = 0; b < buckets; b += 1) { - const i0 = Math.floor((b / buckets) * n); - const i1 = Math.max(i0 + 1, Math.floor(((b + 1) / buckets) * n)); - let p = 0; - for (let i = i0; i < i1 && i < n; i += 1) if (env[i] > p) p = env[i]; - max.push(p); - // analyseMedia's envelope is positive-only. Mirroring it is what makes the - // canvas draw the symmetric shape a waveform is expected to be, rather than - // a row of upward spikes. - min.push(-p); - } + // analyseMedia's envelope is positive-only. Mirroring it (bucketsOf) is what + // makes the canvas draw the symmetric shape a waveform is expected to be, + // rather than a row of upward spikes. + const { min, max } = bucketsOf(env, 0, n, buckets); return Response.json( { diff --git a/umtool/app/api/report/trailer-beats/route.ts b/umtool/app/api/report/trailer-beats/route.ts @@ -1,10 +1,12 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { anchorContextOf } from "@/lib/report/reelPlay.mjs"; import { BeatsStale, DEFAULT_REEL, TRAILER_LIMITS, addTrailerBeat, + anchorTrailerBeats, beatsToken, createReel, introSecondsOf, @@ -43,6 +45,10 @@ export const dynamic = "force-dynamic"; // order {} the cut's order // settings { limit?, xfade?, intro?, title?, take? } null: the default again // undo {} the reel as it was before its last write +// anchor { only? } anchor beats (all, or the 0-based `only`) to `take` +// `take` on add / set / anchor: the take the edit was made against -- each +// beat written gets its anchor (lib/report/reelAnchor.mjs), so the reel can +// say later what changed under it. `set`'s patch may re-point a beat (`id`). // new-reel { name, from?, title? } a new reel (empty, or a copy of `from`) // A stale token is a 409. @@ -94,13 +100,18 @@ export async function POST(request: Request) { 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 { + // The take this edit was made against: its anchors go on the beats written. + const take = typeof body.take === "string" && body.take ? body.take : null; + const ctx = take && ["add", "set", "anchor"].includes(String(body.op)) ? await anchorContextOf(dir, take) : null; + if (take && body.op === "anchor" && !ctx) return Response.json({ error: `take ${take} has no finished master to anchor to` }, { status: 400 }); + const anchorFor = ctx?.anchorFor ?? null; 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, reel }); + await addTrailerBeat(dir, (body.beat ?? {}) as Record<string, unknown>, { token, at: typeof body.at === "number" ? body.at : null, manifest: r.manifest, reel, anchorFor }); break; case "set": - await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token, reel }); + await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token, reel, anchorFor }); break; case "remove": await removeTrailerBeat(dir, Number(body.index), { token, reel }); @@ -114,6 +125,12 @@ export async function POST(request: Request) { case "settings": await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro", "title", "take"].filter((k) => k in body).map((k) => [k, body[k]])), { token, reel }); break; + case "anchor": { + if (!anchorFor) return Response.json({ error: "anchor needs the take to anchor to (take)" }, { status: 400 }); + const only = Array.isArray(body.only) ? body.only.map(Number) : null; + await anchorTrailerBeats(dir, anchorFor, { token, reel, only, take: take ?? "" }); + break; + } case "undo": { const u = await undoTrailerBeats(dir, { token, reel }); did = { undone: u.undone }; @@ -126,7 +143,7 @@ export async function POST(request: Request) { break; } default: - return Response.json({ error: "op must be add, set, remove, move, order, settings, undo or new-reel" }, { status: 400 }); + return Response.json({ error: "op must be add, set, remove, move, order, settings, anchor, undo or new-reel" }, { status: 400 }); } return Response.json({ ok: true, ...did, ...(await view(dir, r.manifest, reel)) }, { headers: noStore }); } catch (e) { diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -10,7 +10,6 @@ import { LatestLine, type WorkingCut } from "./review/WhatPlays"; import { createPortal } from "react-dom"; import Link from "next/link"; import { useRouter } from "next/navigation"; -import Waveform, { type Peaks } from "@/components/Waveform"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { StoredUrlCheckbox, useStoredUrlOffered } from "@/components/clips/StoredUrlOption"; @@ -24,27 +23,21 @@ import CopyCitation from "./bench/CopyCitation"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport"; import EdgeStrip from "./bench/EdgeStrip"; import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts"; -import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom"; +import { ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom"; import TakeWalkStrip from "./bench/TakeWalkStrip"; import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenTools"; // The renderer's own line, imported rather than re-written. A preview that // disagrees with the header by a character is worth less than no preview: you // would only find out twenty minutes into a build. import { attributionLine } from "umtool-report-to-video/attribution"; -import { - MUTE_FADE, - START_LEAD, - bufferSchedule, - covers, - decodeSpan, - elementShouldStop, - muteRamp, - playheadAt, -} from "@/lib/report/playback.mjs"; -import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; import { DETAIL_SPAN } from "@/lib/report/benchZoom.mjs"; // Gaps inside a clip: the rule (the writer's and the build's) and the pieces that play. -import { GAP_FADE, GAP_LIMITS, editGaps, gapSpan, gappedLength, gapsWithin, inGap, keptSpans, validateGaps } from "umtool-report-to-video/gaps"; +import { gapSpan, gappedLength, validateGaps } from "umtool-report-to-video/gaps"; +import { useGapEditor } from "./bench/useGapEditor"; +import { BenchWaveBox, GapTools } from "./bench/BenchWave"; +import { sourceWindowMedia } from "./bench/benchMedia"; +import { useBenchPlayer } from "./bench/useBenchPlayer"; +import { usePeaks } from "./bench/usePeaks"; import { DeckFrame, NeutralFrame, @@ -474,63 +467,6 @@ type WindowPatch = { muteFrom?: number | string; }; -/** - * A decoded span of the cached window, placed on the source clock. `name` is - * the window's name and the version of its bytes (`<name>|<v>`). - */ -type Decoded = { name: string; span: { from: number; to: number }; buf: AudioBuffer }; - -/** - * What is playing, and what the last playback measured. - * - * On the page as data attributes (`data-play-*`), because "did it stop where - * the selection ends" is the claim this bench now makes, and a spec has to be - * able to check it against the audio clock rather than against a feeling. - */ -type PlayInfo = { - engine: "webaudio" | "element"; - state: "playing" | "stopped"; - from: number; - /** The scheduled end, in source seconds. */ - to: number; - rate: number; - /** - * Web Audio at a speed but 1x: the range was time-stretched and played at - * 1x, so it keeps its pitch as the element does (`preservesPitch`). False at - * 1x, and for the element, which keeps the pitch by itself. - */ - stretched: boolean; - /** Context clock: when the source starts and when it is told to stop. */ - ctxStart: number | null; - ctxStop: number | null; - /** - * Where the playback had reached, in source seconds, when the page heard it - * end: the element's own position at its pause, or the context clock at - * `ended` -- which reaches the page a task later than the sound stopped, so - * for Web Audio it is an upper bound and `ctxStop` is the stop itself. - */ - endedAt: number | null; -}; - -/** The playback in flight. One at a time: a new one stops the last. */ -type Session = { - gen: number; - engine: "webaudio" | "element"; - node: AudioBufferSourceNode | null; - gain: GainNode | null; - raf: number; - timers: number[]; - from: number; - to: number; - rate: number; - t0: number; - ctxStop: number; - /** The element's own mute, put back when the picture stops following. */ - mutedBefore: boolean; - /** A playback across gaps: the later pieces' nodes (the first is `node`). */ - more?: AudioBufferSourceNode[]; -}; - export default function ClipBench({ data, navigate, @@ -571,7 +507,6 @@ export default function ClipBench({ // Armed: the next click on the waveform places the mark instead of moving // an edge. const [mutePick, setMutePick] = useState(false); - const [peaks, setPeaks] = useState<Peaks | null>(null); // The cues AROUND the cached window: what is coming, read before paying for // the media. One request, widened only when somebody asks. const [peek, setPeek] = useState<Cue[]>([]); @@ -579,11 +514,6 @@ export default function ClipBench({ // manifest: it is a fact about a matching run, not about the cut. const [cutScore, setCutScore] = useState<number | null>(null); const [peekPad, setPeekPad] = useState(PEEK_STEP); - const [playhead, setPlayhead] = useState<number | null>(null); - const playheadRef = useRef<number | null>(null); - useEffect(() => { - playheadRef.current = playhead; - }, [playhead]); const [note, setNote] = useState<string | null>(null); // A window save refused because a stamp's second (or the mute mark) would fall outside the new // window (manifest.mjs MarksOutside): the refused patch, kept to retry with the fix the @@ -736,27 +666,36 @@ export default function ClipBench({ // The widest cached file is the one the bench draws from: it is how much room // there is to drag before anything has to be fetched. const cached = windows[0] ?? null; - // The version of its bytes in every media URL: a refetch under the same name is a new URL. - const vq = cached?.v ? `&v=${encodeURIComponent(cached.v)}` : ""; const fetchStart = cached?.from ?? 0; const cachedTo = cached?.to ?? 0; - // ---- peaks -------------------------------------------------------------- + // What plays (bench/benchMedia.ts): the widest cached window, on the source clock. + const media = useMemo( + () => sourceWindowMedia({ project: data.project, clip: clip.id, take: takeId, win: cached }), + // The window by its name and the version of its bytes: a refresh returning the same one is the same media. + // eslint-disable-next-line react-hooks/exhaustive-deps + [data.project, clip.id, takeId, cached?.name, cached?.v, cached?.from, cached?.to], + ); + // Read by play() at the moment it schedules, so a mark moved since the last + // render is the one you hear -- without re-creating play() on every nudge. + const muteRef = useRef<number | null>(data.clip.muteFrom); + // The gaps as SAVED: what every playback skips. Read at the moment it schedules, like the mark. + const gapsRef = useRef<Span[]>(data.clip.gaps ?? []); + gapsRef.current = clip.gaps ?? []; + // The playback engine (bench/useBenchPlayer.ts): every bounded range from decoded audio, the picture following. + const { play, stopPlayback, playhead, playInfo, audio, retargetMute } = useBenchPlayer({ + media, + video, + rate: playback.rate, + gapsRef, + muteRef, + warm: { from: clip.start, to: clip.end }, + }); + const playheadRef = useRef<number | null>(null); useEffect(() => { - if (!cached) return; - let live = true; - void (async () => { - const r = await fetch( - `/api/report/peaks?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}${vq}`, - { cache: "no-store" }, - ); - if (!r.ok || !live) return; - setPeaks((await r.json()) as Peaks); - })(); - return () => { - live = false; - }; - }, [cached, data.project, clip.id, tq]); + playheadRef.current = playhead; + }, [playhead]); + const peaks = usePeaks(media); // Follow the playhead in the reading pane, and ONLY while something is // playing: scrolling the words out from under somebody who is reading ahead @@ -904,524 +843,6 @@ export default function ClipBench({ return () => el.removeEventListener("loadedmetadata", again); }, [playback, segment, cached, renderedOpen, deckPreview]); - // ---- audition ----------------------------------------------------------- - // - // EVERY BOUNDED RANGE PLAYS FROM DECODED AUDIO. A selection, an edge, a line - // of the transcript, the auto-audition: each is an AudioBufferSourceNode - // started at an exact offset and stopped at an exact time on the audio - // clock, so what you hear ends where the selection ends, to the sample. The - // <video> used to play these itself and was stopped from `timeupdate`, which - // fires every 15-250 ms -- the stop overran by up to a quarter of a second, - // and by a different amount every time, which is exactly what makes a cut - // between two words impossible to judge by ear. (The old HTML chooser had - // this right; it is the same technique.) - // - // The picture FOLLOWS, muted, and the playhead is read off the audio clock. - // When the decode fails the element plays instead, stopped per animation - // frame by remaining time, and the bench says so. - - /** The decoded audio for the cached window: one decode per window. */ - const decoded = useRef<Decoded | null>(null); - const decoding = useRef<{ key: string; p: Promise<Decoded> } | null>(null); - // The last few time-stretched ranges: a replay at the same speed, and the - // clip's selection stretched ahead of the first play, cost nothing. - const stretchedRanges = useRef<{ key: string; buf: AudioBuffer }[]>([]); - const actx = useRef<AudioContext | null>(null); - const session = useRef<Session | null>(null); - const playGen = useRef(0); - // Pauses the bench asked for itself and has not yet heard the event of. A - // `pause` event is a task, so it arrives AFTER the next playback has started: - // without the count, stopping one playback to start the next would read as - // somebody pausing the picture, and stop the new one. - const selfPauses = useRef(0); - const pauseVideo = useCallback((el: HTMLVideoElement) => { - if (el.paused) return; - selfPauses.current += 1; - el.pause(); - }, []); - // Read by play() at the moment it schedules, so a mark moved since the last - // render is the one you hear -- without re-creating play() on every nudge. - const muteRef = useRef<number | null>(data.clip.muteFrom); - // The gaps as SAVED: what every playback skips. Read at the moment it schedules, like the mark. - const gapsRef = useRef<Span[]>(data.clip.gaps ?? []); - gapsRef.current = clip.gaps ?? []; - const [audio, setAudio] = useState<{ state: "idle" | "loading" | "ready" | "failed"; why?: string }>({ - state: "idle", - }); - const [playInfo, setPlayInfo] = useState<PlayInfo | null>(null); - - /** - * The cached window's sound over (at least) `want`, decoded once. - * - * Through /api/report/audio -- ffmpeg's decode of the same file the player - * loads, as PCM -- and decoded here on an OfflineAudioContext, so no audio - * output is opened before somebody asks to hear something. A buffer belongs - * to no context and plays in the real one. - */ - const ensureDecoded = useCallback( - async (want: { from: number; to: number }): Promise<Decoded> => { - if (!cached) throw new Error("nothing is cached for this clip"); - const have = decoded.current; - if (have && have.name === `${cached.name}|${cached.v ?? ""}` && covers(have.span, want.from, want.to)) return have; - const span = decodeSpan({ from: cached.from, to: cached.to }, want); - const key = `${cached.name}|${cached.v ?? ""}|${span.from}|${span.to}`; - if (decoding.current?.key === key) return decoding.current.p; - const p = (async () => { - setAudio({ state: "loading" }); - const r = await fetch( - `/api/report/audio?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` + - `&file=${encodeURIComponent(cached.name)}&from=${span.from}&to=${span.to}${tq}${vq}`, - ); - if (!r.ok) { - const j = (await r.json().catch(() => null)) as { error?: string } | null; - throw new Error(j?.error ?? `the audio route answered ${r.status}`); - } - const from = Number(r.headers.get("x-audio-from") ?? span.from); - const bytes = await r.arrayBuffer(); - const Offline = - typeof window !== "undefined" ? (window.OfflineAudioContext ?? null) : null; - if (!Offline) throw new Error("this browser has no Web Audio"); - const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes); - const d: Decoded = { name: `${cached.name}|${cached.v ?? ""}`, span: { from, to: from + buf.duration }, buf }; - decoded.current = d; - setAudio({ state: "ready" }); - return d; - })(); - decoding.current = { key, p }; - p.catch((e: unknown) => { - if (decoding.current?.p === p) decoding.current = null; - setAudio({ state: "failed", why: e instanceof Error ? e.message : String(e) }); - }); - return p; - }, - [cached, data.project, clip.id], - ); - - // A different window -- a wider one after "fetch more", or the first after a - // fetch -- is different audio: drop the old decode and start the new one - // now, so the first play after it does not wait. - // (Its name and the version of its bytes: a refetch under the same name is different audio too.) - const cachedName = cached ? `${cached.name}|${cached.v ?? ""}` : null; - useEffect(() => { - decoded.current = null; - decoding.current = null; - setAudio({ state: "idle" }); - if (!cachedName) return; - ensureDecoded({ from: clip.start, to: clip.end }).catch(() => { - /* said in the bench; play() falls back to the element */ - }); - // ensureDecoded changes identity with `cached`, which is this effect's - // whole subject; keying on the NAME is what stops a refresh() that returns - // the same window from decoding it again. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cachedName]); - - /** - * The range [offset, offset + duration) of a decoded buffer, time-stretched - * to `rate` at its own pitch (timeStretch.mjs): played at 1x it lasts - * duration / rate -- the wall length bufferSchedule computed -- and starts - * and ends on the range's own samples. - */ - const stretchFor = useCallback((d: Decoded, offset: number, duration: number, rate: number): AudioBuffer => { - const key = `${d.name}|${d.span.from}|${offset.toFixed(5)}|${duration.toFixed(5)}|${rate}`; - const hit = stretchedRanges.current.find((r) => r.key === key); - if (hit) return hit.buf; - const sr = d.buf.sampleRate; - const a = Math.max(0, Math.min(d.buf.length, Math.round(offset * sr))); - const b = Math.max(a, Math.min(d.buf.length, a + Math.round(duration * sr))); - const channels: Float32Array[] = []; - for (let c = 0; c < d.buf.numberOfChannels; c++) channels.push(d.buf.getChannelData(c).subarray(a, b)); - const out = timeStretch(channels, sr, rate); - const buf = new AudioBuffer({ - length: Math.max(1, out[0]?.length ?? 0), - numberOfChannels: Math.max(1, out.length), - sampleRate: sr, - }); - out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array<ArrayBuffer>, c)); - stretchedRanges.current = [{ key, buf }, ...stretchedRanges.current.filter((r) => r.key !== key)].slice(0, 4); - return buf; - }, []); - - // At a speed but 1x, the clip's selection is stretched while the bench is - // idle, so "play the clip" does not wait for it (a minute of stereo is a - // few hundred ms). - useEffect(() => { - const rate = playback.rate; - if (audio.state !== "ready" || !wantsStretch(rate)) return; - const d = decoded.current; - if (!d) return; - const sch = bufferSchedule(d.span, d.buf.duration, clip.start, clip.end, rate); - if (!sch) return; - const w = window as Window & { - requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number; - cancelIdleCallback?: (id: number) => void; - }; - const run = () => { - if (decoded.current === d) stretchFor(d, sch.offset, sch.duration, rate); - }; - if (w.requestIdleCallback) { - const id = w.requestIdleCallback(run, { timeout: 2000 }); - return () => w.cancelIdleCallback?.(id); - } - const id = window.setTimeout(run, 250); - return () => window.clearTimeout(id); - }, [audio.state, playback.rate, clip.start, clip.end, stretchFor]); - - /** Stop whatever is playing, Web Audio or element, and let go of it. */ - const stopPlayback = useCallback(() => { - const s = session.current; - if (!s) return; - session.current = null; - cancelAnimationFrame(s.raf); - for (const t of s.timers) clearTimeout(t); - for (const node of [s.node, ...(s.more ?? [])]) { - if (!node) continue; - node.onended = null; - try { - node.stop(); - } catch { - /* never started, or already stopped */ - } - node.disconnect(); - } - s.gain?.disconnect(); - const el = video.current; - if (el) { - pauseVideo(el); - el.muted = s.mutedBefore; - } - setPlayInfo((pi) => (pi && pi.state === "playing" ? { ...pi, state: "stopped" } : pi)); - }, [pauseVideo]); - - /** - * The fallback: the element, stopped per animation frame by REMAINING TIME. - * - * `timeupdate` was the old stop and is the overrun this replaces; a frame - * tick that stops once the end is under half a frame away is the best the - * element can do, and the bench says that this is what is playing. - */ - const playElement = useCallback( - (from: number, to: number, gen: number, gaps: Span[] = []) => { - const el = video.current; - if (!el || !cached) return; - const rate = playback.rate; - el.currentTime = Math.max(0, from - fetchStart); - el.playbackRate = rate; - const s: Session = { - gen, - engine: "element", - node: null, - gain: null, - raf: 0, - timers: [], - from, - to, - rate, - t0: 0, - ctxStop: 0, - mutedBefore: el.muted, - }; - session.current = s; - setPlayInfo({ - engine: "element", - state: "playing", - from, - to, - rate, - stretched: false, - ctxStart: null, - ctxStop: null, - endedAt: null, - }); - const stopNow = () => { - if (session.current !== s) return; - pauseVideo(el); - session.current = null; - cancelAnimationFrame(s.raf); - for (const t of s.timers) clearTimeout(t); - el.muted = s.mutedBefore; - setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: el.currentTime + fetchStart } : pi)); - }; - const tick = () => { - if (session.current !== s) return; - const t = el.currentTime + fetchStart; - setPlayhead(t); - // A gap: on past it, as near as a frame tick gets it. - const g = inGap(t, gaps); - if (g && !el.seeking) el.currentTime = g.to - fetchStart; - // The mark, as near as a frame tick gets it. - const m = muteRef.current; - el.muted = s.mutedBefore || (m != null && t >= m); - if (!el.paused && elementShouldStop(t, to, rate)) { - stopNow(); - return; - } - // Inside the last few frames, a timer for the REMAINING time: it lands - // between frames, where the next tick would land up to a frame late. - const remaining = (to - t) / rate; - if (!el.paused && remaining < 0.1 && !s.timers.length) { - s.timers.push(window.setTimeout(stopNow, remaining * 1000)); - } - s.raf = requestAnimationFrame(tick); - }; - s.raf = requestAnimationFrame(tick); - // A rejected play() is normal, not a bug: Chrome refuses unmuted audio on - // a document nobody has interacted with (a typed URL, a fresh tab), and - // an unhandled rejection in that case would be noise. The seek has - // already happened either way. - void el.play().catch(() => {}); - }, - [cached, fetchStart, playback.rate, pauseVideo], - ); - - /** - * Play [from, to], skipping the clip's GAPS as the cut will (gaps.mjs): each - * piece that plays is its own node, abutting the next on the context's - * clock, the join faded out and in by the build's GAP_FADE; the picture is - * seeked at each join. `through` plays the gaps too (a span being chosen for - * one is heard as it is); `extra` is one more span to skip (Hear it: a - * selection heard as cut, before it is written). - */ - const play = useCallback( - async (from: number, to: number, { through = false, extra = null }: { through?: boolean; extra?: Span | null } = {}) => { - const gen = (playGen.current += 1); - stopPlayback(); - if (!cached || !(to > from)) return; - const gaps = through ? [] : gapsWithin([...gapsRef.current, ...(extra ? [extra] : [])].sort((a, b) => a.from - b.from), from, to); - const rate = playback.rate; - // The context is opened HERE, inside the click or the key that asked: - // that gesture is what lets it start. - let ac = actx.current; - if (!ac && typeof window !== "undefined" && window.AudioContext) { - ac = new window.AudioContext(); - actx.current = ac; - } - const resumed = ac && ac.state !== "running" ? ac.resume().catch(() => {}) : null; - let d: Decoded; - try { - if (!ac) throw new Error("this browser has no Web Audio"); - d = await ensureDecoded({ from, to }); - } catch { - if (gen === playGen.current) playElement(from, to, gen, gaps); - return; - } - if (gen !== playGen.current) return; - // Longer than one decode: the element, rather than a second decode in - // the middle of a click. - if (!covers(d.span, from, to)) { - playElement(from, to, gen, gaps); - return; - } - if (resumed) await Promise.race([resumed, new Promise((res) => setTimeout(res, 300))]); - // No gesture has ever reached this document, so the context may not - // start: the same refusal a muted-autoplay policy gives the element, and - // just as silent. - if (gen !== playGen.current || ac!.state !== "running") return; - const ctx = ac!; - // The pieces that play: the whole range without gaps. - const pieces = keptSpans(from, to, gaps) - .map((p) => ({ p, sch: bufferSchedule(d.span, d.buf.duration, p.from, p.to, rate) })) - .filter((x): x is { p: Span; sch: NonNullable<ReturnType<typeof bufferSchedule>> } => !!x.sch); - if (!pieces.length) return; - - // At a speed but 1x the range is stretched at its own pitch and played - // at 1x; a buffer's playbackRate is tape speed, an octave up at 2x. - const stretched = wantsStretch(rate); - const bufs = pieces.map(({ sch }) => (stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf)); - if (gen !== playGen.current) return; - - const gain = ctx.createGain(); - gain.connect(ctx.destination); - // Ahead of now, so start and stop stay on the clock they were computed - // on: a start in the past begins late at the SAME offset. - const t0 = ctx.currentTime + START_LEAD; - // Each piece's place on the wall clock, from t0. - let acc = 0; - const placed = pieces.map(({ p, sch }) => { - const w0 = acc; - acc += sch.wall; - return { p, sch, w0, w1: acc }; - }); - const ctxStop = t0 + acc; - const end = placed[placed.length - 1].p.from + placed[placed.length - 1].sch.duration; - const nodes = placed.map(({ sch, w0 }, k) => { - const node = ctx.createBufferSource(); - node.buffer = bufs[k]; - node.playbackRate.value = stretched ? 1 : rate; - node.connect(gain); - // The stop is a TIME on the context's clock, not start()'s duration - // argument: that one is buffer content, and a clock time means the same - // thing at every speed. - node.start(t0 + w0, stretched ? 0 : sch.offset); - node.stop(t0 + w0 + sch.wall); - return node; - }); - if (placed.length === 1) { - const m = muteRamp(muteRef.current, from, from + placed[0].sch.duration, rate); - if (m) { - if (m.at <= 0) gain.gain.setValueAtTime(0, t0); - else { - gain.gain.setValueAtTime(1, t0 + m.at); - gain.gain.linearRampToValueAtTime(0, t0 + m.at + m.fade); - } - } - } else { - // Across gaps: the joins' fades and the mute mark, as one level on the wall clock. - const fadeW = GAP_FADE / rate; - const mark = muteRef.current; - let markW: number | null = null; - if (mark != null) { - if (mark <= from) markW = 0; - else { - const k = placed.findIndex((x) => mark <= x.p.from + x.sch.duration); - if (k >= 0) markW = placed[k].w0 + Math.max(0, mark - placed[k].p.from) / rate; - } - } - const muteFadeW = MUTE_FADE / rate; - const level = (w: number) => { - let v = 1; - placed.forEach((x, k) => { - if (w < x.w0 || w > x.w1) return; - if (k > 0 && w < x.w0 + fadeW) v = Math.min(v, (w - x.w0) / fadeW); - if (k < placed.length - 1 && w > x.w1 - fadeW) v = Math.min(v, (x.w1 - w) / fadeW); - }); - if (markW != null) { - if (w >= markW) v = 0; - else if (w > markW - muteFadeW) v = Math.min(v, (markW - w) / muteFadeW); - } - return Math.max(0, Math.min(1, v)); - }; - const pts = new Set<number>([0, acc]); - placed.forEach((x, k) => { - if (k > 0) [x.w0, x.w0 + fadeW].forEach((w) => pts.add(w)); - if (k < placed.length - 1) [x.w1 - fadeW, x.w1 - 1e-4].forEach((w) => pts.add(w)); - }); - if (markW != null) [markW - muteFadeW, markW].forEach((w) => pts.add(Math.max(0, w))); - const ws = [...pts].filter((w) => w >= 0 && w <= acc).sort((a, b) => a - b); - gain.gain.setValueAtTime(level(ws[0]), t0 + ws[0]); - for (const w of ws.slice(1)) gain.gain.linearRampToValueAtTime(level(w), t0 + w); - } - const node = nodes[0]; - - const el = video.current; - const s: Session = { - gen, - engine: "webaudio", - node, - gain, - raf: 0, - timers: [], - from, - to: end, - rate, - t0, - ctxStop, - mutedBefore: el?.muted ?? false, - ...(nodes.length > 1 ? { more: nodes.slice(1) } : {}), - }; - session.current = s; - setPlayInfo({ - engine: "webaudio", - state: "playing", - from, - to: s.to, - rate, - stretched, - ctxStart: t0, - ctxStop, - endedAt: null, - }); - /** The source second playing `w` wall seconds in: its piece's, from its first. */ - const posAt = (w: number) => { - const x = placed.find((q) => w <= q.w1) ?? placed[placed.length - 1]; - return Math.min(x.p.from + x.sch.duration, x.p.from + Math.max(0, w - x.w0) * rate); - }; - - // The picture follows, muted. It is not what is being judged; a few - // milliseconds of drift between the two is not worth a sync loop. - if (el) { - el.muted = true; - el.playbackRate = rate; - el.currentTime = Math.max(0, from - fetchStart); - s.timers.push( - window.setTimeout(() => { - if (session.current === s) void el.play().catch(() => {}); - }, START_LEAD * 1000), - ); - // Each join: the picture jumps with the sound. - for (const x of placed.slice(1)) { - s.timers.push( - window.setTimeout(() => { - if (session.current === s) el.currentTime = Math.max(0, x.p.from - fetchStart); - }, (START_LEAD + x.w0) * 1000), - ); - } - } - - const last = nodes[nodes.length - 1]; - last.onended = () => { - if (session.current !== s) return; - // How late the context clock reads at `ended`, mapped back onto the - // source: what the playback measured, for the bench's own record. - const late = ctx.currentTime - ctxStop; - session.current = null; - cancelAnimationFrame(s.raf); - for (const t of s.timers) clearTimeout(t); - for (const n of nodes) n.disconnect(); - gain.disconnect(); - if (el) { - pauseVideo(el); - el.muted = s.mutedBefore; - } - setPlayhead(s.to); - setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: s.to + Math.max(0, late) * rate } : pi)); - }; - - // The playhead at ~30 Hz, not every frame: each update re-renders the - // bench, and the line moving smoothly is not worth that at 60. - // - // And the picture is pulled back to the sound when it drifts by more - // than a quarter second -- which it does after a seek into a file that - // is only partly loaded, where the element starts late by however long - // the bytes took. - let painted = -1; - let checked = t0; - const tick = () => { - if (session.current !== s) return; - const now = ctx.currentTime; - const pos = placed.length === 1 ? playheadAt(from, t0, now, rate, placed[0].sch.duration) : posAt(Math.max(0, now - t0)); - if (now - painted >= 1 / 30) { - painted = now; - setPlayhead(pos); - } - if (el && now - checked >= 0.5 && now > t0) { - checked = now; - const want = pos - fetchStart; - if (!el.seeking && Math.abs(el.currentTime - want) > 0.25) el.currentTime = want; - } - s.raf = requestAnimationFrame(tick); - }; - s.raf = requestAnimationFrame(tick); - }, - [cached, fetchStart, playback.rate, ensureDecoded, playElement, stopPlayback, pauseVideo, stretchFor], - ); - - // A speed change mid-playback would leave the picture and the sound at two - // rates: stop, and the next play is at the new one. - useEffect(() => { - stopPlayback(); - }, [playback.rate, stopPlayback]); - - // Let go of the audio output with the bench. - useEffect( - () => () => { - stopPlayback(); - void actx.current?.close().catch(() => {}); - actx.current = null; - }, - [stopPlayback], - ); - // ---- auto-audition ------------------------------------------------------- // // Off by default, and when it is on it waits for the element rather than @@ -1453,41 +874,6 @@ export default function ClipBench({ }; }, [playback.auto, cached, clip.id, clip.start, clip.end, play]); - // The element's own controls: unbounded "play from here", which stays on the - // element. Its clock moves the playhead only while nothing bounded is - // playing -- during a Web Audio playback the muted picture would otherwise - // fight the audio clock for it. Pausing the picture by hand stops the sound - // it is following. - useEffect(() => { - const el = video.current; - if (!el) return; - // While it plays by itself. A paused element's `timeupdate` is the one its - // own pause fires -- after a Web Audio playback, that is the muted picture - // stopping wherever it had got to, which is not where the sound stopped. - const tick = () => { - if (!session.current && !el.paused) setPlayhead(el.currentTime + fetchStart); - }; - // A scrub on the paused element's own bar. - const seeked = () => { - if (!session.current) setPlayhead(el.currentTime + fetchStart); - }; - const paused = () => { - if (selfPauses.current > 0) { - selfPauses.current -= 1; - return; - } - if (session.current) stopPlayback(); - }; - el.addEventListener("timeupdate", tick); - el.addEventListener("seeked", seeked); - el.addEventListener("pause", paused); - return () => { - el.removeEventListener("timeupdate", tick); - el.removeEventListener("seeked", seeked); - el.removeEventListener("pause", paused); - }; - }, [fetchStart, stopPlayback, cachedName]); - // ---- the selection ------------------------------------------------------ // // Clamped to the cached file. Past its edge the handle stops and the "fetch @@ -1851,31 +1237,6 @@ export default function ClipBench({ // waveform, by a nudge -- and every playback here mutes at it, so a mark is // heard before it is saved. - /** Re-aim the playback in flight at a new mark, from now. */ - const retargetMute = useCallback((t: number | null) => { - const s = session.current; - const ctx = actx.current; - if (!s || s.engine !== "webaudio" || !s.gain || !ctx) return; - const now = ctx.currentTime; - const g = s.gain.gain; - g.cancelScheduledValues(now); - const pos = playheadAt(s.from, s.t0, now, s.rate, s.to - s.from); - const m = t == null ? null : muteRamp(t, pos, s.to, s.rate); - if (!m) { - g.setValueAtTime(1, now); - return; - } - if (m.at <= 0) { - // Already past the mark: fade out from here. - g.setValueAtTime(g.value, now); - g.linearRampToValueAtTime(0, now + MUTE_FADE / s.rate); - return; - } - g.setValueAtTime(1, now); - g.setValueAtTime(1, now + m.at); - g.linearRampToValueAtTime(0, now + m.at + m.fade); - }, []); - /** * Put the mark at `t`, inside the selection. `audition` plays across it -- * three seconds of sound and two of what should now be silence -- the way a @@ -1923,16 +1284,6 @@ export default function ClipBench({ // -- and leaves an undo point (auto-before-gaps) -- and Undo here writes the // list back as it was. The rule is checked here first, with the same // sentences, so a refusal is said before anything is sent. - const [gapSel, setGapSel] = useState<Span | null>(null); - const [gapPick, setGapPick] = useState(false); - const [gapUndo, setGapUndo] = useState<{ gaps: Span[]; what: string } | null>(null); - // A different clip: nothing selected, nothing to undo. - useEffect(() => { - setGapSel(null); - setGapPick(false); - setGapUndo(null); - }, [clip.id]); - /** Why `gaps` cannot be written on this clip as saved (the writer's own check), or null. */ const gapRefusal = useCallback( (gaps: Span[]) => { const errs = validateGaps({ type: "clip", id: clip.id, start: clip.start, end: clip.end, cutStart: clip.cutStart, cutEnd: clip.cutEnd, muteFrom: clip.muteFrom, gaps }, "gap"); @@ -1940,91 +1291,17 @@ export default function ClipBench({ }, [clip.id, clip.start, clip.end, clip.cutStart, clip.cutEnd, clip.muteFrom], ); - const writeGaps = useCallback( - async (patch: Record<string, unknown>, next: Span[], what: string) => { - const why = gapRefusal(next); - if (why) { - setNote(`not cut: ${why}`); - return false; - } - const before = clip.gaps ?? []; - const ok = await save(patch); - if (ok) { - setGapUndo({ gaps: before, what }); - setNote(`${what} — the cut plays ${gappedLength(gapSpan(clip).from, gapSpan(clip).to, next).toFixed(2)} s, one segment`); - } - return ok; - }, - [gapRefusal, save, clip], - ); - const cutGap = useCallback(async () => { - const s = gapSel; - if (!s) return; - const g = { from: round2(s.from), to: round2(s.to) }; - let next: Span[]; - try { - next = editGaps(clip.gaps ?? [], { add: g }); - } catch (e) { - setNote(e instanceof Error ? e.message : String(e)); - return; - } - const ok = await writeGaps({ gapAdd: g }, next, `cut ${hms(g.from)}–${hms(g.to)} out`); - if (ok) { - setGapSel(null); - setGapPick(false); - } - }, [gapSel, clip.gaps, writeGaps]); - const removeGap = useCallback( - (g: Span) => { - const next = (clip.gaps ?? []).filter((x) => x.from !== g.from || x.to !== g.to); - void writeGaps({ gapRemove: (g.from + g.to) / 2 }, next, `put ${hms(g.from)}–${hms(g.to)} back`); - }, - [clip.gaps, writeGaps], - ); - /** `G`: the gap the playhead is in (or at the edge of). */ - const removeGapAt = useCallback( - (t: number | null) => { - const g = t == null ? null : (clip.gaps ?? []).find((x) => t >= x.from - 0.05 && t <= x.to + 0.05); - if (!g) { - setNote("the playhead is not on a gap — play to it, or click its band"); - return; - } - removeGap(g); - }, - [clip.gaps, removeGap], - ); - const undoGap = useCallback(() => { - const u = gapUndo; - if (!u) return; - void save({ gaps: u.gaps }).then((ok) => { - if (!ok) return; - setGapUndo(null); - setNote(`undone — ${u.what} is reversed`); - }); - }, [gapUndo, save]); - /** A span dragged for a gap: kept inside the cut; under the shortest gap on release, dropped and said. */ - const selectGap = useCallback( - (s: Span, done: boolean) => { - const span = gapSpan(clip); - const from = Math.max(span.from, s.from); - const to = Math.min(span.to, s.to); - if (!done) { - setGapSel(to > from ? { from, to } : null); - return; - } - if (to - from < GAP_LIMITS.min) { - setGapSel(null); - if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`); - return; - } - setGapSel({ from, to }); - const why = gapRefusal(editGaps(clip.gaps ?? [], { add: { from: round2(from), to: round2(to) } })); - setNote(why ? `this span cannot be cut: ${why}` : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`); - }, - [clip, gapRefusal], - ); - // Alt + drag on the waveform selects a gap's span without arming anything. - const altDrag = useRef<{ id: number; at: number } | null>(null); + // bench/useGapEditor.ts, writing through the window writer: `gapAdd` / `gapRemove`, Undo the whole list. + const gap = useGapEditor({ + key: clip.id, + gaps: clip.gaps ?? [], + span: gapSpan(clip), + refusal: gapRefusal, + write: (op, _next) => save("add" in op ? { gapAdd: op.add } : "remove" in op ? { gapRemove: (op.remove.from + op.remove.to) / 2 } : { gaps: op.set }), + said: (next) => `the cut plays ${gappedLength(gapSpan(clip).from, gapSpan(clip).to, next).toFixed(2)} s, one segment`, + setNote, + fmt: hms, + }); // ---- the zoom ---------------------------------------------------------------- // What the waveform shows of the cached window (bench/GapsZoom.tsx). Fit -- the @@ -2166,15 +1443,15 @@ export default function ClipBench({ zoom.fit(); break; case "F": - zoom.to(gapSel ?? sel); + zoom.to(gap.sel ?? sel); break; // Gaps: g cuts the selected span (or starts selecting one), G puts back the gap at the playhead. case "g": - if (gapSel) void cutGap(); - else setGapPick((v) => !v); + if (gap.sel) void gap.cut(); + else gap.setPick((v) => !v); break; case "G": - removeGapAt(playheadRef.current); + gap.removeAt(playheadRef.current); break; case "Escape": // Reject ▾'s reasons are up: the Escape closes them (RejectClip), nothing else. @@ -2182,9 +1459,9 @@ export default function ClipBench({ // (React flushes that discrete update in a microtask between the two window // listeners, so isOpen() is false by now) and marked the event handled. if (e.defaultPrevented || rejectCtl.current?.isOpen()) return; - if (gapPick || gapSel) { - setGapPick(false); - setGapSel(null); + if (gap.pick || gap.sel) { + gap.setPick(false); + gap.setSel(null); break; } if (!mutePick) return; @@ -2219,10 +1496,10 @@ export default function ClipBench({ clearMute, placeMute, zoom, - gapSel, - gapPick, - cutGap, - removeGapAt, + gap.sel, + gap.pick, + gap.cut, + gap.removeAt, ]); const refresh = useCallback(async (): Promise<ClipBenchData | null> => { @@ -3427,7 +2704,7 @@ export default function ClipBench({ <video ref={video} data-testid="clip-video" - src={`/api/report/raw?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}${vq}`} + src={media.src ?? undefined} // object-contain, because the height is now whatever is left // rather than whatever 16:9 asks for. // The picture and the words SHARE what is left, 3:2, rather @@ -3691,69 +2968,25 @@ export default function ClipBench({ <div className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> {/* Zoomed: round ticks over what is shown. */} {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} - <div - ref={zoom.ref} - data-wave-box="" - data-wave-vis={`${zoom.vis.from}-${zoom.vis.to}`} - className="relative" - // Alt + drag: a span for a gap, never an edge (the waveform's own drag is held off). - onPointerDownCapture={(e) => { - if (!e.altKey || gapPick || mutePick) return; - e.preventDefault(); - e.stopPropagation(); - e.currentTarget.setPointerCapture(e.pointerId); - const r = e.currentTarget.getBoundingClientRect(); - const at = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; - altDrag.current = { id: e.pointerId, at }; - selectGap({ from: at, to: at }, false); - }} - onPointerMoveCapture={(e) => { - const d = altDrag.current; - if (!d || d.id !== e.pointerId) return; - e.stopPropagation(); - const r = e.currentTarget.getBoundingClientRect(); - const t = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; - selectGap({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); - }} - onPointerUpCapture={(e) => { - const d = altDrag.current; - if (!d || d.id !== e.pointerId) return; - e.stopPropagation(); - altDrag.current = null; - const r = e.currentTarget.getBoundingClientRect(); - const t = zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; - selectGap({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); - }} + <BenchWaveBox + zoom={zoom} + sel={sel} + cand={{ from: clip.start, to: clip.end }} + cues={cues} + peaks={peaks} + playhead={playhead} + onSel={onSel} + gap={gap} + gaps={clip.gaps ?? []} + silences={renderEdges?.silences ?? null} + words={nearWords?.words ?? null} + busy={!!busy} + held={mutePick} > - <Waveform - view={zoom.vis} - sel={sel} - cand={{ from: clip.start, to: clip.end }} - words={cues.map((c) => ({ start: c.start, end: c.end, w: c.text.slice(0, 24) }))} - peaks={peaks} - playhead={playhead} - height={104} - onSel={onSel} - onReachEdge={() => { - /* widening is a FETCH here, not a redraw -- see the button below */ - }} - /> {/* The mute mark over the waveform: a line where the sound stops and a hatch over what is silent to the end of the selection. In the interaction colour, like the handles -- it is an edit, not a reading -- and never in the way of a drag. */} - {/* The gaps, the span being selected for one, and close in the silences and the pauses between words. */} - <GapLayer - vis={zoom.vis} - gaps={clip.gaps ?? []} - selection={gapSel} - picking={gapPick && !mutePick} - silences={renderEdges?.silences ?? null} - words={nearWords?.words ?? null} - busy={!!busy} - onRemove={removeGap} - onSelect={selectGap} - /> {mute != null && mute >= zoom.vis.from && mute <= zoom.vis.to && ( <> <div @@ -3789,81 +3022,19 @@ export default function ClipBench({ }} /> )} - </div> + </BenchWaveBox> {/* Zoomed: the whole cached window, what is shown of it -- drag to pan. */} {zoom.zoomed && <ZoomOverview zoom={zoom} whole={view} peaks={peaks} sel={sel} gaps={clip.gaps ?? []} />} {/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */} <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> - {/* ---- GAPS inside the clip ---- - Seconds cut out of its middle: it renders as one segment of - jump cuts. Written at once (not drafted like the edges), and - every playback here skips them, as the cut will. */} - <span data-gaps={(clip.gaps ?? []).map((g) => `${g.from}-${g.to}`).join(",")} className="flex flex-wrap items-center gap-1.5"> - {(clip.gaps ?? []).length ? ( - <span data-gaps-summary="" className="num text-[var(--color-text)]"> - {(clip.gaps ?? []).length} gap{(clip.gaps ?? []).length === 1 ? "" : "s"}{" "} - <span className="text-[var(--color-dim)]"> - (the cut plays {gappedLength(gapSpan(clip).from, gapSpan(clip).to, clip.gaps ?? []).toFixed(2)} s of{" "} - {(gapSpan(clip).to - gapSpan(clip).from).toFixed(2)} s, one segment) - </span> - </span> - ) : ( - <span className="text-[var(--color-dim)]">no gaps — the cut plays whole</span> - )} - <button - type="button" - data-gap-pick={gapPick ? "armed" : ""} - aria-pressed={gapPick} - className={`${buttonVariants({ variant: "outline", size: "sm" })}${gapPick ? " bg-panel-2 border-muted" : ""}`} - title="drag on the waveform to select seconds to cut out of the clip (g; or hold Alt and drag; Esc cancels)" - onClick={() => setGapPick((v) => !v)} - > - {gapPick ? "Drag on the waveform…" : "Select a gap"} - </button> - {gapSel && ( - <> - <button - type="button" - data-gap-cut="" - className={buttonVariants({ size: "sm" })} - disabled={!!busy || gapSel.to - gapSel.from < GAP_LIMITS.min} - title="cut the selected seconds out of the clip (g)" - onClick={() => void cutGap()} - > - Cut gap {hms(gapSel.from)}–{hms(gapSel.to)} ({(gapSel.to - gapSel.from).toFixed(2)} s) - </button> - <button - type="button" - data-gap-hear="" - className={buttonVariants({ variant: "outline", size: "sm" })} - title="two seconds either side, the selection skipped: the jump as the cut will play it" - onClick={() => void play(Math.max(sel.from, gapSel.from - 2), Math.min(sel.to, gapSel.to + 2), { extra: gapSel })} - > - Hear it - </button> - <button - type="button" - data-gap-play-span="" - className={buttonVariants({ variant: "outline", size: "sm" })} - title="play what the selection would take out" - onClick={() => void play(gapSel.from, gapSel.to, { through: true })} - > - Play the span - </button> - </> - )} - {gapUndo && ( - <button type="button" data-gap-undo="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={!!busy} onClick={undoGap} title={`undo: ${gapUndo.what}`}> - Undo - </button> - )} - </span> + {/* ---- GAPS inside the clip (bench/BenchWave.tsx GapTools) ---- */} + <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapSpan(clip)} sel={sel} busy={!!busy} fmt={hms} play={play} /> <TightenButtons tools={edgeTools} busy={!!busy} /> <span className="micro max-md:hidden"> <kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "} <kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead </span> - <ZoomControls zoom={zoom} whole={view} selection={gapSel ?? sel} playhead={playhead} /> + <ZoomControls zoom={zoom} whole={view} selection={gap.sel ?? sel} playhead={playhead} /> </div> </div> diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -95,7 +95,7 @@ export default async function ProjectView({ 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} />; + return <ReelWalkPage project={project} reel={search.reel} take={search.take} beat={search.beat} changed={search.changed === "1"} />; } 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/bench/BenchWave.tsx b/umtool/components/projects/bench/BenchWave.tsx @@ -0,0 +1,214 @@ +"use client"; + +import { useRef } from "react"; +import Waveform, { type Peaks } from "@/components/Waveform"; +import { buttonVariants } from "@/components/ui/button"; +import { GAP_LIMITS, gappedLength } from "umtool-report-to-video/gaps"; +import { GapLayer, type WaveZoom } from "./GapsZoom"; +import type { Span } from "./benchMedia"; +import type { GapEditor } from "./useGapEditor"; + +// --------------------------------------------------------------------------- +// THE BENCH'S WAVEFORM AND ITS GAPS (lifted out of ClipBench.tsx; shared with +// the reel's walk, lane/reel-bench): the zoomed waveform with its handles, +// Alt + drag selecting a span for a gap (the waveform's own drag held off), +// the gaps' bands and close-in pauses and words (GapLayer), any marks the +// bench draws over it (`children`), and the gaps' row of tools under it. +// Source seconds throughout; what plays is the bench's media's business. +// --------------------------------------------------------------------------- + +type Cue = { start: number; end: number; text: string }; + +/** The waveform box: Waveform, GapLayer and the bench's own overlays, with Alt + drag for a gap. */ +export function BenchWaveBox({ + zoom, + sel, + cand, + cues, + peaks, + playhead, + onSel, + gap, + gaps, + silences, + words, + busy, + held = false, + children, +}: { + zoom: WaveZoom; + sel: Span; + /** The saved extent, drawn behind the selection. */ + cand: Span; + cues: Cue[]; + peaks: Peaks | null; + playhead: number | null; + onSel: (next: Span, dragging: boolean, edge?: "start" | "end" | null) => void; + gap: GapEditor; + gaps: Span[]; + silences: Span[] | null; + words: { start: number; end?: number; w?: string }[] | null; + busy: boolean; + /** Another pick is armed (the mute mark's): Alt + drag and the gap pick stand down. */ + held?: boolean; + children?: React.ReactNode; +}) { + const altDrag = useRef<{ id: number; at: number } | null>(null); + const zspan = Math.max(1e-6, zoom.vis.to - zoom.vis.from); + const tAt = (e: React.PointerEvent<HTMLDivElement>) => { + const r = e.currentTarget.getBoundingClientRect(); + return zoom.vis.from + Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))) * zspan; + }; + return ( + <div + ref={zoom.ref} + data-wave-box="" + data-wave-vis={`${zoom.vis.from}-${zoom.vis.to}`} + className="relative" + // Alt + drag: a span for a gap, never an edge (the waveform's own drag is held off). + onPointerDownCapture={(e) => { + if (!e.altKey || gap.pick || held) return; + e.preventDefault(); + e.stopPropagation(); + e.currentTarget.setPointerCapture(e.pointerId); + const at = tAt(e); + altDrag.current = { id: e.pointerId, at }; + gap.select({ from: at, to: at }, false); + }} + onPointerMoveCapture={(e) => { + const d = altDrag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + const t = tAt(e); + gap.select({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); + }} + onPointerUpCapture={(e) => { + const d = altDrag.current; + if (!d || d.id !== e.pointerId) return; + e.stopPropagation(); + altDrag.current = null; + const t = tAt(e); + gap.select({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); + }} + > + <Waveform + view={zoom.vis} + sel={sel} + cand={cand} + words={cues.map((c) => ({ start: c.start, end: c.end, w: c.text.slice(0, 24) }))} + peaks={peaks} + playhead={playhead} + height={104} + onSel={onSel} + onReachEdge={() => { + /* widening is the bench's own button, never a redraw */ + }} + /> + {/* The gaps, the span being selected for one, and close in the silences and the pauses between words. */} + <GapLayer + vis={zoom.vis} + gaps={gaps} + selection={gap.sel} + picking={gap.pick && !held} + silences={silences} + words={words} + busy={busy} + onRemove={gap.remove} + onSelect={gap.select} + /> + {children} + </div> + ); +} + +/** + * The gaps' tools under the waveform: what they leave, Select a gap, Cut gap, + * Hear it, Play the span, Undo. `span` is what the gaps are inside (the + * clip's cut, a beat), `noun` what plays as one ("the cut", "the beat"). + */ +export function GapTools({ + gap, + gaps, + span, + sel, + busy, + fmt, + play, + noun = "the cut", + of = "the clip", +}: { + gap: GapEditor; + gaps: Span[]; + span: Span; + sel: Span; + busy: boolean; + fmt: (t: number) => string; + play: (from: number, to: number, o?: { through?: boolean; extra?: Span | null }) => unknown; + noun?: string; + of?: string; +}) { + const g = gap.sel; + return ( + // Seconds cut out of its middle: it plays as one run of jump cuts. Written + // at once (not drafted like the edges), and every playback here skips them. + <span data-gaps={gaps.map((x) => `${x.from}-${x.to}`).join(",")} className="flex flex-wrap items-center gap-1.5"> + {gaps.length ? ( + <span data-gaps-summary="" className="num text-[var(--color-text)]"> + {gaps.length} gap{gaps.length === 1 ? "" : "s"}{" "} + <span className="text-[var(--color-dim)]"> + ({noun} plays {gappedLength(span.from, span.to, gaps).toFixed(2)} s of {(span.to - span.from).toFixed(2)} s, one segment) + </span> + </span> + ) : ( + <span className="text-[var(--color-dim)]">no gaps — {noun} plays whole</span> + )} + <button + type="button" + data-gap-pick={gap.pick ? "armed" : ""} + aria-pressed={gap.pick} + className={`${buttonVariants({ variant: "outline", size: "sm" })}${gap.pick ? " bg-panel-2 border-muted" : ""}`} + title={`drag on the waveform to select seconds to cut out of ${of} (g; or hold Alt and drag; Esc cancels)`} + onClick={() => gap.setPick((v) => !v)} + > + {gap.pick ? "Drag on the waveform…" : "Select a gap"} + </button> + {g && ( + <> + <button + type="button" + data-gap-cut="" + className={buttonVariants({ size: "sm" })} + disabled={busy || g.to - g.from < GAP_LIMITS.min} + title={`cut the selected seconds out of ${of} (g)`} + onClick={() => void gap.cut()} + > + Cut gap {fmt(g.from)}–{fmt(g.to)} ({(g.to - g.from).toFixed(2)} s) + </button> + <button + type="button" + data-gap-hear="" + className={buttonVariants({ variant: "outline", size: "sm" })} + title="two seconds either side, the selection skipped: the jump as the cut will play it" + onClick={() => void play(Math.max(sel.from, g.from - 2), Math.min(sel.to, g.to + 2), { extra: g })} + > + Hear it + </button> + <button + type="button" + data-gap-play-span="" + className={buttonVariants({ variant: "outline", size: "sm" })} + title="play what the selection would take out" + onClick={() => void play(g.from, g.to, { through: true })} + > + Play the span + </button> + </> + )} + {gap.undo && ( + <button type="button" data-gap-undo="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={busy} onClick={gap.undoLast} title={`undo: ${gap.undo.what}`}> + Undo + </button> + )} + </span> + ); +} diff --git a/umtool/components/projects/bench/benchMedia.ts b/umtool/components/projects/bench/benchMedia.ts @@ -0,0 +1,125 @@ +import type { Peaks } from "@/components/Waveform"; +import { fileAt, fileSpans, peaksOnSource, sourceAt, type FileMap } from "@/lib/report/fileMedia.mjs"; + +// --------------------------------------------------------------------------- +// WHAT A BENCH PLAYS, behind one shape (lane/reel-bench): the bench's own +// work -- edges, gaps, cues, words, the mute mark -- is always in SOURCE +// seconds; a media adapter says where those seconds are in the picture and +// the sound. +// +// sourceWindow the clip's cached raw window (the clip bench): the decode +// clock IS the source clock, the element is offset by the +// window's start (`fetchStart`), and a clip's gaps are still +// in the file -- playback skips them. +// renderedFile a rendered file in the project (a take's master, the +// reel's walk) with its map onto the clip's source +// (lib/report/fileMedia.mjs): the decode clock and the +// element are the FILE's clock, and the render's own gaps +// are already out of it. +// +// The playback engine (useBenchPlayer.ts) schedules on the decode clock and +// reports the playhead back in source seconds; the waveform's peaks come +// back on the source clock either way. +// --------------------------------------------------------------------------- + +export type Span = { from: number; to: number }; + +export type BenchMedia = { + kind: "source" | "file"; + /** What is playing, for the decode cache: a new key is new audio. Null: nothing to play. */ + key: string | null; + /** The <video>'s src. */ + src: string | null; + /** The source seconds it holds: how far an edge may go. */ + span: Span | null; + /** The decode clock's bounds (decodeSpan picks inside them). */ + clock: Span | null; + /** A source second on the decode clock, and back. */ + clockOf: (src: number) => number; + sourceOfClock: (c: number) => number; + /** A decode-clock second as the element's currentTime, and back. */ + elOf: (c: number) => number; + clockOfEl: (t: number) => number; + /** Source-second spans to leave out, as decode-clock spans (the render's own gaps are already out of a file). */ + clockGaps: (gaps: Span[]) => Span[]; + /** The decoded sound of a decode-clock span: a WAV, `x-audio-from` its first second on that clock. */ + audioUrl: (span: Span) => string; + /** The waveform's envelope, and how to put it on the source clock. */ + peaksUrl: string | null; + peaksOnSource: (p: Peaks) => Peaks; +}; + +const enc = encodeURIComponent; + +/** The clip bench's media: the widest cached window of the clip, its bytes' version in every URL. */ +export function sourceWindowMedia({ + project, + clip, + take, + win, +}: { + project: string; + clip: string; + take: string | null; + win: { name: string; from: number; to: number; v?: string | null } | null; +}): BenchMedia { + const tq = take ? `&take=${enc(take)}` : ""; + const vq = win?.v ? `&v=${enc(win.v)}` : ""; + const fetchStart = win?.from ?? 0; + const id = (t: number) => t; + return { + kind: "source", + key: win ? `${win.name}|${win.v ?? ""}` : null, + src: win ? `/api/report/raw?project=${enc(project)}&clip=${enc(clip)}&file=${enc(win.name)}${tq}${vq}` : null, + span: win ? { from: win.from, to: win.to } : null, + clock: win ? { from: win.from, to: win.to } : null, + clockOf: id, + sourceOfClock: id, + elOf: (c) => c - fetchStart, + clockOfEl: (t) => t + fetchStart, + clockGaps: (gaps) => gaps, + audioUrl: (s) => + win + ? `/api/report/audio?project=${enc(project)}&clip=${enc(clip)}&file=${enc(win.name)}&from=${s.from}&to=${s.to}${tq}${vq}` + : "", + peaksUrl: win ? `/api/report/peaks?project=${enc(project)}&clip=${enc(clip)}&file=${enc(win.name)}${tq}${vq}` : null, + peaksOnSource: (p) => p, + }; +} + +/** + * A rendered file of the project (`path`, project-relative) over the source + * seconds `span` of one clip, through `map`. `v` the file's version (its mtime). + */ +export function renderedFileMedia({ + project, + path, + v, + map, + span, +}: { + project: string; + path: string; + v: string | number | null; + map: FileMap; + span: Span; +}): BenchMedia { + const q = `project=${enc(project)}&path=${enc(path)}${v ? `&v=${enc(String(v))}` : ""}`; + const clock = { from: fileAt(map, span.from), to: fileAt(map, span.to) }; + const id = (t: number) => t; + return { + kind: "file", + key: `${path}|${v ?? ""}`, + src: `/api/report/file?${q}`, + span, + clock, + clockOf: (s) => fileAt(map, s), + sourceOfClock: (c) => sourceAt(map, c), + elOf: id, + clockOfEl: id, + clockGaps: (gaps) => fileSpans(map, gaps), + audioUrl: (s) => `/api/report/audio?${q}&from=${s.from}&to=${s.to}`, + peaksUrl: `/api/report/peaks?${q}&from=${clock.from}&to=${clock.to}`, + peaksOnSource: (p) => peaksOnSource(p, span, map), + }; +} diff --git a/umtool/components/projects/bench/useBenchPlayer.ts b/umtool/components/projects/bench/useBenchPlayer.ts @@ -0,0 +1,539 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { + MUTE_FADE, + START_LEAD, + bufferSchedule, + covers, + decodeSpan, + elementShouldStop, + muteRamp, + playheadAt, +} from "@/lib/report/playback.mjs"; +import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs"; +import { GAP_FADE, gapsWithin, inGap, keptSpans } from "umtool-report-to-video/gaps"; +import type { BenchMedia, Span } from "./benchMedia"; + +// --------------------------------------------------------------------------- +// THE BENCH'S PLAYBACK ENGINE, shared by the clip bench and the reel's walk +// (lifted out of ClipBench.tsx unchanged in behaviour; lane/reel-bench). +// +// EVERY BOUNDED RANGE PLAYS FROM DECODED AUDIO. A selection, an edge, a line +// of the transcript, the auto-audition: each is an AudioBufferSourceNode +// started at an exact offset and stopped at an exact time on the audio +// clock, so what you hear ends where the selection ends, to the sample. The +// <video> used to play these itself and was stopped from `timeupdate`, which +// fires every 15-250 ms -- the stop overran by up to a quarter of a second, +// and by a different amount every time, which is exactly what makes a cut +// between two words impossible to judge by ear. +// +// The picture FOLLOWS, muted, and the playhead is read off the audio clock. +// When the decode fails the element plays instead, stopped per animation +// frame by remaining time, and the bench says so. +// +// Callers speak SOURCE seconds; the media adapter (benchMedia.ts) puts them +// on the decode clock -- the source clock for a raw window, the file's for a +// render -- and the playhead comes back in source seconds. +// --------------------------------------------------------------------------- + +/** A decoded span of the media, on the decode clock. `name` is the media's key. */ +type Decoded = { name: string; span: Span; buf: AudioBuffer }; + +/** What is playing, and what the last playback measured (the bench's `data-play-*`). */ +export type PlayInfo = { + engine: "webaudio" | "element"; + state: "playing" | "stopped"; + from: number; + /** The scheduled end, in source seconds. */ + to: number; + rate: number; + /** Web Audio at a speed but 1x: time-stretched at its own pitch, played at 1x. */ + stretched: boolean; + /** Context clock: when the source starts and when it is told to stop. */ + ctxStart: number | null; + ctxStop: number | null; + /** Where the playback had reached, in source seconds, when the page heard it end. */ + endedAt: number | null; +}; + +type Session = { + gen: number; + engine: "webaudio" | "element"; + node: AudioBufferSourceNode | null; + gain: GainNode | null; + raf: number; + timers: number[]; + /** On the decode clock. */ + from: number; + to: number; + rate: number; + t0: number; + ctxStop: number; + mutedBefore: boolean; + more?: AudioBufferSourceNode[]; +}; + +export type AudioState = { state: "idle" | "loading" | "ready" | "failed"; why?: string }; + +export function useBenchPlayer({ + media, + video, + rate, + gapsRef, + muteRef, + warm, +}: { + media: BenchMedia; + video: React.RefObject<HTMLVideoElement | null>; + rate: number; + /** The gaps every playback skips (source seconds), read at the moment it schedules. */ + gapsRef: React.RefObject<Span[]>; + /** The mute mark (source seconds) every playback fades out at, read when it schedules. */ + muteRef: React.RefObject<number | null>; + /** The span decoded (and, at a speed, stretched) ahead of the first play: the clip's or the beat's. */ + warm: Span; +}) { + const [playhead, setPlayhead] = useState<number | null>(null); + const decoded = useRef<Decoded | null>(null); + const decoding = useRef<{ key: string; p: Promise<Decoded> } | null>(null); + const stretchedRanges = useRef<{ key: string; buf: AudioBuffer }[]>([]); + const actx = useRef<AudioContext | null>(null); + const session = useRef<Session | null>(null); + const playGen = useRef(0); + // Pauses the bench asked for itself and has not yet heard the event of: a + // `pause` event is a task, so it arrives AFTER the next playback has started. + const selfPauses = useRef(0); + const pauseVideo = useCallback((el: HTMLVideoElement) => { + if (el.paused) return; + selfPauses.current += 1; + el.pause(); + }, []); + const [audio, setAudio] = useState<AudioState>({ state: "idle" }); + const [playInfo, setPlayInfo] = useState<PlayInfo | null>(null); + const m = media; + + /** The media's sound over (at least) `want` -- decode-clock seconds -- decoded once. */ + const ensureDecoded = useCallback( + async (want: Span): Promise<Decoded> => { + if (!m.key || !m.clock) throw new Error("nothing is cached for this clip"); + const have = decoded.current; + if (have && have.name === m.key && covers(have.span, want.from, want.to)) return have; + const span = decodeSpan(m.clock, want); + const key = `${m.key}|${span.from}|${span.to}`; + if (decoding.current?.key === key) return decoding.current.p; + const name = m.key; + const p = (async () => { + setAudio({ state: "loading" }); + const r = await fetch(m.audioUrl(span)); + if (!r.ok) { + const j = (await r.json().catch(() => null)) as { error?: string } | null; + throw new Error(j?.error ?? `the audio route answered ${r.status}`); + } + const from = Number(r.headers.get("x-audio-from") ?? span.from); + const bytes = await r.arrayBuffer(); + const Offline = typeof window !== "undefined" ? (window.OfflineAudioContext ?? null) : null; + if (!Offline) throw new Error("this browser has no Web Audio"); + const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes); + const d: Decoded = { name, span: { from, to: from + buf.duration }, buf }; + decoded.current = d; + setAudio({ state: "ready" }); + return d; + })(); + decoding.current = { key, p }; + p.catch((e: unknown) => { + if (decoding.current?.p === p) decoding.current = null; + setAudio({ state: "failed", why: e instanceof Error ? e.message : String(e) }); + }); + return p; + }, + [m], + ); + + // Different media -- a wider window after a fetch, a re-rendered master -- is + // different audio: drop the old decode and start the new one now. + useEffect(() => { + decoded.current = null; + decoding.current = null; + setAudio({ state: "idle" }); + if (!m.key) return; + ensureDecoded({ from: m.clockOf(warm.from), to: m.clockOf(warm.to) }).catch(() => { + /* said in the bench; play() falls back to the element */ + }); + // Keyed on the media's NAME: a refresh that returns the same window does not decode it again. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [m.key]); + + /** [offset, offset + duration) of a decoded buffer, time-stretched to `rate` at its own pitch. */ + const stretchFor = useCallback((d: Decoded, offset: number, duration: number, r: number): AudioBuffer => { + const key = `${d.name}|${d.span.from}|${offset.toFixed(5)}|${duration.toFixed(5)}|${r}`; + const hit = stretchedRanges.current.find((x) => x.key === key); + if (hit) return hit.buf; + const sr = d.buf.sampleRate; + const a = Math.max(0, Math.min(d.buf.length, Math.round(offset * sr))); + const b = Math.max(a, Math.min(d.buf.length, a + Math.round(duration * sr))); + const channels: Float32Array[] = []; + for (let c = 0; c < d.buf.numberOfChannels; c++) channels.push(d.buf.getChannelData(c).subarray(a, b)); + const out = timeStretch(channels, sr, r); + const buf = new AudioBuffer({ length: Math.max(1, out[0]?.length ?? 0), numberOfChannels: Math.max(1, out.length), sampleRate: sr }); + out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array<ArrayBuffer>, c)); + stretchedRanges.current = [{ key, buf }, ...stretchedRanges.current.filter((x) => x.key !== key)].slice(0, 4); + return buf; + }, []); + + // At a speed but 1x, the warm span is stretched while the bench is idle. + useEffect(() => { + if (audio.state !== "ready" || !wantsStretch(rate)) return; + const d = decoded.current; + if (!d) return; + const sch = bufferSchedule(d.span, d.buf.duration, m.clockOf(warm.from), m.clockOf(warm.to), rate); + if (!sch) return; + const w = window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number; cancelIdleCallback?: (id: number) => void }; + const run = () => { + if (decoded.current === d) stretchFor(d, sch.offset, sch.duration, rate); + }; + if (w.requestIdleCallback) { + const id = w.requestIdleCallback(run, { timeout: 2000 }); + return () => w.cancelIdleCallback?.(id); + } + const id = window.setTimeout(run, 250); + return () => window.clearTimeout(id); + }, [audio.state, rate, warm.from, warm.to, stretchFor, m]); + + /** Stop whatever is playing, Web Audio or element, and let go of it. */ + const stopPlayback = useCallback(() => { + const s = session.current; + if (!s) return; + session.current = null; + cancelAnimationFrame(s.raf); + for (const t of s.timers) clearTimeout(t); + for (const node of [s.node, ...(s.more ?? [])]) { + if (!node) continue; + node.onended = null; + try { + node.stop(); + } catch { + /* never started, or already stopped */ + } + node.disconnect(); + } + s.gain?.disconnect(); + const el = video.current; + if (el) { + pauseVideo(el); + el.muted = s.mutedBefore; + } + setPlayInfo((pi) => (pi && pi.state === "playing" ? { ...pi, state: "stopped" } : pi)); + }, [pauseVideo, video]); + + /** The fallback: the element, stopped per animation frame by REMAINING TIME. Decode-clock seconds. */ + const playElement = useCallback( + (from: number, to: number, gen: number, gaps: Span[] = []) => { + const el = video.current; + if (!el || !m.key) return; + el.currentTime = Math.max(0, m.elOf(from)); + el.playbackRate = rate; + const s: Session = { gen, engine: "element", node: null, gain: null, raf: 0, timers: [], from, to, rate, t0: 0, ctxStop: 0, mutedBefore: el.muted }; + session.current = s; + setPlayInfo({ engine: "element", state: "playing", from: m.sourceOfClock(from), to: m.sourceOfClock(to), rate, stretched: false, ctxStart: null, ctxStop: null, endedAt: null }); + const stopNow = () => { + if (session.current !== s) return; + pauseVideo(el); + session.current = null; + cancelAnimationFrame(s.raf); + for (const t of s.timers) clearTimeout(t); + el.muted = s.mutedBefore; + setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: m.sourceOfClock(m.clockOfEl(el.currentTime)) } : pi)); + }; + const tick = () => { + if (session.current !== s) return; + const t = m.clockOfEl(el.currentTime); + setPlayhead(m.sourceOfClock(t)); + // A gap: on past it, as near as a frame tick gets it. + const g = inGap(t, gaps); + if (g && !el.seeking) el.currentTime = m.elOf(g.to); + // The mark, as near as a frame tick gets it. + const mk = muteRef.current; + el.muted = s.mutedBefore || (mk != null && t >= m.clockOf(mk)); + if (!el.paused && elementShouldStop(t, to, rate)) { + stopNow(); + return; + } + // Inside the last few frames, a timer for the REMAINING time. + const remaining = (to - t) / rate; + if (!el.paused && remaining < 0.1 && !s.timers.length) s.timers.push(window.setTimeout(stopNow, remaining * 1000)); + s.raf = requestAnimationFrame(tick); + }; + s.raf = requestAnimationFrame(tick); + // A rejected play() is normal (no gesture yet): the seek has happened either way. + void el.play().catch(() => {}); + }, + [m, rate, pauseVideo, video, muteRef], + ); + + /** + * Play [from, to] (source seconds), skipping the gaps as the cut will: each + * piece that plays is its own node, abutting the next on the context's + * clock, the join faded out and in by the build's GAP_FADE; the picture is + * seeked at each join. `through` plays the gaps too (a span being chosen + * for one is heard as it is); `extra` is one more span to skip (Hear it). + */ + const play = useCallback( + async (srcFrom: number, srcTo: number, { through = false, extra = null }: { through?: boolean; extra?: Span | null } = {}) => { + const gen = (playGen.current += 1); + stopPlayback(); + if (!m.key || !(srcTo > srcFrom)) return; + const srcGaps = through ? [] : gapsWithin([...(gapsRef.current ?? []), ...(extra ? [extra] : [])].sort((a, b) => a.from - b.from), srcFrom, srcTo); + // On the decode clock from here on. + const from = m.clockOf(srcFrom); + const to = m.clockOf(srcTo); + const gaps = gapsWithin(m.clockGaps(srcGaps), from, to); + const mark = muteRef.current == null ? null : m.clockOf(muteRef.current); + let ac = actx.current; + if (!ac && typeof window !== "undefined" && window.AudioContext) { + ac = new window.AudioContext(); + actx.current = ac; + } + const resumed = ac && ac.state !== "running" ? ac.resume().catch(() => {}) : null; + let d: Decoded; + try { + if (!ac) throw new Error("this browser has no Web Audio"); + d = await ensureDecoded({ from, to }); + } catch { + if (gen === playGen.current) playElement(from, to, gen, gaps); + return; + } + if (gen !== playGen.current) return; + if (!covers(d.span, from, to)) { + playElement(from, to, gen, gaps); + return; + } + if (resumed) await Promise.race([resumed, new Promise((res) => setTimeout(res, 300))]); + if (gen !== playGen.current || ac!.state !== "running") return; + const ctx = ac!; + const pieces = keptSpans(from, to, gaps) + .map((p) => ({ p, sch: bufferSchedule(d.span, d.buf.duration, p.from, p.to, rate) })) + .filter((x): x is { p: Span; sch: NonNullable<ReturnType<typeof bufferSchedule>> } => !!x.sch); + if (!pieces.length) return; + const stretched = wantsStretch(rate); + const bufs = pieces.map(({ sch }) => (stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf)); + if (gen !== playGen.current) return; + + const gain = ctx.createGain(); + gain.connect(ctx.destination); + const t0 = ctx.currentTime + START_LEAD; + let acc = 0; + const placed = pieces.map(({ p, sch }) => { + const w0 = acc; + acc += sch.wall; + return { p, sch, w0, w1: acc }; + }); + const ctxStop = t0 + acc; + const end = placed[placed.length - 1].p.from + placed[placed.length - 1].sch.duration; + const nodes = placed.map(({ sch, w0 }, k) => { + const node = ctx.createBufferSource(); + node.buffer = bufs[k]; + node.playbackRate.value = stretched ? 1 : rate; + node.connect(gain); + node.start(t0 + w0, stretched ? 0 : sch.offset); + node.stop(t0 + w0 + sch.wall); + return node; + }); + if (placed.length === 1) { + const mr = muteRamp(mark, from, from + placed[0].sch.duration, rate); + if (mr) { + if (mr.at <= 0) gain.gain.setValueAtTime(0, t0); + else { + gain.gain.setValueAtTime(1, t0 + mr.at); + gain.gain.linearRampToValueAtTime(0, t0 + mr.at + mr.fade); + } + } + } else { + // Across gaps: the joins' fades and the mute mark, as one level on the wall clock. + const fadeW = GAP_FADE / rate; + let markW: number | null = null; + if (mark != null) { + if (mark <= from) markW = 0; + else { + const k = placed.findIndex((x) => mark <= x.p.from + x.sch.duration); + if (k >= 0) markW = placed[k].w0 + Math.max(0, mark - placed[k].p.from) / rate; + } + } + const muteFadeW = MUTE_FADE / rate; + const level = (w: number) => { + let v = 1; + placed.forEach((x, k) => { + if (w < x.w0 || w > x.w1) return; + if (k > 0 && w < x.w0 + fadeW) v = Math.min(v, (w - x.w0) / fadeW); + if (k < placed.length - 1 && w > x.w1 - fadeW) v = Math.min(v, (x.w1 - w) / fadeW); + }); + if (markW != null) { + if (w >= markW) v = 0; + else if (w > markW - muteFadeW) v = Math.min(v, (markW - w) / muteFadeW); + } + return Math.max(0, Math.min(1, v)); + }; + const pts = new Set<number>([0, acc]); + placed.forEach((x, k) => { + if (k > 0) [x.w0, x.w0 + fadeW].forEach((w) => pts.add(w)); + if (k < placed.length - 1) [x.w1 - fadeW, x.w1 - 1e-4].forEach((w) => pts.add(w)); + }); + if (markW != null) [markW - muteFadeW, markW].forEach((w) => pts.add(Math.max(0, w))); + const ws = [...pts].filter((w) => w >= 0 && w <= acc).sort((a, b) => a - b); + gain.gain.setValueAtTime(level(ws[0]), t0 + ws[0]); + for (const w of ws.slice(1)) gain.gain.linearRampToValueAtTime(level(w), t0 + w); + } + + const el = video.current; + const s: Session = { + gen, engine: "webaudio", node: nodes[0], gain, raf: 0, timers: [], from, to: end, rate, t0, ctxStop, + mutedBefore: el?.muted ?? false, + ...(nodes.length > 1 ? { more: nodes.slice(1) } : {}), + }; + session.current = s; + setPlayInfo({ engine: "webaudio", state: "playing", from: m.sourceOfClock(from), to: m.sourceOfClock(end), rate, stretched, ctxStart: t0, ctxStop, endedAt: null }); + /** The decode-clock second playing `w` wall seconds in. */ + const posAt = (w: number) => { + const x = placed.find((q) => w <= q.w1) ?? placed[placed.length - 1]; + return Math.min(x.p.from + x.sch.duration, x.p.from + Math.max(0, w - x.w0) * rate); + }; + + // The picture follows, muted. + if (el) { + el.muted = true; + el.playbackRate = rate; + el.currentTime = Math.max(0, m.elOf(from)); + s.timers.push(window.setTimeout(() => { + if (session.current === s) void el.play().catch(() => {}); + }, START_LEAD * 1000)); + for (const x of placed.slice(1)) { + s.timers.push(window.setTimeout(() => { + if (session.current === s) el.currentTime = Math.max(0, m.elOf(x.p.from)); + }, (START_LEAD + x.w0) * 1000)); + } + } + + const last = nodes[nodes.length - 1]; + last.onended = () => { + if (session.current !== s) return; + const late = ctx.currentTime - ctxStop; + session.current = null; + cancelAnimationFrame(s.raf); + for (const t of s.timers) clearTimeout(t); + for (const n of nodes) n.disconnect(); + gain.disconnect(); + if (el) { + pauseVideo(el); + el.muted = s.mutedBefore; + } + setPlayhead(m.sourceOfClock(s.to)); + setPlayInfo((pi) => (pi ? { ...pi, state: "stopped", endedAt: m.sourceOfClock(s.to + Math.max(0, late) * rate) } : pi)); + }; + + // The playhead at ~30 Hz; the picture pulled back to the sound past a quarter second of drift. + let painted = -1; + let checked = t0; + const tick = () => { + if (session.current !== s) return; + const now = ctx.currentTime; + const pos = placed.length === 1 ? playheadAt(from, t0, now, rate, placed[0].sch.duration) : posAt(Math.max(0, now - t0)); + if (now - painted >= 1 / 30) { + painted = now; + setPlayhead(m.sourceOfClock(pos)); + } + if (el && now - checked >= 0.5 && now > t0) { + checked = now; + const want = m.elOf(pos); + if (!el.seeking && Math.abs(el.currentTime - want) > 0.25) el.currentTime = want; + } + s.raf = requestAnimationFrame(tick); + }; + s.raf = requestAnimationFrame(tick); + }, + [m, rate, ensureDecoded, playElement, stopPlayback, pauseVideo, stretchFor, video, gapsRef, muteRef], + ); + + // A speed change mid-playback would leave the picture and the sound at two rates. + useEffect(() => { + stopPlayback(); + }, [rate, stopPlayback]); + + // Let go of the audio output with the bench. + useEffect( + () => () => { + stopPlayback(); + void actx.current?.close().catch(() => {}); + actx.current = null; + }, + [stopPlayback], + ); + + // The element's own controls: unbounded "play from here", which stays on the + // element. Its clock moves the playhead only while nothing bounded plays; + // pausing the picture by hand stops the sound it follows. + useEffect(() => { + const el = video.current; + if (!el) return; + const tick = () => { + if (!session.current && !el.paused) setPlayhead(m.sourceOfClock(m.clockOfEl(el.currentTime))); + }; + const seeked = () => { + if (!session.current) setPlayhead(m.sourceOfClock(m.clockOfEl(el.currentTime))); + }; + const paused = () => { + if (selfPauses.current > 0) { + selfPauses.current -= 1; + return; + } + if (session.current) stopPlayback(); + }; + el.addEventListener("timeupdate", tick); + el.addEventListener("seeked", seeked); + el.addEventListener("pause", paused); + return () => { + el.removeEventListener("timeupdate", tick); + el.removeEventListener("seeked", seeked); + el.removeEventListener("pause", paused); + }; + // The element is the same one while the media is. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [m.key, stopPlayback]); + + /** Re-aim the playback in flight at a new mute mark (source seconds), from now. */ + const retargetMute = useCallback((t: number | null) => { + const s = session.current; + const ctx = actx.current; + if (!s || s.engine !== "webaudio" || !s.gain || !ctx) return; + const now = ctx.currentTime; + const g = s.gain.gain; + g.cancelScheduledValues(now); + const pos = playheadAt(s.from, s.t0, now, s.rate, s.to - s.from); + const mr = t == null ? null : muteRamp(m.clockOf(t), pos, s.to, s.rate); + if (!mr) { + g.setValueAtTime(1, now); + return; + } + if (mr.at <= 0) { + g.setValueAtTime(g.value, now); + g.linearRampToValueAtTime(0, now + MUTE_FADE / s.rate); + return; + } + g.setValueAtTime(1, now); + g.setValueAtTime(1, now + mr.at); + g.linearRampToValueAtTime(0, now + mr.at + mr.fade); + }, [m]); + + /** Show the picture at a source second, paused (a click on the waveform, a handle let go). */ + const showAt = useCallback( + (src: number) => { + const el = video.current; + if (!el || !m.key) return; + stopPlayback(); + el.currentTime = Math.max(0, m.elOf(m.clockOf(src))); + setPlayhead(src); + }, + [m, stopPlayback, video], + ); + + return { play, stopPlayback, playhead, setPlayhead, playInfo, audio, retargetMute, showAt, playing: playInfo?.state === "playing" }; +} diff --git a/umtool/components/projects/bench/useGapEditor.ts b/umtool/components/projects/bench/useGapEditor.ts @@ -0,0 +1,148 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { GAP_LIMITS, editGaps } from "umtool-report-to-video/gaps"; +import type { Span } from "./benchMedia"; + +// --------------------------------------------------------------------------- +// GAPS, EDITED (lifted out of ClipBench.tsx; lane/reel-bench): seconds cut +// out of the middle of a span (umtool-report-to-video gaps.mjs), so it plays +// as one run of jump cuts. A span is dragged on the waveform with Alt held +// (or after `g` / Select a gap) and written by Cut gap (or `g`); a click on a +// gap's band puts it back; Undo writes the list back as it was. Written AT +// ONCE, through the caller's writer -- a clip's window writer (`gapAdd` / +// `gapRemove`) or a reel's beat writer -- which refuses what the build would; +// the rule is checked here first (`refusal`), with the same sentences, so a +// refusal is said before anything is sent. +// --------------------------------------------------------------------------- + +export type GapOp = { add: Span } | { remove: Span } | { set: Span[] }; + +const r2 = (n: number) => Number(n.toFixed(2)); + +export function useGapEditor({ + key, + gaps, + span, + refusal, + write, + said, + setNote, + fmt, +}: { + /** What the gaps belong to: another one starts with nothing selected and nothing to undo. */ + key: string; + /** The gaps as saved. */ + gaps: Span[]; + /** Where a gap may go (the clip's cut or extent; a beat's span). */ + span: Span; + /** Why `next` cannot be written, or null. */ + refusal: (next: Span[]) => string | null; + /** Write the op (`next` the list it makes); resolves whether it was written. */ + write: (op: GapOp, next: Span[]) => Promise<boolean>; + /** The sentence after a write, with the list it made ("the cut plays 6.20 s, one segment"). */ + said: (next: Span[]) => string; + setNote: (s: string | null) => void; + fmt: (t: number) => string; +}) { + const [sel, setSel] = useState<Span | null>(null); + const [pick, setPick] = useState(false); + const [undo, setUndo] = useState<{ gaps: Span[]; what: string } | null>(null); + useEffect(() => { + setSel(null); + setPick(false); + setUndo(null); + }, [key]); + + const run = useCallback( + async (op: GapOp, next: Span[], what: string) => { + const why = refusal(next); + if (why) { + setNote(`not cut: ${why}`); + return false; + } + const before = gaps; + const ok = await write(op, next); + if (ok) { + setUndo({ gaps: before, what }); + setNote(`${what} — ${said(next)}`); + } + return ok; + }, + [refusal, write, said, setNote, gaps], + ); + + const cut = useCallback(async () => { + const s = sel; + if (!s) return; + const g = { from: r2(s.from), to: r2(s.to) }; + let next: Span[]; + try { + next = editGaps(gaps, { add: g }); + } catch (e) { + setNote(e instanceof Error ? e.message : String(e)); + return; + } + const ok = await run({ add: g }, next, `cut ${fmt(g.from)}–${fmt(g.to)} out`); + if (ok) { + setSel(null); + setPick(false); + } + }, [sel, gaps, run, setNote, fmt]); + + const remove = useCallback( + (g: Span) => { + const next = gaps.filter((x) => x.from !== g.from || x.to !== g.to); + void run({ remove: g }, next, `put ${fmt(g.from)}–${fmt(g.to)} back`); + }, + [gaps, run, fmt], + ); + + /** `G`: the gap the playhead is in (or at the edge of). */ + const removeAt = useCallback( + (t: number | null) => { + const g = t == null ? null : gaps.find((x) => t >= x.from - 0.05 && t <= x.to + 0.05); + if (!g) { + setNote("the playhead is not on a gap — play to it, or click its band"); + return; + } + remove(g); + }, + [gaps, remove, setNote], + ); + + const undoLast = useCallback(() => { + const u = undo; + if (!u) return; + void write({ set: u.gaps }, u.gaps).then((ok) => { + if (!ok) return; + setUndo(null); + setNote(`undone — ${u.what} is reversed`); + }); + }, [undo, write, setNote]); + + /** A span dragged for a gap: kept inside the span; under the shortest gap on release, dropped and said. */ + const select = useCallback( + (s: Span, done: boolean) => { + const from = Math.max(span.from, s.from); + const to = Math.min(span.to, s.to); + if (!done) { + setSel(to > from ? { from, to } : null); + return; + } + if (to - from < GAP_LIMITS.min) { + setSel(null); + if (to - from > 0.01) setNote(`a gap is at least ${GAP_LIMITS.min} s — drag a longer span`); + return; + } + setSel({ from, to }); + const why = refusal(editGaps(gaps, { add: { from: r2(from), to: r2(to) } })); + setNote(why ? `this span cannot be cut: ${why}` : `${(to - from).toFixed(2)} s selected — Cut gap (g) to take it out, Hear it to listen first`); + }, + [span.from, span.to, gaps, refusal, setNote], + ); + + return { sel, setSel, pick, setPick, undo, cut, remove, removeAt, undoLast, select }; +} + +export type GapEditor = ReturnType<typeof useGapEditor>; diff --git a/umtool/components/projects/bench/usePeaks.ts b/umtool/components/projects/bench/usePeaks.ts @@ -0,0 +1,29 @@ +"use client"; + +import { useEffect, useState } from "react"; +import type { Peaks } from "@/components/Waveform"; +import type { BenchMedia } from "./benchMedia"; + +/** The waveform's envelope for a bench's media, on the source clock (benchMedia.ts). One request per media. */ +export function usePeaks(media: BenchMedia): Peaks | null { + const [got, setGot] = useState<{ url: string; peaks: Peaks } | null>(null); + const url = media.peaksUrl; + const toSource = media.peaksOnSource; + useEffect(() => { + if (!url) return; + let live = true; + void (async () => { + const r = await fetch(url, { cache: "no-store" }); + if (!r.ok || !live) return; + const p = (await r.json()) as Peaks; + if (live) setGot({ url, peaks: toSource(p) }); + })(); + return () => { + live = false; + }; + // The URL names the media; its mapping comes with it. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [url]); + // Until the new media's envelope arrives, the last one stays drawn (as the bench always did). + return got?.peaks ?? null; +} diff --git a/umtool/components/projects/reel/ReelBench.tsx b/umtool/components/projects/reel/ReelBench.tsx @@ -0,0 +1,622 @@ +"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 } 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/<p>/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<ReelView>(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 ( + <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 || !initial.media) { + return ( + <main className="deck-main flex-1 space-y-2 p-4" data-reel-walk="" data-reel-beat={beat}> + <SourceBanner view={view} beat={beat} changed={changed} /> + {row && <BeatStatusBar view={view} row={row} clips={initial.clips} onDone={() => router.refresh()} />} + <p className="m-0 text-[13px] text-text"> + {row ? `Beat ${beat} does not play from take ${take}'s master: ${row.problem ?? "it does not map"}.` : `The reel ${reel} has no beat ${beat}.`}{" "} + <Link href={trailerHref(project, { reel })} className="ink-link"> + Its beats + </Link> + </p> + </main> + ); + } + return <BeatEditor key={`${reel}:${take}:${beat}`} view={view} setView={setView} row={row} data={initial} prevRow={prevRow} nextRow={nextRow} fps={fps} isClip={isClip} router={router} changed={changed} />; +} + +/** 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<typeof useRouter>; + 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<Span>(saved); + const savedKey = `${saved.from}|${saved.to}`; + useEffect(() => setSel(saved), [savedKey]); // eslint-disable-line react-hooks/exhaustive-deps + const [msg, setMsg] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [rate, setRate] = useState(1); + const video = useRef<HTMLVideoElement | null>(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<string | null>(view.token); + token.current = view.token; + const lastSaved = useRef<Record<string, unknown> | 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<string, unknown>, 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<string, unknown>) => { + const p: Record<string, unknown> = {}; + 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<Span[]>(gaps); + gapsRef.current = gaps; + const muteRef = useRef<number | null>(null); + const { play, stopPlayback, playhead, playInfo, audio, showAt, playing } = useBenchPlayer({ media, video, rate, gapsRef, muteRef, warm: sel }); + const playheadRef = useRef<number | null>(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<ReelAnchor | null>(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) : []; + const confirmedCount = (view.rows ?? []).filter((x) => x.verdict === "confirmed").length; + + 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 ?? ""} + data-reel-gaps={gaps.map((g) => `${g.from}-${g.to}`).join(",")} + > + <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"> + <SourceBanner view={view} beat={row.n} changed={changed} /> + <BeatStatusBar view={view} row={row} clips={data.clips} onDone={() => void reload()} /> + <div className="relative mx-auto aspect-video w-full max-w-[900px] overflow-hidden rounded-[3px] bg-black"> + <video + ref={video} + src={media.src ?? undefined} + preload="auto" + playsInline + data-reel-walk-video="" + onLoadedMetadata={() => showAt(sel.from)} + className="absolute inset-0 h-full w-full object-contain" + /> + </div> + {/* ---- the edges, in source seconds, and what the master plays of them ---- */} + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> + <span className="num font-mono text-text" data-reel-source-edges=""> + {isClip ? "source " : "master "} + {fmt(sel.from)} – {fmt(sel.to)} + </span> + <span className="num font-mono text-text-2" data-reel-edges=""> + {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))} + </span> + <span className="num font-mono text-muted" data-reel-head=""> + ▸ {playhead != null ? fmt(playhead) : "—"} + </span> + {dirty && <b className="text-[var(--color-dirty,#e0a020)]" data-reel-unsaved="">unsaved — Enter saves, R puts back</b>} + {atLimit && ( + <span data-reel-limit-hit={atLimit} className="text-[var(--color-dirty)]"> + 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 + </span> + )} + </div> + {/* ---- the instrument: the clip bench's waveform, zoom and gaps ---- */} + <div className="flex flex-col gap-1"> + {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} + <BenchWaveBox + zoom={zoom} + sel={sel} + cand={saved} + cues={cues} + peaks={peaks} + playhead={playhead} + onSel={onSel} + gap={gap} + gaps={gaps} + silences={isClip ? (render?.silences ?? null) : null} + words={nearWords?.words ?? null} + busy={busy} + held={!isClip} + > + {/* What the master already left out of the clip (its render's gaps): nothing plays there. */} + {masterGaps.map((g) => ( + <div + key={`mg-${g.from}`} + data-reel-master-gap={`${g.from}-${g.to}`} + title={`${sourceClock(g.from)}–${sourceClock(g.to)}: cut out of ${row.id} in the master (the clip's own gap) — edit it on the clip's walk`} + className="pointer-events-none absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-dim)_25%,transparent)]" + style={{ left: zpct(g.from), width: `calc(${zpct(g.to)} - ${zpct(g.from)})` }} + /> + ))} + </BenchWaveBox> + {zoom.zoomed && <ZoomOverview zoom={zoom} whole={span} peaks={peaks} sel={sel} gaps={gaps} />} + <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> + {isClip ? ( + <GapTools gap={gap} gaps={gaps} span={saved} sel={sel} busy={busy} fmt={sourceClock} play={play} noun="the beat" of="the beat" /> + ) : ( + <span className="text-[var(--color-dim)]" data-reel-no-gaps="">a master beat is master seconds: only a clip beat has gaps</span> + )} + {isClip && <TightenButtons tools={edgeTools} busy={busy} />} + <ZoomControls zoom={zoom} whole={span} selection={gap.sel ?? sel} playhead={playhead} /> + </div> + </div> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" data-reel-play-beat="" onClick={() => (playing ? stopPlayback() : void play(sel.from, sel.to))} className={buttonVariants({ size: "sm" })}> + {playing ? "Stop" : "Play the beat"} + </button> + <button type="button" data-reel-save="" disabled={!dirty || busy} onClick={() => void saveEdges()} 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> + <label className="flex items-center gap-1 text-[12px]"> + <span className="micro">speed</span> + <select data-playback-rate="" value={rate} onChange={(e) => setRate(Number(e.target.value))} className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-1 py-0.5 text-[11px]"> + {RATES.map((x) => ( + <option key={x} value={x}> + {x}× + </option> + ))} + </select> + </label> + <span + data-playback="" + data-audio-state={audio.state} + data-play-engine={playInfo?.engine ?? ""} + data-play-state={playInfo?.state ?? ""} + data-play-from={playInfo?.from ?? ""} + data-play-to={playInfo?.to ?? ""} + className="micro" + > + {audio.state === "ready" ? "exact playback" : audio.state === "loading" ? "decoding the audio…" : audio.state === "failed" ? `the picture plays instead — ${audio.why}` : null} + </span> + {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>} + {isClip && <span className="text-muted" data-reel-limits="">its segment plays source {sourceClock(span.from)}–{sourceClock(span.to)}</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 · z Z f F zoom · g (or Alt + drag) a gap, G puts one back · - = speed + </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> + )} + <span className="ml-2 text-[12px] text-muted">{confirmedCount} of {(view.rows ?? []).length} confirmed</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={() => void save({ verdict: null })} 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, changed })} 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, changed })} 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: string, ask: CutAsk | null) => { + const n = await notes.write({ op: "add", text, anchor: { ...drafting, ...(ask ? { ask } : {}) } }); + if (!n) return; + setDrafting(null); + if (row.verdict !== "confirmed") await save({ verdict: "note" }); + }} + /> + )} + {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> + ))} + {/* The clip's words over what the master plays of it: a line plays from there. */} + {cues.length > 0 && ( + <section data-reel-cues="" className="mt-2 space-y-0.5"> + <h2 className="micro m-0">{row.id}&rsquo;s words</h2> + {cues.map((c) => { + const outside = c.end < span.from || c.start > span.to; + const inSel = c.end > sel.from && c.start < sel.to; + const lit = playhead != null && playhead >= c.start && playhead < c.end; + return ( + <button + key={`${c.start}-${c.end}`} + type="button" + data-reel-cue={c.start} + disabled={outside} + title={outside ? "outside what the master rendered of this clip" : "play from here"} + onClick={() => void play(Math.max(span.from, c.start), Math.min(span.to, c.end + 2))} + className={cn( + "flex w-full items-baseline gap-2 border-l-2 px-1.5 py-0.5 text-left text-[12.5px]", + lit ? "border-signal" : "border-transparent", + outside ? "text-muted opacity-60" : inSel ? "text-text" : "text-text-2", + )} + > + <span className="num w-[4.6rem] shrink-0 font-mono text-[10.5px] text-muted">{sourceClock(c.start)}</span> + <span className="min-w-0 font-serif leading-snug"> + {c.text} + {c.endsSentence ? " ¶" : ""} + </span> + </button> + ); + })} + </section> + )} + <p className="m-0 mt-auto break-all font-mono text-[11px] text-muted" data-reel-master-file=""> + {view.file} · take {take} · {m.path} + </p> + </aside> + </div> + ); +} diff --git a/umtool/components/projects/reel/ReelCutPanel.tsx b/umtool/components/projects/reel/ReelCutPanel.tsx @@ -170,6 +170,7 @@ export default function ReelCutPanel({ project, reel }: { project: string; reel: · {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" : ""} + {here.reelChanged ? " · the reel was edited since this cut: cut it again" : ""} </span> </p> {here.record && <p className="m-0 font-mono text-[10.5px] text-[var(--color-dim)]">{here.record}</p>} diff --git a/umtool/components/projects/reel/ReelPlay.tsx b/umtool/components/projects/reel/ReelPlay.tsx @@ -9,7 +9,8 @@ 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 { SourceBanner } from "./ReelSource"; +import { clock, itemAt, masterAt, masterOfSource, masterSrc, reelAtMaster, readReelView, reelItems, sourceClock, sourceOfMaster, type ReelRow, type ReelView } from "./reelTypes"; import { useReelPlayer } from "./useReelPlayer"; // --------------------------------------------------------------------------- @@ -106,10 +107,10 @@ export default function ReelPlay({ initial, initialBeat = null, initialNote = nu 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))); + if (it && m !== null) return reelAtMaster(it, m); } 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); + if (byBeat && a.masterT !== undefined && a.masterT >= byBeat.mStart && a.masterT <= byBeat.mEnd) return reelAtMaster(byBeat, a.masterT); return byBeat ? byBeat.at : a.t; }, [items], @@ -123,7 +124,7 @@ export default function ReelPlay({ initial, initialBeat = null, initialNote = nu if (!it?.row) return; resume.current = e.playing; if (e.playing) player.setPlaying(false); - const masterT = it.mStart + (e.t - it.at); + const masterT = masterAt(it, e.t); const src = sourceOfMaster(it.row, masterT); setDrafting({ kind: "reel", @@ -236,13 +237,15 @@ export default function ReelPlay({ initial, initialBeat = null, initialNote = nu 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 masterT = item ? masterAt(item, t) : 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"> + {/* What the reel was cut against, and the beats this take changed (ReelSource.tsx). */} + <SourceBanner view={view} beat={item?.n || 1} changed={false} /> <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 diff --git a/umtool/components/projects/reel/ReelSource.tsx b/umtool/components/projects/reel/ReelSource.tsx @@ -0,0 +1,110 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { reelWalkHref } from "@/lib/hrefs"; +import { cn } from "@/lib/utils"; +import { STATE_LABEL, r2, reelWrite, sourceClock, type ReelRow, type ReelView } from "./reelTypes"; + +// --------------------------------------------------------------------------- +// WHAT THE REEL WAS CUT AGAINST (lib/report/reelAnchor.mjs): the reel's line +// ("cut against draft-6; take draft-7 changes beats 7") with the filter that +// walks only the changed beats, and per beat its state, why, and the fix -- +// clamp a clipped beat into its clip's new limits, remove or re-point an +// orphan, or anchor a beat to this take once it has been looked at. Every +// fix is one write through the beats' writer, an undo point, and in the +// reel's history. +// --------------------------------------------------------------------------- + +export function SourceBanner({ view, beat, changed }: { view: ReelView; beat: number; changed: boolean }) { + const st = view.status; + if (!st || !view.take) return null; + const n = st.changed.length; + return ( + <p data-reel-source-banner={n ? "changed" : "same"} className={cn("m-0 flex flex-wrap items-center gap-2 rounded-[3px] border px-3 py-1.5 text-[12.5px]", n ? "border-[var(--color-dirty)] text-text" : "border-seam text-text-2")}> + <span data-reel-source-line="">{st.line}</span> + {n > 0 && + (changed ? ( + <Link href={reelWalkHref(view.project, { reel: view.reel, take: view.take.id, beat })} data-reel-walk-filter="all" className="ink-link"> + Walk every beat + </Link> + ) : ( + <Link href={reelWalkHref(view.project, { reel: view.reel, take: view.take.id, beat: st.changed.includes(beat) ? beat : st.changed[0], changed: true })} data-reel-walk-filter="changed" className="ink-link"> + Walk only the changed beats ({n}) + </Link> + ))} + </p> + ); +} + +export function BeatStatusBar({ view, row, clips, onDone }: { view: ReelView; row: ReelRow; clips: string[]; onDone: () => void }) { + const st = row.status; + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<string | null>(null); + const [to, setTo] = useState(""); + if (!st || !view.take) return null; + const take = view.take.id; + const run = async (op: string, args: Record<string, unknown>, done: string) => { + setBusy(true); + try { + const r = await reelWrite(view.project, view.reel, view.token, op, { ...args, take }); + setSaid(r.ok ? done : r.error); + if (r.ok) onDone(); + } finally { + setBusy(false); + } + }; + const now = st.now as { start: number; end: number } | null | undefined; + const was = st.was as { start: number; end: number } | null | undefined; + const b = row.beat as { start?: number; end?: number; gaps?: { from: number; to: number }[] }; + const clamp = + st.state === "clipped" && now && b.start !== undefined && b.end !== undefined + ? (() => { + const start = r2(Math.max(b.start, now.start)); + const end = r2(Math.min(b.end, now.end)); + return end - start >= 0.2 ? { start, end, ...(b.gaps ? { gaps: b.gaps.filter((g) => g.from >= start + 0.5 && g.to <= end - 0.5) } : {}) } : null; + })() + : null; + const quiet = st.state === "unchanged" || st.state === "rerendered"; + return ( + <div data-reel-beat-state={st.state} className={cn("flex flex-wrap items-center gap-2 text-[12px]", quiet ? "text-muted" : "text-text")}> + <span className={cn("rounded-[2px] border px-1.5 py-px font-mono text-[11px]", quiet ? "border-seam" : "border-[var(--color-dirty)] text-[var(--color-dirty)]")}>{STATE_LABEL[st.state]}</span> + <span data-reel-beat-why="">{st.why}</span> + {st.state === "edges" && was && now && ( + <span data-reel-beat-was="" className="num font-mono text-text-2"> + was {sourceClock(was.start)}–{sourceClock(was.end)} · now {sourceClock(now.start)}–{sourceClock(now.end)} + </span> + )} + {clamp && ( + <button type="button" data-reel-clamp="" disabled={busy} onClick={() => void run("set", { index: row.n - 1, patch: clamp }, `clamped to ${clamp.start}–${clamp.end}`)} className={buttonVariants({ variant: "go", size: "sm" })}> + Clamp to {sourceClock(clamp.start)}–{sourceClock(clamp.end)} + </button> + )} + {st.state === "orphan" && ( + <> + <button type="button" data-reel-remove="" disabled={busy} onClick={() => void run("remove", { index: row.n - 1 }, `beat ${row.n} removed`)} className={buttonVariants({ size: "sm" })}> + Remove the beat + </button> + <select data-reel-repoint-to="" value={to} onChange={(e) => setTo(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-1 py-0.5 text-[11px]"> + <option value="">re-point to…</option> + {clips.map((c) => ( + <option key={c} value={c}> + {c} + </option> + ))} + </select> + <button type="button" data-reel-repoint="" disabled={busy || !to} onClick={() => void run("set", { index: row.n - 1, patch: { id: to } }, `beat ${row.n} re-pointed to ${to}`)} className={buttonVariants({ size: "sm" })}> + Re-point + </button> + </> + )} + {(st.state === "edges" || st.state === "look" || st.state === "unanchored" || st.state === "rerendered") && ( + <button type="button" data-reel-anchor="" disabled={busy} onClick={() => void run("anchor", { only: [row.n - 1] }, `beat ${row.n} anchored to take ${take}`)} className={buttonVariants({ variant: quiet ? "quiet" : "outline", size: "sm" })} title={`it has been looked at against take ${take}: anchor it there (an edit or a confirm does this too)`}> + {st.state === "rerendered" ? `Anchor to ${take}` : `Looked at — anchor to ${take}`} + </button> + )} + {said && <span data-reel-status-said="" className="text-text-2">{said}</span>} + </div> + ); +} diff --git a/umtool/components/projects/reel/ReelWalk.tsx b/umtool/components/projects/reel/ReelWalk.tsx @@ -1,459 +0,0 @@ -"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 @@ -2,31 +2,38 @@ 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 { reelBenchData } from "@/lib/report/reelBenchData"; 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"; +import ReelBench from "./ReelBench"; +import { CHANGED_STATES } 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). +// reel's editor over one beat, on the take's rendered master (ReelBench.tsx, +// built from the clip bench's parts; lib/report/reelBenchData.ts its data). export default async function ReelWalkPage({ project, reel = DEFAULT_REEL, take, beat, + changed = false, }: { project: ProjectRef; reel?: string; take?: string; beat?: string; + /** Walk only the beats the take changed under the reel (reelAnchor.mjs). */ + changed?: boolean; }) { 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 data = await reelBenchData(project, { reel: r, take: take || null, beat: n }); + const view = data.view; + const all = view.rows ?? []; + // `changed`: the walk visits only the beats the take changed (the beat asked for is shown either way). + const rows = changed ? all.filter((x) => x.n === n || (x.status && CHANGED_STATES.includes(x.status.state))) : all; const i = rows.findIndex((x) => x.n === n); const t = view.take?.id ?? null; return ( @@ -37,16 +44,24 @@ export default async function ReelWalkPage({ trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: reelPlayHref(project.id, { reel: r, take: t, beat: n }), label: `${project.name} · ${r}` }} kind="Reel walk" + keys={[ + { keys: ["[", "]", ",", "."], label: "nudge" }, + { keys: ["space"], label: "play" }, + { keys: ["y"], label: "confirm" }, + { keys: ["g"], label: "gap" }, + { keys: ["u"], label: "undo" }, + { keys: ["b"], label: "the reel" }, + ]} 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} + pos={i >= 0 ? { index: i + 1, total: rows.length, of: changed ? "changed beats" : "beats" } : null} + prev={i > 0 ? { href: reelWalkHref(project.id, { reel: r, take: t, beat: rows[i - 1].n, changed }), 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, changed }), 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} /> + <ReelBench key={`${r}:${t ?? ""}:${n}`} initial={data} changed={changed} /> </NotesProvider> </BenchFrame> ); diff --git a/umtool/components/projects/reel/reelTypes.ts b/umtool/components/projects/reel/reelTypes.ts @@ -10,6 +10,9 @@ export type ReelPiece = { seamless: boolean; moved: unknown; source: { start: number; end: number } | null; + /** A gapped beat: the master spans its gaps leave out (hard cuts), and the seconds it plays. */ + cuts?: { from: number; to: number }[]; + seconds?: number; }; export type ReelRow = { @@ -18,7 +21,7 @@ export type ReelRow = { id: string | null; label: string | null; verdict: "confirmed" | "note" | null; - beat: { start?: number; end?: number; at?: number; dur?: number }; + beat: { start?: number; end?: number; at?: number; dur?: number; gaps?: { from: number; to: number }[] }; problem: string | null; piece: ReelPiece | null; asked: { start: number; end: number } | null; @@ -29,6 +32,27 @@ export type ReelRow = { channel: string | null; video: string | null; date: string | null; + /** What the beat was cut against, read against the take now (lib/report/reelAnchor.mjs). */ + status?: BeatStatus | null; +}; + +export type BeatState = "unanchored" | "orphan" | "clipped" | "edges" | "look" | "rerendered" | "unchanged"; +export type BeatStatus = { + state: BeatState; + why: string; + was?: { start: number; end: number; gaps?: { from: number; to: number }[] } | Record<string, unknown> | null; + now?: { start: number; end: number; gaps?: { from: number; to: number }[] } | Record<string, unknown> | null; +}; +/** The states the walk's "changed beats" filter keeps (reelAnchor.mjs CHANGED_STATES). */ +export const CHANGED_STATES: BeatState[] = ["orphan", "clipped", "edges", "look"]; +export const STATE_LABEL: Record<BeatState, string> = { + unanchored: "not anchored", + orphan: "clip gone", + clipped: "clipped", + edges: "clip's edges moved", + look: "chrome changed", + rerendered: "re-rendered, same", + unchanged: "unchanged", }; export type ReelCut = { @@ -42,6 +66,8 @@ export type ReelCut = { encodeSeconds: number | null; notes: number; stale: boolean; + /** The reel was edited since this cut (its record names the reel's version). */ + reelChanged?: boolean; }; export type ReelJob = { @@ -78,6 +104,8 @@ export type ReelView = { intro?: { at: number; master: { start: number; end: number; duration: number } } | null; total?: number; rows?: ReelRow[]; + /** The reel against the take now: the takes it was cut against, the beats that changed, the line. */ + status?: { take: string; against: string[]; changed: number[]; counts: Record<string, number>; line: string } | null; planNotes?: string[]; reels?: ReelListing[]; job?: ReelJob | null; @@ -86,15 +114,35 @@ export type ReelView = { }; /** 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 }; +export type ReelItem = { key: string; n: number; at: number; mStart: number; mEnd: number; dur: number; seamless: boolean; row: ReelRow | null; cuts: { from: number; to: number }[] }; + +/** The master second `t` reel seconds into an item plays (its cuts skipped). */ +export function masterAt(it: ReelItem, t: number): number { + let m = it.mStart + Math.max(0, Math.min(it.dur, t - it.at)); + for (const c of it.cuts) if (m >= c.from - 1e-6) m += c.to - c.from; + return Math.min(it.mEnd, m); +} + +/** The reel second a master second inside an item plays at (inside a cut: where the cut joins). */ +export function reelAtMaster(it: ReelItem, m: number): number { + let off = m - it.mStart; + for (const c of it.cuts) { + if (m >= c.to) off -= c.to - c.from; + else if (m > c.from) off -= m - c.from; + } + return it.at + Math.max(0, Math.min(it.dur, off)); +} + +/** The cut a master second is inside, if any. */ +export const cutAt = (it: ReelItem, m: number) => it.cuts.find((c) => m >= c.from - 1e-3 && m < c.to - 1e-3) ?? 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 }); + 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, cuts: [] }); 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 }); + 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.seconds ?? r.piece.master.duration, seamless: r.piece.seamless, row: r, cuts: r.piece.cuts ?? [] }); } return out; } diff --git a/umtool/components/projects/reel/useReelPlayer.ts b/umtool/components/projects/reel/useReelPlayer.ts @@ -1,7 +1,7 @@ "use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { itemAt, type ReelItem } from "./reelTypes"; +import { cutAt, itemAt, masterAt, reelAtMaster, 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 @@ -12,7 +12,8 @@ import { itemAt, type ReelItem } from "./reelTypes"; // 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 +// t = item.at + (currentTime − item.mStart), less a gapped beat's cuts, which +// the player seeks over as the cut leaves them out (reelTypes masterAt). Nothing is decoded here that the // browser does not: it is seeks of one file. export type ReelPlayer = { @@ -72,7 +73,7 @@ export function useReelPlayer(items: ReelItem[], xfade: number, vids: React.RefO 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)); + const want = masterAt(it, t); if (Math.abs(v.currentTime - want) > 0.04) v.currentTime = want; }, [items, el], @@ -154,7 +155,10 @@ export function useReelPlayer(items: ReelItem[], xfade: number, vids: React.RefO const it = items[i]; const v = el(i); if (!it || !v) return; - let t = it.at + (v.currentTime - it.mStart); + // A gapped beat's cut: on past it, as the cut plays it (a hard cut). + const c = cutAt(it, v.currentTime); + if (c && !v.seeking) v.currentTime = c.to; + let t = reelAtMaster(it, v.currentTime); 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) { diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -62,7 +62,7 @@ Inbox cannot disagree about what is wrong with one. | `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | | `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade and intro, written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) | -| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; every write an undo point ([knobs.md](knobs.md#the-trailers-beats)) | +| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | | `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | | `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -740,9 +740,31 @@ Its cut is `takes/<t>/out/<slug>.<name>.mp4` (the trailer reel: `<slug>.trailer. | the reels; a new one (empty, or a copy) | the Trailer page's **reels** row, **+ New reel** | `umtool trailer-beats <p> reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` | `GET /api/report/trailer-beats` (`reels`) · `{op: "new-reel", name, from?, title?}` | | a reel's title, the take it is cut from | **title** | `trailer-beats <p> --reel R title <text>\|none` · `take <t>\|none` | `{op: "settings", title?, take?}` | | play the reel from a take's master: the crossfades, the clock against the limit, the strip of beats; `M` a note on the beat on screen (anchor `reel`), `E` walk it, `N`/`P` beats, `[`/`]` notes | **Play the reel** → `/projects/<p>/trailer/play?reel=&take=` (the take picker) | `umtool notes <p>` reads the notes | `GET /api/report/reel?project&reel&take` · the master: `GET /api/report/reel/media?project&take&what=master` | -| walk a beat: in/out handles on the master's frames (`[` `]` in, `,` `.` out, Shift 0.5 s; `I`/`O` at the playhead), saved in the clip's source seconds (`Enter`), the clip's quote and source clock, `B` back to the reel | **Walk it** / `E` → `/projects/<p>/trailer/walk?reel=&take=&beat=n` | `trailer-beats <p> --reel R set <n> <from>-<to>` | `{op: "set", index, patch: {start, end}}` | +| walk a beat: the reel's own editor on the clip bench's parts -- the master's waveform (its envelope, on the clip's source clock) with the zoom (`z`/`Z`/`f`/`F`, Ctrl/⌘ + wheel; ruler, overview, close-in pauses and words), the handles and nudges (`[` `]` in, `,` `.` out, Shift 0.5 s; `I`/`O` at the playhead) held to what the master rendered of the clip (said when a handle hits it), exact playback (`Space`, `-`/`=` speed), tighten to the sentence and snap an edge to a pause; saved in the clip's source seconds (`Enter`), `R` puts back, `B` back to the reel | **Walk it** / `E` → `/projects/<p>/trailer/walk?reel=&take=&beat=n` | `trailer-beats <p> --reel R set <n> <from>-<to> [--take <t>]` | `{op: "set", index, patch: {start, end}, take?}` · the master: `GET /api/report/file?project&path&v` · its envelope `GET /api/report/peaks?project&path&from&to` · its sound `GET /api/report/audio?project&path&from&to` | +| a beat's **gaps**: seconds cut out of its middle, in the clip's source seconds -- two moments of one clip as one beat of jump cuts (the clip gap rule: ≥ 0.2 s each, 0.5 s kept before, between and after, at most 12); cut as the clip's gap renders (hard cuts, the sound faded 0.025 s), never the beat-to-beat crossfade; Play the reel skips them and its clock counts kept seconds; a gap wholly inside one the master already cut out of the clip is refused | the walk: `Alt` + drag on the waveform (or **Select a gap** / `g`), **Cut gap** (`g`), **Hear it**, a click on a gap's band puts it back, `G` the one at the playhead, **Undo** | `trailer-beats <p> --reel R gap <n> add <from>-<to>` · `gap <n> remove <second>` · `gap <n> clear` | `{op: "set", index, patch: {gaps: [{from, to}…]}}` | | a beat's verdict: `confirmed` (Y, and on to the next) or `note` (a note left on it) | the walk's **Confirm (Y)** · **Note (M)** · **Clear verdict** | `trailer-beats <p> --reel R verdict <n> confirmed\|note\|clear` | `{op: "set", index, patch: {verdict}}` | -| cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path | the Trailer page's **Cut the trailer** | `umtool trailer <p> --reel <name> [--take <t>]` | `POST /api/report/reel {project, reel, take}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` | +| cut it: a job on umtool's runner (one at a time, the heavy slot, its log, **Cancel**), the result playing with its local path; its record names the take's build, the master's mtime and the reel's version, so the Cut panel says when the master was re-rendered or the reel edited since | the Trailer page's **Cut the trailer** | `umtool trailer <p> --reel <name> [--take <t>]` | `POST /api/report/reel {project, reel, take}` · `?cancel=<job>` · `GET ?job=<id>` · the file: `…/reel/media?what=cut&reel=` | + +### Reels track their source + +A reel is an edit of a master that keeps changing. A beat stays addressed in its clip's source seconds; each beat also +carries an **anchor** -- what it was cut against: the take, its build, the master's mtime, the source span the clip's +segment played (its cut record's start, end and gaps), the segment's content key, a fingerprint of the chrome and fx +over it (timed from the segment's start, so a clip that only moved in the master is not changed), and the master span +it resolved to (`lib/report/reelAnchor.mjs`). The writer stamps it on every beat added or edited against a take (the +walk's writes always are), and keeps it through an edit made without one. On load each beat is read against the take +the reel plays now: **unchanged**; **re-rendered, same** (another render, this clip identical: still good); **clip's +edges moved** (the beat still fits: old vs new); **chrome changed** (the chrome or fx over it: look at it); **clipped** +(the clip's new limits cut into the beat: clamp, or re-place it); **clip gone** (remove it, or re-point it to another +clip); **not anchored** (written before anchors). Every write and undo is appended to +`promo/<name>-beats.history.json` (per beat, each field's old and new; 200 entries, newest last). + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the reel against the take now: "cut against draft-6; take draft-7 changes beat 7", and each beat's state and why | the banner over the walk and Play the reel; each beat's state line in the walk | `umtool trailer-beats <p> --reel R status [--take <t>] [--json]` | `GET /api/report/reel` (`status`, each row's `status`) | +| walk only the changed beats | the banner's **Walk only the changed beats** → `…/trailer/walk?…&changed=1` (N, P and the head's ‹ › skip the rest) | `status` lists them | — | +| clamp a clipped beat; remove or re-point an orphan; anchor a beat that has been looked at | the beat's **Clamp to …**, **Remove the beat**, **Re-point**, **Looked at — anchor to <take>** (an edit or a confirm in the walk re-anchors too) | `trailer-beats <p> --reel R clamp <n>` · `repoint <n> <clip>` · `remove <n>` · `anchor [<n>…] --take <t>` · `--take <t>` on any edit | `{op: "set", index, patch, take}` · `{op: "anchor", only?, take}` | +| what changed, when, against which take | -- | `trailer-beats <p> --reel R history [--json]` | `promo/<name>-beats.history.json` | ## Takes: relabel, supersede, cancel, delete, fork as variant, compare diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1399,8 +1399,26 @@ moves each edge into its pause, as above. **Play the reel** (`…/trailer/play`) back to back, the reel's crossfade dissolved in the browser. It shows the running clock against the limit and a strip of the beats, and takes notes anchored to a beat (`M`; the `reel` anchor, which `umtool notes` prints with the writer to use). **Walk it** (`…/trailer/walk?beat=n`) is the -bench over one beat. Its in/out handles and nudge keys work on the master's frames, and a save -writes the clip's source seconds. Each beat gets a verdict (`confirmed`, or `note`). Every write +reel's own editor, built from the clip bench's parts (`components/projects/bench/`): the master's +waveform and its zoom, the handles and nudges, exact playback, tighten and snap, and a beat's +gaps. What plays is the take's master through its build record's map onto the clip's source -- +the bench's "use a file" media (a rendered file of the project, its envelope and its sound by +span); what is edited is the beat, in the clip's source seconds, held to what the master rendered +of the clip. Each beat gets a verdict (`confirmed`, or `note`). + +A clip beat may carry **gaps** (`gaps: [{from, to}]`, source seconds, the clip gap rule): two +moments of one clip as one beat of jump cuts. The cut maps each gap to the master seconds it +covers (across a gap the render already cut, the master runs on: the span either side) and +leaves them out of the beat as a clip's gap renders -- hard cuts, the sound faded 0.025 s either +side -- never with the beat-to-beat crossfade; the reel's clock counts kept seconds, and Play the +reel seeks over them. + +A beat carries an **anchor**: the take, build and master it was cut against, the clip's segment +as it was, and a fingerprint of the chrome and fx over it. Read against the take the reel plays +now, each beat is unchanged, re-rendered but the same, changed under it (the clip's edges, its +chrome), clipped, or orphaned -- the walk's banner and `trailer-beats … status` say which, and +offer the fix ([knobs.md](knobs.md#reels-track-their-source)). A cut's record names the reel's +version and the master it read, so a cut older than either is said. Every write goes through the one writer and leaves an undo point (`U`, **Undo**, `trailer-beats … undo`). **Cut the trailer** runs `umtool trailer --reel` as a job on umtool's runner (the heavy slot, its log, Cancel), and the file then plays on the page with its local path. A cancelled cut leaves no diff --git a/umtool/e2e/reel-play.spec.ts b/umtool/e2e/reel-play.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type Page } from "@playwright/test"; -import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; @@ -17,11 +17,13 @@ import * as urls from "./urls"; // reel-none-fixture its one take a draft with no master. // // The reel's Play (from the master, the crossfade, the clock against the -// limit, a note on a beat), its walk (handles and nudges on the master's -// frames, written in source seconds through the one writer, an undo point per -// write, Confirm walks on, Back to the reel), Cut the trailer as a job with -// the result's local path, and the no-master state. Fixture: -// e2e/fixtures/reel-fixture.mjs. +// limit, a note on a beat), its walk -- the reel's own editor on the clip +// bench's parts (lane/reel-bench): the master's waveform and zoom, nudges and +// a drag held to what the master rendered, written in source seconds through +// the one writer, tighten, an undo point per write, Confirm walks on, Back to +// the reel -- a beat's gap (Alt + drag, Cut gap; Play skips it and counts kept +// seconds), Cut the trailer as a job with the result's local path, and the +// no-master state. Fixture: e2e/fixtures/reel-fixture.mjs. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -31,17 +33,22 @@ const PROMO = path.join(DIR, "promo"); const OUT = path.join(DIR, "takes", "draft-1", "out"); const NOTES = path.join(DIR, "notes.json"); -const beatsOf = (reel = "trailer") => { +/** The reel's beats as written; `anchors` keeps what each was cut against (a walk's write anchors it to the take). */ +const beatsOf = (reel = "trailer", { anchors = false } = {}) => { const d = JSON.parse(readFileSync(path.join(PROMO, `${reel}-beats.json`), "utf8")); - return (Array.isArray(d) ? d : d.beats) as { id?: string; start?: number; end?: number; verdict?: string }[]; + const list = (Array.isArray(d) ? d : d.beats) as { id?: string; start?: number; end?: number; verdict?: string; anchor?: unknown }[]; + return anchors ? list : list.map(({ anchor: _a, ...b }) => b); }; const root = (page: Page) => page.locator("[data-reel-play]"); +const C03 = path.join(OUT, "sourced", "segments", "c03.cut.json"); + test.beforeAll(() => { for (const f of ["trailer-beats.json", "teaser-beats.json"]) { const p = path.join(PROMO, f); if (!existsSync(`${p}.pristine`)) copyFileSync(p, `${p}.pristine`); } + if (!existsSync(`${C03}.pristine`)) copyFileSync(C03, `${C03}.pristine`); }); test.beforeEach(() => { test.setTimeout(120_000); @@ -51,6 +58,7 @@ test.beforeEach(() => { } for (const f of readdirSync(OUT)) if (/\.(trailer|teaser)\.(mp4|json)$/.test(f) || f.endsWith(".trailer.json")) rmSync(path.join(OUT, f), { force: true }); rmSync(NOTES, { force: true }); + copyFileSync(`${C03}.pristine`, C03); }); test("the Trailer page lists the reels; a reel plays from the take's rendered master, beat after beat, against the limit; a note lands on its beat", async ({ page }) => { @@ -103,7 +111,7 @@ test("the Trailer page lists the reels; a reel plays from the take's rendered ma await expect(page.locator("[data-reel-walk]")).toHaveAttribute("data-reel-beat", "2"); }); -test("the walk: in/out on the master's frames, written in source seconds through the one writer; each write an undo point; Confirm walks on; Back to the reel", async ({ page }) => { +test("the walk is the reel's own editor on the clip bench's parts: the master's waveform and zoom, nudges and a drag held to what the master rendered, saved in source seconds; tighten; undo; Confirm walks on; Back to the reel", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.reelWalkHref(PROJECT, { beat: 2 })); const walk = page.locator("[data-reel-walk]"); @@ -111,31 +119,51 @@ test("the walk: in/out on the master's frames, written in source seconds through await expect(walk).toHaveAttribute("data-reel-dirty", "0"); await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:05.00 – 0:06.50"); await expect(page.locator("[data-reel-beat-quote]")).toContainText("the words of c03"); - await expect(page.locator("[data-reel-handle]")).toHaveCount(2); + await expect(page.locator("[data-reel-limits]")).toContainText("0:04.75–0:06.75"); + // The master's waveform (its envelope, on the clip's source clock), over the seconds its segment plays. + const box = page.locator("[data-wave-box]"); + await expect(box).toHaveAttribute("data-wave-vis", "4.75-6.75"); + await expect(page.locator("[data-reel-walk-video]")).toHaveAttribute("src", /\/api\/report\/file\?.*path=takes%2Fdraft-1%2Fout%2Freel-fixture\.mp4/); + await expect(page.locator("[data-playback]")).toHaveAttribute("data-audio-state", "ready", { timeout: 15_000 }); + + // The zoom: z closer (the ruler and the overview), f back to the whole segment. + await page.keyboard.press("z"); + await expect(box).not.toHaveAttribute("data-wave-vis", "4.75-6.75"); + await expect(page.locator("[data-zoom-overview]")).toHaveCount(1); + await page.keyboard.press("f"); + await expect(box).toHaveAttribute("data-wave-vis", "4.75-6.75"); - // ] twice: the in edge 0.1 s later; . with Shift: the out edge 0.5 s later -- held to the clip's cut (6.75). + // ] twice: the in edge 0.1 s later; . with Shift: the out edge 0.5 s later -- held to the segment (6.75), and said. await page.keyboard.press("]"); await page.keyboard.press("]"); await page.keyboard.press("Shift+."); await expect(walk).toHaveAttribute("data-reel-dirty", "1"); await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:05.10 – 0:06.75"); + await expect(page.locator("[data-reel-limit-hit='end']")).toContainText("the end of what the master rendered for c03"); await page.keyboard.press("Enter"); await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5.1, end: 6.75 }); await expect(walk).toHaveAttribute("data-reel-dirty", "0"); - await expect(page.locator("[data-reel-msg]")).toContainText("saved — beat 2 5.1–6.75"); + await expect(page.locator("[data-reel-msg]")).toContainText("saved beat 2: edges"); - // A handle dragged: the in edge back to the segment's start (the clip's cut, 4.75). - const track = await page.locator("[data-reel-track]").boundingBox(); - const h = await page.locator("[data-reel-handle='from']").boundingBox(); - await page.mouse.move(h!.x + h!.width / 2, h!.y + h!.height / 2); + // The in handle dragged on the waveform past the segment's start: held at 4.75. + const wb = (await box.boundingBox())!; + const xOf = (t: number) => wb.x + ((t - 4.75) / 2) * wb.width; + await page.mouse.move(xOf(5.1), wb.y + wb.height / 2); await page.mouse.down(); - await page.mouse.move(track!.x + 2, h!.y + h!.height / 2, { steps: 5 }); + await page.mouse.move(wb.x - 20, wb.y + wb.height / 2, { steps: 6 }); await page.mouse.up(); await expect(page.locator("[data-reel-source-edges]")).toHaveText("source 0:04.75 – 0:06.75"); await page.locator("[data-reel-save]").click(); await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 4.75, end: 6.75 }); await page.screenshot({ path: test.info().outputPath("reel-walk.png") }); + // Tighten to the sentence is the clip bench's own button, over the clip's words: it says what it did. + await page.locator("[data-tighten]").click(); + await expect(page.locator("[data-reel-msg]")).toContainText(/tightened|already tight|not tightened/); + // A tighten that moved the edges is a write of its own: U takes it back. + await page.waitForTimeout(300); + if (JSON.stringify(beatsOf()[1]) !== JSON.stringify({ id: "c03", start: 4.75, end: 6.75 })) await page.keyboard.press("u"); + await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 4.75, end: 6.75 }); // U: the last write undone, then the one before. await page.keyboard.press("u"); await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5.1, end: 6.75 }); @@ -158,6 +186,80 @@ test("the walk: in/out on the master's frames, written in source seconds through await expect(page.locator("[data-beat='2'] [data-beat-verdict='confirmed']")).toHaveCount(1); }); +test("a beat's gap: Alt + drag on the master's waveform, Cut gap writes it in source seconds, the reel's Play skips it and its clock counts kept seconds; undo takes it back", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.reelWalkHref(PROJECT, { beat: 2 })); + const box = page.locator("[data-wave-box]"); + await expect(box).toHaveAttribute("data-wave-vis", "4.75-6.75"); + const wb = (await box.boundingBox())!; + const xOf = (t: number) => wb.x + ((t - 4.75) / 2) * wb.width; + const y = wb.y + wb.height / 2; + await page.keyboard.down("Alt"); + await page.mouse.move(xOf(5.5), y); + await page.mouse.down(); + await page.mouse.move(xOf(5.8), y, { steps: 5 }); + await page.mouse.up(); + await page.keyboard.up("Alt"); + await expect(page.locator("[data-gap-cut]")).toBeVisible(); + await page.keyboard.press("g"); + await expect.poll(() => (beatsOf()[1] as { gaps?: { from: number; to: number }[] }).gaps?.length ?? 0).toBe(1); + const g = (beatsOf()[1] as { gaps: { from: number; to: number }[] }).gaps[0]; + expect(Math.abs(g.from - 5.5)).toBeLessThan(0.03); + expect(Math.abs(g.to - 5.8)).toBeLessThan(0.03); + await expect(page.locator("[data-reel-walk]")).toHaveAttribute("data-reel-gaps", `${g.from}-${g.to}`); + await expect(page.locator("[data-gaps-summary]")).toContainText("1 gap"); + await expect(page.locator("[data-reel-msg]")).toContainText("one beat of jump cuts"); + + // Play the reel: 3.8 s less the gap's seconds, and it plays through, skipping it. + await page.goto(urls.reelPlayHref(PROJECT)); + const cut = g.to - g.from; + const total = 3.8 - cut; + await expect(page.locator("[data-reel-clock]")).toHaveText(`0:00.0 / 0:0${total.toFixed(1)}`); + await page.locator("[data-reel-toggle]").click(); + await expect(root(page)).toHaveAttribute("data-reel-beat", "3", { timeout: 15_000 }); + await expect(root(page)).toHaveAttribute("data-reel-state", "paused", { timeout: 15_000 }); + expect(Number(await root(page).getAttribute("data-reel-t"))).toBeGreaterThan(total - 0.2); + + // Back on the walk, U takes the gap back. + await page.goto(urls.reelWalkHref(PROJECT, { beat: 2 })); + await page.keyboard.press("u"); + await expect.poll(() => beatsOf()[1]).toEqual({ id: "c03", start: 5, end: 6.5 }); +}); + +test("reels track their source: a beat anchored to the take, then its clip's end moved under it -- flagged, walked alone, clamped; the history says so", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.reelWalkHref(PROJECT, { beat: 2 })); + await expect(page.locator("[data-reel-source-line]")).toHaveText("no beat is anchored yet"); + await expect(page.locator("[data-reel-beat-state]")).toHaveAttribute("data-reel-beat-state", "unanchored"); + await page.locator("[data-reel-anchor]").click(); + await expect(page.locator("[data-reel-beat-state]")).toHaveAttribute("data-reel-beat-state", "unchanged"); + expect((beatsOf("trailer", { anchors: true })[1] as { anchor?: { take: string; clip: { end: number } } }).anchor).toMatchObject({ take: "draft-1", clip: { start: 4.75, end: 6.75 } }); + + // The take's record for c03 now ends at 6.6 (as if the clip's edge moved and the take were rendered again): + // beat 2 still fits -- its clip's edges moved; the reel says which beat. + const rec = JSON.parse(readFileSync(C03, "utf8")); + writeFileSync(C03, JSON.stringify({ ...rec, end: 6.6 })); + await page.goto(urls.reelWalkHref(PROJECT, { beat: 1 })); + await expect(page.locator("[data-reel-source-line]")).toHaveText("take draft-1 changes beat 2"); + await page.locator("[data-reel-walk-filter='changed']").click(); + await expect(page).toHaveURL(/beat=2.*changed=1|changed=1.*beat=2/); + await expect(page.locator("[data-bench-pos]")).toHaveText("1 of 1 changed beats"); + await expect(page.locator("[data-reel-beat-state]")).toHaveAttribute("data-reel-beat-state", "edges"); + await expect(page.locator("[data-reel-beat-was]")).toHaveText("was 0:04.75–0:06.75 · now 0:04.75–0:06.60"); + await page.screenshot({ path: test.info().outputPath("reel-changed.png") }); + + // Pulled in past the beat: clipped, and Clamp fits it back -- anchored to the take it was fixed against. + writeFileSync(C03, JSON.stringify({ ...rec, end: 6.3 })); + await page.reload(); + await expect(page.locator("[data-reel-beat-state]")).toHaveAttribute("data-reel-beat-state", "clipped"); + await page.locator("[data-reel-clamp]").click(); + await expect.poll(() => (beatsOf()[1] as { end: number }).end).toBe(6.3); + await expect(page.locator("[data-reel-beat-state]")).toHaveAttribute("data-reel-beat-state", "unchanged"); + const hist = JSON.parse(readFileSync(path.join(PROMO, "trailer-beats.history.json"), "utf8")).entries as { what: string; take?: string }[]; + expect(hist.map((e) => e.what)).toEqual(["anchor beat 2 to take draft-1", "beat 2: start, end"]); + expect(hist[1].take).toBe("draft-1"); +}); + test("Cut the trailer: a job on the runner, its log, the result playing on the page with its local path; a new reel", async ({ page }) => { await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.trailerHref(PROJECT, { reel: "teaser" })); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -306,9 +306,9 @@ export function reelPlayHref(project: string, q: NoteOpt & { reel?: string | nul ); } -/** A beat reel's walk: the bench over beat `beat` (from 1) on the take's master. */ -export function reelWalkHref(project: string, q: { reel?: string | null; take?: string | null; beat?: number | null } = {}): string { - return withQuery(`/projects/${encodePath(project)}/trailer/walk`, { reel: q.reel && q.reel !== "trailer" ? q.reel : null, take: q.take, beat: q.beat ?? 1 }); +/** A beat reel's walk: the bench over beat `beat` (from 1) on the take's master; `changed` walks only the beats the take changed. */ +export function reelWalkHref(project: string, q: { reel?: string | null; take?: string | null; beat?: number | null; changed?: boolean } = {}): string { + return withQuery(`/projects/${encodePath(project)}/trailer/walk`, { reel: q.reel && q.reel !== "trailer" ? q.reel : null, take: q.take, beat: q.beat ?? 1, changed: q.changed ? "1" : null }); } export function takesHref(project: string, q: NoteOpt = {}): string { diff --git a/umtool/lib/report/fileMedia.mjs b/umtool/lib/report/fileMedia.mjs @@ -0,0 +1,80 @@ +// A RENDERED FILE AS A BENCH'S MEDIA (lane/reel-bench, 2 Nov). +// +// The clip bench plays a clip's cached RAW window, on the source clock. A +// reel's walk plays a take's rendered MASTER -- the final frames, the chrome +// burned in -- and works on the same source seconds: a beat is written in its +// clip's source seconds, the cues and words are the clip's. Between the two +// clocks is the build record's map: the file second the clip's segment +// starts at (`segStart`), the source second its picture starts at +// (`recStart`), and the source seconds the render cut out of it (`gaps`, +// gaps.mjs). Within a kept piece the map is a shift; across a gap the file +// goes straight on while the source jumps. +// +// Plain ESM: the bench's media adapter (components/projects/bench/benchMedia.ts) +// and the tests read it. +import { inGap, offsetIn, sourceAtOffset } from "umtool-report-to-video/gaps"; + +/** + * @typedef {{ segStart: number, recStart: number, gaps: Array<{ from: number, to: number }> }} FileMap + */ + +/** + * The file second a source second plays at (a second inside a gap the render + * cut out: the join). + * + * @param {FileMap} map + * @param {number} src + */ +export const fileAt = (map, src) => map.segStart + offsetIn(src, map.recStart, map.gaps ?? []); + +/** + * The source second a file second shows; at a join, the material after the gap. + * + * @param {FileMap} map + * @param {number} t + */ +export const sourceAt = (map, t) => sourceAtOffset(t - map.segStart, map.recStart, map.gaps ?? []); + +/** + * Source-second spans as spans of the file's clock: what is left of each once + * the render's own gaps are out (a span wholly inside one is nothing, and + * dropped). + * + * @param {FileMap} map + * @param {Array<{ from: number, to: number }>} spans + * @param {number} [min] shorter than this on the file's clock is dropped + */ +export function fileSpans(map, spans, min = 1e-3) { + const out = []; + for (const s of spans ?? []) { + const a = fileAt(map, s.from); + const b = fileAt(map, s.to); + if (b - a > min) out.push({ from: a, to: b }); + } + return out; +} + +/** + * A file's peaks (uniform over a span of the FILE's clock) as peaks over a + * span of SOURCE seconds -- what the bench's waveform draws. A source second + * inside a gap the render cut out is silence. + * + * @param {{ from: number, to: number, min: number[], max: number[] }} peaks on the file's clock + * @param {{ from: number, to: number }} span source seconds + * @param {FileMap} map + * @param {number} [n] buckets out + */ +export function peaksOnSource(peaks, span, map, n = peaks.max.length) { + const k = peaks.max.length; + const pSpan = Math.max(1e-9, peaks.to - peaks.from); + const width = Math.max(1e-9, span.to - span.from); + const min = []; + const max = []; + for (let b = 0; b < n; b += 1) { + const t = span.from + ((b + 0.5) / n) * width; + const i = inGap(t, map.gaps) ? -1 : Math.floor(((fileAt(map, t) - peaks.from) / pSpan) * k); + min.push(i >= 0 && i < k ? peaks.min[i] : 0); + max.push(i >= 0 && i < k ? peaks.max[i] : 0); + } + return { from: span.from, to: span.to, min, max }; +} diff --git a/umtool/lib/report/projectFile.mjs b/umtool/lib/report/projectFile.mjs @@ -0,0 +1,46 @@ +// A FILE OF THE PROJECT, served to a bench ("use a file", lane/reel-bench): a +// rendered file -- a take's master first -- that a bench plays, decodes and +// draws the envelope of, named by its path RELATIVE to the project. +// +// The path is lexical first (inside the project, no `..`, a media file by its +// extension), then real: the file's real path must stay under the real path +// of the project or of one of its own directories on the way to it -- a +// take's out/ may be a link to the media drive, and that link is the +// project's own decision; nothing else is followed out of it. +// +// Plain ESM. +import { realpath, stat } from "node:fs/promises"; +import path from "node:path"; + +/** What a bench may play. */ +export const PROJECT_MEDIA = /\.(mp4|m4v|mov|mkv|webm|m4a|mp3|wav)$/i; + +/** + * @param {{ dir: string }} project + * @param {string} rel + * @returns {Promise<{ abs: string, rel: string, size: number, mtimeMs: number } | { error: string, status: number }>} + */ +export async function resolveProjectFile(project, rel) { + const r = String(rel ?? "").replace(/\\/g, "/"); + if (!r || r.startsWith("/") || r.split("/").some((s) => s === ".." || s === "" || s === ".")) return { error: "path is a file inside the project, relative to it", status: 400 }; + if (!PROJECT_MEDIA.test(r)) return { error: "path names a media file (mp4, mov, mkv, webm, m4a, mp3, wav)", status: 400 }; + const lexical = path.join(project.dir, ...r.split("/")); + const real = await realpath(lexical).catch(() => null); + if (!real) return { error: `no ${r} in this project`, status: 404 }; + // The project's own directories on the way to the file, each by its real path. + const segs = r.split("/").slice(0, -1); + const roots = [project.dir]; + for (let k = 1; k <= segs.length; k += 1) roots.push(path.join(project.dir, ...segs.slice(0, k))); + let ok = false; + for (const d of roots) { + const rd = await realpath(d).catch(() => null); + if (rd && real.startsWith(`${rd}${path.sep}`)) { + ok = true; + break; + } + } + if (!ok) return { error: "not served", status: 403 }; + const st = await stat(real).catch(() => null); + if (!st?.isFile()) return { error: "gone", status: 404 }; + return { abs: real, rel: r, size: st.size, mtimeMs: Math.round(st.mtimeMs) }; +} diff --git a/umtool/lib/report/reelAnchor.mjs b/umtool/lib/report/reelAnchor.mjs @@ -0,0 +1,200 @@ +// REELS TRACK THEIR SOURCE (lane/reel-bench, 2 Nov). +// +// A reel is an edit of a rendered master that keeps changing: a new take, a +// clip's edges moved, a clip taken out of the cut, the chrome or the fx over +// a clip changed. A beat stays ADDRESSED in its clip's source seconds -- that +// is what survives a re-render -- and carries an ANCHOR: what it was cut +// against when it was made or last edited. The anchor is provenance, never +// the address: +// +// take, build, masterMtimeMs the take, its build (take.json builtAt), and +// its master's mtime +// clip { start, end, gaps } the source seconds the clip's segment played +// (its cut record: start/end, the gaps it left out) +// seg the segment's content key (the cut record's +// segKey: the picture and sound of the clip) +// fx a fingerprint of the chrome and the fx over +// the clip's segment (the schedule's entry for it +// and the receipts/zoom it carries, timed from the +// segment's start -- so a shift is not a change) +// master { start, end } the master span the beat resolved to +// at when +// +// On load each beat is CLASSIFIED against the take the reel plays now +// (classifyBeat, pure): +// +// unanchored written before anchors (or by hand): nothing to compare +// orphan its clip is gone from the cut -- remove it, or re-point it +// clipped the clip's new limits cut into the beat -- clamp, or re-place +// edges the clip's edges or gaps moved; the beat still fits (old vs new) +// look the chrome or fx in its span changed -- look at it +// rerendered another render, this clip identical -- still good +// unchanged the very master it was cut against +// +// Plain ESM: the page's view, the writer's route and `umtool trailer-beats +// status` read it. +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { recordGaps } from "umtool-report-to-video/gaps"; +import { TrailerError, loadTakeBuild, parseBeats, planTrailer } from "umtool-report-to-video/trailer"; + +export const BEAT_STATES = Object.freeze(["unanchored", "orphan", "clipped", "edges", "look", "rerendered", "unchanged"]); +/** The states that ask for a person: the walk's "changed beats" filter. */ +export const CHANGED_STATES = Object.freeze(["orphan", "clipped", "edges", "look"]); + +const r3 = (n) => Number(Number(n).toFixed(3)); +const EPS = 0.02; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const sha = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 16); + +/** The chrome and fx over one clip's segment, timed from the segment's start: their fingerprint. */ +export function fxFingerprint(schedule, id) { + const seg = (schedule?.segments ?? []).find((s) => s?.id === id); + if (!seg) return null; + const { start, end, duration, ...chrome } = seg; + const rel = (t) => (Number.isFinite(t) ? r3(t - start) : t); + const fx = {}; + for (const [k, v] of Object.entries(schedule?.fx ?? {})) { + if (!isObj(v) || !Array.isArray(v.clips)) continue; + const mine = v.clips + .filter((c) => c?.segment === id) + .map((c) => ({ ...c, in: rel(c.in), out: rel(c.out), markAt: rel(c.markAt), cards: (c.cards ?? []).map((x) => ({ ...x, at: rel(x.at) })) })); + if (mine.length) fx[k] = { ...v, clips: mine }; + } + return sha({ chrome, fx }); +} + +/** What a take's build says of one clip now: present, the source span its segment plays, its content key, its fx. */ +export function clipSnapshot(build, id) { + const rec = build.records.get(id); + const inSchedule = (build.schedule?.segments ?? []).some((s) => s?.id === id); + if (!rec || !inSchedule || !Number.isFinite(rec.start) || !Number.isFinite(rec.end)) return { present: false }; + return { + present: true, + clip: { start: r3(rec.start), end: r3(rec.end), gaps: recordGaps(rec).map((g) => ({ from: r3(g.from), to: r3(g.to) })) }, + seg: typeof rec.segKey === "string" ? rec.segKey : sha({ start: rec.start, end: rec.end, gaps: recordGaps(rec) }), + fx: fxFingerprint(build.schedule, id), + }; +} + +/** + * A take's anchoring context: its build, and `anchorFor(beat)` -- the anchor + * a beat gets when it is written against this take (null when the beat does + * not map onto it: the beat is written without one, and says so on load). + * + * @param {string} takeDir + * @param {{ take: string, masterMtimeMs?: number | null, now?: () => string, build?: any }} o `build`: loadTakeBuild's, when it is read already + */ +export async function anchorContext(takeDir, { take, masterMtimeMs = null, now = () => new Date().toISOString(), build: loaded = null }) { + const build = loaded ?? (await loadTakeBuild(takeDir)); + const meta = await readFile(path.join(takeDir, "take.json"), "utf8").then(JSON.parse, () => null); + const buildId = typeof meta?.builtAt === "string" ? meta.builtAt : null; + const anchorFor = (beat) => { + let piece = null; + try { + const [b] = parseBeats([beat]); + piece = planTrailer({ schedule: build.schedule, records: build.records, beats: [b], xfade: 0, snap: false }).pieces[0]; + } catch (e) { + if (e instanceof TrailerError) return null; + throw e; + } + const base = { take, build: buildId, masterMtimeMs, master: { start: piece.master.start, end: piece.master.end }, at: now() }; + if (beat.id === undefined) return base; + const s = clipSnapshot(build, beat.id); + if (!s.present) return null; + return { ...base, clip: s.clip, seg: s.seg, fx: s.fx }; + }; + // Named by its take, for the history the writer keeps (trailerBeats.mjs anchorTake). + anchorFor.take = take; + return { take, build: buildId, masterMtimeMs, schedule: build.schedule, records: build.records, anchorFor, snapshot: (id) => clipSnapshot(build, id) }; +} + +const sameGaps = (a = [], b = []) => a.length === b.length && a.every((g, i) => Math.abs(g.from - b[i].from) < EPS && Math.abs(g.to - b[i].to) < EPS); + +/** + * One beat against the take it plays now. Pure. + * + * @param {Record<string, any>} beat the reel file's beat (its `anchor`, if any) + * @param {{ take: string, build: string | null, masterMtimeMs: number | null, snapshot: (id: string) => ReturnType<typeof clipSnapshot> }} now + * @returns {{ state: string, why: string, was?: any, now?: any }} + */ +export function classifyBeat(beat, now) { + const a = isObj(beat?.anchor) ? beat.anchor : null; + const isClip = beat?.id !== undefined; + const snap = isClip ? now.snapshot(beat.id) : null; + // Gone from the cut is said whether or not the beat was anchored. + if (isClip && !snap.present) return { state: "orphan", why: `${beat.id} is not in take ${now.take}'s cut any more — remove the beat, or re-point it to another clip`, was: a?.clip ?? null }; + if (isClip) { + const c = snap.clip; + if (beat.start < c.start - EPS || beat.end > c.end + EPS) { + return { + state: "clipped", + why: `${beat.id} now plays source ${c.start}–${c.end}${a?.clip ? ` (was ${a.clip.start}–${a.clip.end})` : ""}: the beat ${beat.start}–${beat.end} reaches past it — clamp it, or re-place it`, + was: a?.clip ?? null, + now: c, + }; + } + } + if (!a) return { state: "unanchored", why: "written before beats were anchored: nothing to compare (anchor it to this take)" }; + if (isClip) { + const c = snap.clip; + if (a.clip && (Math.abs(a.clip.start - c.start) > EPS || Math.abs(a.clip.end - c.end) > EPS || !sameGaps(a.clip.gaps, c.gaps))) { + const moved = [ + Math.abs(a.clip.start - c.start) > EPS ? `start ${a.clip.start} → ${c.start}` : null, + Math.abs(a.clip.end - c.end) > EPS ? `end ${a.clip.end} → ${c.end}` : null, + !sameGaps(a.clip.gaps, c.gaps) ? "its gaps" : null, + ].filter(Boolean); + return { state: "edges", why: `${beat.id}'s ${moved.join(", ")} since take ${a.take}; the beat still fits — check its edges`, was: a.clip, now: c }; + } + if ((a.fx ?? null) !== (snap.fx ?? null) || (a.seg && snap.seg && a.seg !== snap.seg)) { + return { state: "look", why: `the ${a.fx !== snap.fx ? "chrome or fx" : "picture or sound"} over ${beat.id} changed since take ${a.take} — look at it`, was: { seg: a.seg, fx: a.fx }, now: { seg: snap.seg, fx: snap.fx } }; + } + } + if (a.take !== now.take || (a.build ?? null) !== (now.build ?? null) || (a.masterMtimeMs ?? null) !== (now.masterMtimeMs ?? null)) { + return { state: "rerendered", why: `cut against take ${a.take}${a.take === now.take ? " (rendered again since)" : ""}; ${isClip ? `${beat.id} is the same in take ${now.take}` : "a master beat: its seconds are as written"}` }; + } + return { state: "unchanged", why: `the master it was cut against (take ${a.take})` }; +} + +/** + * Every beat of a reel against the take it plays now, and the reel's line: + * which takes it was cut against, and the beats that changed. + * + * @param {any[]} beats + * @param {Parameters<typeof classifyBeat>[1]} now + */ +export function reelStatus(beats, now) { + const rows = (beats ?? []).map((b, i) => ({ n: i + 1, id: b?.id ?? null, ...classifyBeat(b, now) })); + const against = [...new Set((beats ?? []).map((b) => b?.anchor?.take).filter((t) => typeof t === "string"))]; + const changed = rows.filter((r) => CHANGED_STATES.includes(r.state)).map((r) => r.n); + const counts = Object.fromEntries(BEAT_STATES.map((s) => [s, rows.filter((r) => r.state === s).length])); + const others = against.filter((t) => t !== now.take); + const line = !rows.length + ? "no beats" + : others.length + ? `cut against ${others.join(", ")}; take ${now.take} ${changed.length ? `changes beat${changed.length === 1 ? "" : "s"} ${changed.join(", ")}` : "changes none of them"}` + : changed.length + ? `take ${now.take} changes beat${changed.length === 1 ? "" : "s"} ${changed.join(", ")}` + : counts.unanchored === rows.length + ? "no beat is anchored yet" + : `every anchored beat matches take ${now.take}`; + return { take: now.take, against, changed, counts, line, rows }; +} + +/** + * The fix a status offers, as a beat patch (or null): `clamp` pulls a clipped + * beat inside the clip's new limits (its gaps kept where they still fit), + * `repoint` names another clip of the cut for it (the seconds kept; refused + * by the writer when they do not fit that clip). + * + * @param {Record<string, any>} beat + * @param {{ clip: { start: number, end: number } }} snap clipSnapshot's, present + */ +export function clampPatch(beat, snap) { + const start = Math.max(beat.start, snap.clip.start); + const end = Math.min(beat.end, snap.clip.end); + if (!(end - start >= 0.2)) return null; + const gaps = (beat.gaps ?? []).filter((g) => g.from >= start + 0.5 && g.to <= end - 0.5); + return { start: Number(start.toFixed(2)), end: Number(end.toFixed(2)), ...(beat.gaps ? { gaps } : {}) }; +} diff --git a/umtool/lib/report/reelAnchor.test.mjs b/umtool/lib/report/reelAnchor.test.mjs @@ -0,0 +1,151 @@ +// Reels track their source (reelAnchor.mjs, reelHistory.mjs; lane/reel-bench): +// a beat's anchor, its classification against the take the reel plays now, the +// reel's line, the clamp; the writer stamping anchors and keeping the history. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { anchorContext, clampPatch, classifyBeat, clipSnapshot, fxFingerprint, reelStatus } from "./reelAnchor.mjs"; +import { diffReel, readReelHistory } from "./reelHistory.mjs"; +import { anchorTrailerBeats, readTrailerBeats, updateTrailerBeat } from "./trailerBeats.mjs"; + +const schedule = (aEnd = 10, extra = 0) => ({ + version: 1, kind: "deck", fps: 30, transition: 0, total: 30 + extra, + segments: [ + { id: "a", type: "clip", start: 0, duration: aEnd, end: aEnd, title: "A", subtitle: "the stream · 1 Oct" }, + { id: "b", type: "clip", start: aEnd, duration: 10, end: aEnd + 10, title: "B" }, + { id: "c", type: "clip", start: aEnd + 10, duration: 10, end: aEnd + 20, title: "C" }, + ], + fx: { keys: ["receipts"], receipts: { clips: [{ segment: "c", in: aEnd + 12, out: aEnd + 15, cards: [{ shot: "x.png", at: aEnd + 12 }] }] } }, +}); +const records = (aEnd = 110) => new Map([ + ["a", { id: "a", start: 100, end: aEnd, segKey: `a-${aEnd}` }], + ["b", { id: "b", start: 200, end: 210, segKey: "b" }], + ["c", { id: "c", start: 300, end: 310, segKey: "c" }], +]); +const build = (o = {}) => ({ schedule: o.schedule ?? schedule(), records: o.records ?? records() }); +const nowOf = (b, take = "t2", extra = {}) => ({ take, build: "2026-11-02T12:00:00Z", masterMtimeMs: 2, snapshot: (id) => clipSnapshot(b, id), ...extra }); +const anchorOf = (b, beat, take = "t1") => { + const s = clipSnapshot(b, beat.id); + return { take, build: "2026-11-01T12:00:00Z", masterMtimeMs: 1, master: { start: 0, end: 1 }, clip: s.clip, seg: s.seg, fx: s.fx, at: "x" }; +}; + +test("fx: the chrome and fx over a segment, timed from its start -- a shift is not a change, an edit is", () => { + const s1 = schedule(10); + const s2 = schedule(12.5); // everything after a moves 2.5 s later + assert.equal(fxFingerprint(s1, "c"), fxFingerprint(s2, "c")); + assert.equal(fxFingerprint(s1, "b"), fxFingerprint(s2, "b")); + const s3 = schedule(10); + s3.fx.receipts.clips[0].cards[0].shot = "y.png"; + assert.notEqual(fxFingerprint(s1, "c"), fxFingerprint(s3, "c")); + const s4 = schedule(10); + s4.segments[1].title = "B, retitled"; + assert.notEqual(fxFingerprint(s1, "b"), fxFingerprint(s4, "b")); + assert.equal(fxFingerprint(s1, "zz"), null); +}); + +test("each beat against the take now: unchanged, rerendered, edges, clipped, look, orphan, unanchored -- and the reel's line", () => { + const was = build(); + const beats = [ + { id: "a", start: 101, end: 105 }, + { id: "b", start: 201, end: 205 }, + { id: "c", start: 301, end: 305 }, + { id: "a", start: 106, end: 109.9 }, + { id: "b", start: 202, end: 203 }, + ].map((b) => ({ ...b, anchor: anchorOf(was, b) })); + beats.push({ id: "c", start: 302, end: 304 }); // never anchored + + // The same master: unchanged. + assert.equal(classifyBeat(beats[0], nowOf(was, "t1", { build: "2026-11-01T12:00:00Z", masterMtimeMs: 1 })).state, "unchanged"); + // Rendered again, a's end moved 110 → 112.5 (the kf3c case): a's beats flagged, nothing else. + const later = build({ schedule: schedule(12.5, 2.5), records: records(112.5) }); + const st = reelStatus(beats, nowOf(later)); + assert.deepEqual(st.rows.map((r) => r.state), ["edges", "rerendered", "rerendered", "edges", "rerendered", "unanchored"]); + assert.deepEqual(st.changed, [1, 4]); + assert.match(st.rows[0].why, /a's end 110 → 112.5 since take t1; the beat still fits/); + assert.deepEqual(st.rows[0].was, { start: 100, end: 110, gaps: [] }); + assert.equal(st.line, "cut against t1; take t2 changes beats 1, 4"); + // a's end pulled IN past a beat: clipped, with the clamp that fits it. + const shorter = build({ schedule: schedule(8), records: records(108) }); + const c = classifyBeat(beats[3], nowOf(shorter)); + assert.equal(c.state, "clipped"); + assert.match(c.why, /a now plays source 100–108 \(was 100–110\)/); + assert.deepEqual(clampPatch(beats[3], clipSnapshot(shorter, "a")), { start: 106, end: 108 }); + // The receipts over c changed: look. + const fx = build(); + fx.schedule.fx.receipts.clips[0].cards[0].shot = "z.png"; + assert.equal(classifyBeat(beats[2], nowOf(fx)).state, "look"); + // b gone from the cut: orphan (anchored or not). + const noB = build(); + noB.schedule = { ...noB.schedule, segments: noB.schedule.segments.filter((s) => s.id !== "b") }; + assert.equal(classifyBeat(beats[1], nowOf(noB)).state, "orphan"); + assert.equal(classifyBeat({ id: "b", start: 201, end: 202 }, nowOf(noB)).state, "orphan"); + // A master beat anchored: rerendered when the master is another. + assert.equal(classifyBeat({ at: 1, dur: 2, anchor: { take: "t1", build: "x", masterMtimeMs: 1 } }, nowOf(was)).state, "rerendered"); +}); + +test("diffReel: per beat old and new, adds, removes, the order, the settings", () => { + const a = { beats: [{ id: "a", start: 1, end: 2 }, { id: "b", start: 3, end: 4 }], settings: { limit: 140 } }; + const b = { beats: [{ id: "a", start: 1.5, end: 2, gaps: [{ from: 1.6, to: 1.8 }] }, { id: "b", start: 3, end: 4, verdict: "confirmed", anchor: { take: "t2" } }], settings: { limit: 90 } }; + const d = diffReel(a, b); + assert.deepEqual(d.changes, [ + { n: 1, id: "a", field: "start", old: 1, new: 1.5 }, + { n: 1, id: "a", field: "gaps", old: null, new: [{ from: 1.6, to: 1.8 }] }, + { n: 2, id: "b", field: "verdict", old: null, new: "confirmed" }, + { n: 2, id: "b", field: "anchor", old: null, new: "t2" }, + ]); + assert.deepEqual(d.settings, { limit: [140, 90] }); + const r = diffReel(a, { beats: [{ id: "b", start: 3, end: 4 }, { id: "c", start: 5, end: 6 }] }); + assert.deepEqual(r.changes.map((x) => x.op), ["remove", "add"]); + assert.deepEqual(diffReel(a, { beats: [a.beats[1], a.beats[0]] }).changes, [{ op: "order", old: ["a", "b"], new: ["b", "a"] }]); +}); + +test("the writer stamps a beat with the take it was edited against, anchors a reel to a take, and keeps the history", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-anchor-")); + try { + const take = path.join(dir, "takes", "t1"); + await mkdir(path.join(take, "out", "sourced", "segments"), { recursive: true }); + await writeFile(path.join(take, "video.manifest.json"), JSON.stringify({ slug: "s", render: { fps: 30 }, timeline: [] })); + await writeFile(path.join(take, "take.json"), JSON.stringify({ id: "t1", builtAt: "2026-11-01T12:00:00Z" })); + await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(schedule())); + for (const [id, rec] of records()) await writeFile(path.join(take, "out", "sourced", "segments", `${id}.cut.json`), JSON.stringify(rec)); + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "promo", "trailer-beats.json"), JSON.stringify([{ id: "a", start: 101, end: 105 }, { id: "c", start: 301, end: 305 }])); + const ctx = await anchorContext(take, { take: "t1", masterMtimeMs: 7, now: () => "2026-11-02T00:00:00Z" }); + await updateTrailerBeat(dir, 0, { end: 106 }, { anchorFor: ctx.anchorFor }); + let doc = await readTrailerBeats(dir); + assert.deepEqual(doc.beats[0].anchor, { + take: "t1", build: "2026-11-01T12:00:00Z", masterMtimeMs: 7, master: { start: 1, end: 6 }, at: "2026-11-02T00:00:00Z", + clip: { start: 100, end: 110, gaps: [] }, seg: "a-110", fx: fxFingerprint(schedule(), "a"), + }); + assert.equal(doc.beats[1].anchor, undefined); + // An edit with no take keeps the anchor it had. + await updateTrailerBeat(dir, 0, { verdict: "confirmed" }); + doc = await readTrailerBeats(dir); + assert.equal(doc.beats[0].anchor.take, "t1"); + await anchorTrailerBeats(dir, ctx.anchorFor, { take: "t1" }); + doc = await readTrailerBeats(dir); + assert.equal(doc.beats[1].anchor.take, "t1"); + const st = reelStatus(doc.beats, { take: "t1", build: ctx.build, masterMtimeMs: 7, snapshot: ctx.snapshot }); + assert.deepEqual(st.rows.map((r) => r.state), ["unchanged", "unchanged"]); + const h = await readReelHistory(dir, path.join("promo", "trailer-beats.json")); + assert.deepEqual(h.map((e) => e.what), ["beat 1: end", "beat 1: verdict", "anchor every beat to take t1"]); + assert.equal(h[0].take, "t1"); + assert.deepEqual(h[0].changes.map((c) => c.field), ["end", "anchor"]); + assert.deepEqual(h[2].changes, [{ n: 2, id: "c", field: "anchor", old: null, new: "t1" }]); + assert.ok((await readFile(path.join(dir, "promo", "trailer-beats.history.json"), "utf8")).includes('"entries"')); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a reel's version for its cut: the seconds, the gaps, the crossfade and the intro -- never a verdict, a label or an anchor", async () => { + const { reelVersion } = await import("./trailerBeats.mjs"); + const v = reelVersion({ beats: [{ id: "a", start: 1, end: 2 }], settings: { xfade: 0.3 } }); + assert.equal(reelVersion({ beats: [{ id: "a", start: 1, end: 2, verdict: "confirmed", label: "x", anchor: { take: "t" } }], settings: { xfade: 0.3, title: "T", limit: 90 } }), v); + assert.notEqual(reelVersion({ beats: [{ id: "a", start: 1, end: 2.5 }], settings: { xfade: 0.3 } }), v); + assert.notEqual(reelVersion({ beats: [{ id: "a", start: 1, end: 2, gaps: [{ from: 1.2, to: 1.5 }] }], settings: { xfade: 0.3 } }), v); + assert.notEqual(reelVersion({ beats: [{ id: "a", start: 1, end: 2 }], settings: { xfade: 0 } }), v); +}); diff --git a/umtool/lib/report/reelBenchData.ts b/umtool/lib/report/reelBenchData.ts @@ -0,0 +1,71 @@ +import path from "node:path"; +import { cuesInWindow, readManifest } from "@/lib/projects/report.mjs"; +import { reelPlayView } from "@/lib/report/reelPlay.mjs"; +import { sourceAt, type FileMap } from "@/lib/report/fileMedia.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +import type { ReelView } from "@/components/projects/reel/reelTypes"; + +// THE REEL'S WALK, as data (lane/reel-bench): what `/projects/<p>/trailer/walk` +// renders (components/projects/reel/ReelBench.tsx) for one beat -- the reel's +// view (lib/report/reelPlay.mjs reelPlayView: each beat mapped onto the take's +// rendered master by the trailer's own plan), and for the beat on screen: the +// master as the bench's media (its project-relative path, its mtime, the +// build record's map onto the clip's source, the source seconds its segment +// plays), and the clip's words over those seconds. + +export type ReelBenchCue = { start: number; end: number; text: string; endsSentence: boolean }; + +export type ReelBenchData = { + view: ReelView; + beat: number; + /** The clip the beat plays, from the take's manifest (or the project's). Null for a master beat. */ + clip: { id: string; video: string; channel: string | null; quote: string | null; note: string | null; title: string | null } | null; + cues: ReelBenchCue[]; + /** The master as the bench plays it; null when there is none or the beat does not map. */ + media: { path: string; v: number | null; map: FileMap; span: { from: number; to: number } } | null; + /** The clips of the take's cut, in order: what an orphaned beat can be re-pointed to. */ + clips: string[]; +}; + +const r3 = (n: number) => Number(n.toFixed(3)); + +export async function reelBenchData(project: ProjectRef, { reel, take, beat }: { reel: string; take: string | null; beat: number }): Promise<ReelBenchData> { + const view = (await reelPlayView(project, { reel, take })) as ReelView; + const row = (view.rows ?? []).find((r) => r.n === beat) ?? null; + const out: ReelBenchData = { view, beat, clip: null, cues: [], media: null, clips: [] }; + if (!row || !view.take?.master || view.noMaster) return out; + const takeManifest = await readManifest(path.dirname(path.dirname(view.take.master))).catch(() => null); + out.clips = ((takeManifest?.timeline ?? []) as Record<string, unknown>[]).filter((e) => e?.type === "clip" && typeof e.id === "string").map((e) => String(e.id)); + const rel = path.relative(project.dir, view.take.master).split(path.sep).join("/"); + if (rel.startsWith("..") || path.isAbsolute(rel)) return out; + const v = view.take.masterMtimeMs ?? null; + if (row.kind === "raw" && row.limits) { + // A master beat: master seconds are its seconds (the identity map), the whole master its room. + out.media = { path: rel, v, map: { segStart: 0, recStart: 0, gaps: [] }, span: { from: 0, to: row.limits.end } }; + return out; + } + if (!row.map || !row.limits || !row.id) return out; + // The source seconds its segment plays: the record's start, to the master second the segment stops being this clip. + const map: FileMap = { segStart: row.map.segStart, recStart: row.map.recStart, gaps: row.map.gaps ?? [] }; + const endSrc = row.map.gaps?.length ? sourceAt(map, row.limits.end - 0.002) + 0.002 : sourceAt(map, row.limits.end); + const span = { from: r3(row.limits.source?.start ?? map.recStart), to: r3(Math.min(row.limits.source?.end ?? endSrc, endSrc)) }; + out.media = { path: rel, v, map, span }; + // The clip, from the take's manifest (what the master was built from), else the project's. + const projectManifest = await readManifest(project.dir).catch(() => null); + const find = (m: Record<string, unknown> | null) => ((m?.timeline ?? []) as Record<string, unknown>[]).find((e) => e?.id === row.id && e?.type === "clip") ?? null; + const manifest = find(takeManifest) ? takeManifest : find(projectManifest) ? projectManifest : null; + const e = find(manifest); + if (e) { + out.clip = { + id: String(e.id), + video: String(e.video ?? ""), + channel: typeof e.channel === "string" ? e.channel : null, + quote: typeof e.quote === "string" ? e.quote : null, + note: typeof e.note === "string" ? e.note : null, + title: typeof e.title === "string" ? e.title : null, + }; + const got = await cuesInWindow(project.dir, row.id, span.from - 30, span.to + 30, { manifest }).catch(() => null); + out.cues = ((got?.cues ?? []) as ReelBenchCue[]).map((c) => ({ start: c.start, end: c.end, text: c.text, endsSentence: !!c.endsSentence })); + } + return out; +} diff --git a/umtool/lib/report/reelHistory.mjs b/umtool/lib/report/reelHistory.mjs @@ -0,0 +1,92 @@ +// A REEL'S HISTORY (lane/reel-bench): every write to a reel's beats file, +// append-only, beside it -- `promo/<name>-beats.history.json`, modelled on +// common/lib/metadataHistory.ts: one entry per write whose beats or settings +// changed, the OLD and NEW value of each field that moved (by beat), capped at +// REEL_HISTORY_CAP, newest last. The undo points (`promo/.<file>.undo.json`) +// put a reel back; this says what changed, when and against which take, +// across sessions -- an agent and a person can audit a reel's edits from it. +// +// diffReel is pure; the writer (trailerBeats.mjs beatsWrite, undo) appends. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const REEL_HISTORY_CAP = 200; +const FIELDS = ["id", "start", "end", "gaps", "at", "dur", "label", "verdict"]; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); +/** A beat as the history keeps it: its seconds, never its anchor whole (only the take it names). */ +const compact = (b) => (isObj(b) ? Object.fromEntries([...FIELDS.filter((k) => b[k] !== undefined).map((k) => [k, b[k]]), ...(isObj(b.anchor) ? [["anchor", b.anchor.take ?? null]] : [])]) : b); +const keyOf = (b) => JSON.stringify([b?.id ?? null, b?.start ?? b?.at ?? null, b?.end ?? b?.dur ?? null]); + +/** + * What changed between two versions of a reel: per beat, each field's old and + * new (`anchor` the take it names), beats added and removed, the order, and the + * settings. Empty `changes` and `settings`: nothing moved. + * + * @param {{ beats: any[], settings?: Record<string, any> }} before + * @param {{ beats: any[], settings?: Record<string, any> }} after + */ +export function diffReel(before, after) { + const a = before.beats ?? []; + const b = after.beats ?? []; + /** @type {any[]} */ + const changes = []; + if (a.length === b.length && a.every((x, i) => (x?.id ?? null) === (b[i]?.id ?? null))) { + b.forEach((nb, i) => { + const ob = a[i]; + for (const k of FIELDS) if (!same(ob?.[k], nb?.[k])) changes.push({ n: i + 1, id: nb?.id ?? null, field: k, old: ob?.[k] ?? null, new: nb?.[k] ?? null }); + const ot = isObj(ob?.anchor) ? ob.anchor.take ?? null : null; + const nt = isObj(nb?.anchor) ? nb.anchor.take ?? null : null; + if (!same(ob?.anchor, nb?.anchor)) changes.push({ n: i + 1, id: nb?.id ?? null, field: "anchor", old: ot, new: nt }); + }); + } else { + const before = new Map(a.map((x, i) => [keyOf(x), i])); + const afterKeys = new Set(b.map(keyOf)); + a.forEach((x, i) => { + if (!afterKeys.has(keyOf(x))) changes.push({ op: "remove", n: i + 1, beat: compact(x) }); + }); + b.forEach((x, i) => { + if (!before.has(keyOf(x))) changes.push({ op: "add", n: i + 1, beat: compact(x) }); + }); + const kept = b.filter((x) => before.has(keyOf(x))).map(keyOf); + const was = a.filter((x) => afterKeys.has(keyOf(x))).map(keyOf); + if (!same(kept, was)) changes.push({ op: "order", old: a.map((x) => x?.id ?? null), new: b.map((x) => x?.id ?? null) }); + } + /** @type {Record<string, [any, any]>} */ + const settings = {}; + const sa = before.settings ?? {}; + const sb = after.settings ?? {}; + for (const k of new Set([...Object.keys(sa), ...Object.keys(sb)])) if (!same(sa[k], sb[k])) settings[k] = [sa[k] ?? null, sb[k] ?? null]; + return { changes, settings }; +} + +export const historyFileOf = (dir, rel) => path.join(dir, path.dirname(rel), `${path.basename(rel, ".json")}.history.json`); + +/** A reel's history, oldest first; [] when it has none (or it does not read). */ +export async function readReelHistory(dir, rel) { + try { + const j = JSON.parse(await readFile(historyFileOf(dir, rel), "utf8")); + return Array.isArray(j?.entries) ? j.entries : []; + } catch { + return []; + } +} + +/** + * Append one entry (when something moved): `{ at, what, take?, changes, settings }`. + * @param {string} dir + * @param {string} rel the reel's file, relative to the project + * @param {{ what: string, take?: string | null, before: { beats: any[], settings?: any }, after: { beats: any[], settings?: any }, at?: string }} e + */ +export async function appendReelHistory(dir, rel, { what, take = null, before, after, at = new Date().toISOString() }) { + const d = diffReel(before, after); + if (!d.changes.length && !Object.keys(d.settings).length) return null; + const entry = { at, what, ...(take ? { take } : {}), changes: d.changes, ...(Object.keys(d.settings).length ? { settings: d.settings } : {}) }; + const file = historyFileOf(dir, rel); + const entries = [...(await readReelHistory(dir, rel)), entry].slice(-REEL_HISTORY_CAP); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify({ file: rel, entries }, null, 1) + "\n", "utf8"); + await rename(tmp, file); + return entry; +} diff --git a/umtool/lib/report/reelPlay.mjs b/umtool/lib/report/reelPlay.mjs @@ -33,9 +33,10 @@ import { trailerOutPath, trailerRecordPath, } from "umtool-report-to-video/trailer"; +import { anchorContext, reelStatus } from "./reelAnchor.mjs"; import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; import { listTakes, takesDirOf } from "./takes.mjs"; -import { DEFAULT_REEL, TRAILER_LIMIT_DEFAULT, readTrailerBeats, reelFileOf } from "./trailerBeats.mjs"; +import { DEFAULT_REEL, TRAILER_LIMIT_DEFAULT, readTrailerBeats, reelFileOf, reelVersion } from "./trailerBeats.mjs"; const r3 = (n) => Number(Number(n).toFixed(3)); const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then(JSON.parse, () => null); @@ -86,7 +87,7 @@ export async function takeMasters(projectDir) { * @param {Awaited<ReturnType<typeof takeMasters>>} masters * @param {string} reel */ -export async function reelCuts(masters, reel = DEFAULT_REEL) { +export async function reelCuts(masters, reel = DEFAULT_REEL, { version = null } = {}) { const out = []; for (const t of masters) { if (!t.slug) continue; @@ -105,8 +106,11 @@ export async function reelCuts(masters, reel = DEFAULT_REEL) { seconds: Number.isFinite(rec?.seconds) ? rec.seconds : null, encodeSeconds: Number.isFinite(rec?.encodeSeconds) ? rec.encodeSeconds : null, notes: Array.isArray(rec?.notes) ? rec.notes.length : 0, - // Cut before the master there now was written: the take was rendered again since. - stale: t.masterMtimeMs !== null && st.mtimeMs < t.masterMtimeMs, + // Cut from another master than the one there now (its record names the master's mtime; + // an older record, before that: cut before the master was written): rendered again since. + stale: t.masterMtimeMs !== null && (Number.isFinite(rec?.source?.masterMtimeMs) ? rec.source.masterMtimeMs !== t.masterMtimeMs : st.mtimeMs < t.masterMtimeMs), + // The reel edited since the cut (its record names the reel's version, trailerBeats.mjs reelVersion). + reelChanged: !!(version && typeof rec?.reel?.version === "string" && rec.reel.version !== version), }); } out.sort((a, b) => String(b.builtAt).localeCompare(String(a.builtAt))); @@ -221,10 +225,17 @@ export function reelPlan(build, rawBeats, { intro = false, xfade = TRAILER_XFADE id: isClip ? String(raw.id) : null, label: typeof raw.label === "string" ? raw.label : null, verdict: raw.verdict === "confirmed" || raw.verdict === "note" ? raw.verdict : null, - beat: isClip ? { start: raw.start, end: raw.end } : { at: raw.at, dur: raw.dur }, + beat: isClip ? { start: raw.start, end: raw.end, ...(Array.isArray(raw.gaps) && raw.gaps.length ? { gaps: raw.gaps } : {}) } : { at: raw.at, dur: raw.dur }, problem: r.problem, // Where it plays: the plan's piece (master span after the crossfades are kept out; where it lands in the reel). - piece: p ? { at: p.at, master: p.master, frames: p.frames, seamless: p.seamless === true, moved: p.moved ?? null, source: p.source ?? null } : null, + piece: p + ? { + at: p.at, master: p.master, frames: p.frames, seamless: p.seamless === true, moved: p.moved ?? null, source: p.source ?? null, + // A gapped beat: the master spans it leaves out, and what it plays. + cuts: (p.cuts ?? []).map((c) => ({ from: c.from, to: c.to })), + seconds: p.seconds ?? p.master.duration, + } + : null, asked, limits, map, @@ -261,7 +272,7 @@ export async function reelPlayView(project, { reel = DEFAULT_REEL, take = null } const doc = await readTrailerBeats(project.dir, { reel }); const settings = doc.settings ?? {}; const masters = await takeMasters(project.dir); - const cuts = await reelCuts(masters, reel); + const cuts = await reelCuts(masters, reel, { version: doc.exists ? reelVersion(doc) : null }); const chosen = pickReelTake({ asked: take, pinned: settings.take ?? null, cuts, masters }); const base = { project: project.id, @@ -301,7 +312,15 @@ export async function reelPlayView(project, { reel = DEFAULT_REEL, take = null } return { ...base, take: { id: chosen.id, why: chosen.why, label: m.label }, noMaster: { why: e instanceof TrailerError || e instanceof Error ? e.message : String(e), take: chosen.id } }; } const plan = reelPlan(build, doc.beats, { intro: settings.intro === true, xfade: base.xfade }); + // Each beat against this take (reelAnchor.mjs): what it was cut against, and what changed since. + const ctx = await anchorContext(m.dir, { take: chosen.id, masterMtimeMs: m.masterMtimeMs, build }).catch(() => null); + const status = ctx ? reelStatus(doc.beats, ctx) : null; + if (status) for (const r of plan.rows) { + const st = status.rows[r.n - 1]; + r.status = st ? { state: st.state, why: st.why, ...(st.was ? { was: st.was } : {}), ...(st.now ? { now: st.now } : {}) } : null; + } return { + status: status ? { take: status.take, against: status.against, changed: status.changed, counts: status.counts, line: status.line } : null, ...base, take: { id: chosen.id, @@ -317,6 +336,20 @@ export async function reelPlayView(project, { reel = DEFAULT_REEL, take = null } }; } +/** + * A take's anchoring context (reelAnchor.mjs anchorContext), by its id: the + * anchor a beat written against it gets, and what it says of each clip now. + * Null when the take has no finished master. + * + * @param {string} projectDir + * @param {string} take + */ +export async function anchorContextOf(projectDir, take) { + const m = (await takeMasters(projectDir)).find((x) => x.id === take); + if (!m?.built) return null; + return anchorContext(m.dir, { take, masterMtimeMs: m.masterMtimeMs }); +} + /** A reel's cut may take this long on the runner: one ffmpeg pass over spans of a master, in the heavy slot (it may wait there). */ export const REEL_CUT_TIMEOUT_MS = 45 * 60 * 1000; diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -33,11 +33,13 @@ // `undoTrailerBeats` puts back. // // Plain ESM: the CLI runs it under bare node. +import { createHash } from "node:crypto"; import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { gappedLength, gapsOf } from "umtool-report-to-video/gaps"; -import { TRAILER_XFADE_DEFAULT, TrailerError, parseBeats } from "umtool-report-to-video/trailer"; +import { TRAILER_XFADE_DEFAULT, TrailerError, beatGaps, parseBeats } from "umtool-report-to-video/trailer"; import { indentOf } from "./patchMarkers.mjs"; +import { appendReelHistory } from "./reelHistory.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; @@ -194,7 +196,7 @@ function withBeatsLock(fn) { * settings)` (which throws to refuse), every beat checked by the trailer's own * parseBeats, a `.bak` of the file as it was, then tmp + rename. */ -async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an edit" } = {}) { +async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an edit", take = null } = {}) { return withBeatsLock(async () => { const current = await beatsToken(dir, reel); if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); @@ -220,6 +222,8 @@ async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); await rename(tmp, file); + // The history (reelHistory.mjs): what moved, old and new, by beat. + await appendReelHistory(dir, reelFileOf(reel), { what, take, before: { beats: read.beats, settings: read.settings }, after: { beats, settings } }).catch(() => null); return { ...result, beats, settings, token: await beatsToken(dir, reel) }; }); } @@ -239,6 +243,7 @@ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL const last = points.pop(); if (!last) throw new Error(`nothing to undo on the reel ${reel}`); const file = beatsFile(dir, reel); + const before = await readTrailerBeats(dir, { reel }).catch(() => null); if (last.text === null) await rm(file, { force: true }); else { const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; @@ -246,6 +251,8 @@ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL await rename(tmp, file); } await writeUndo(dir, reel, points); + const after = await readTrailerBeats(dir, { reel }).catch(() => null); + if (before && after) await appendReelHistory(dir, reelFileOf(reel), { what: `undo: ${last.what}`, before, after }).catch(() => null); return { undone: last.what, at: last.at, left: points.length, token: await beatsToken(dir, reel) }; }); } @@ -282,14 +289,57 @@ export async function createReel(dir, name, { from = null, title = null } = {}) }, { reel: name, what: from ? `new reel ${name}, from ${from}` : `new reel ${name}` }); } +/** A beat's anchor (lib/report/reelAnchor.mjs: what it was cut against), carried as written. */ +const anchorOf = (b) => (isObj(b.anchor) ? { anchor: b.anchor } : {}); + /** A beat as a person writes it: `{ id, start, end, label? }` or `{ at, dur, label? }`, rounded to 2 dp. */ function cleanBeat(b) { if (!isObj(b)) throw new Error("a beat is { id, start, end } or { at, dur }"); const label = typeof b.label === "string" && b.label.trim() ? { label: b.label.trim().slice(0, 120) } : {}; if (b.verdict !== undefined && b.verdict !== null && !BEAT_VERDICTS.includes(b.verdict)) throw new Error(`a beat's verdict is one of ${BEAT_VERDICTS.join(", ")}`); const verdict = BEAT_VERDICTS.includes(b.verdict) ? { verdict: b.verdict } : {}; - if (b.id !== undefined) return { id: String(b.id), start: r2(b.start), end: r2(b.end), ...label, ...verdict }; - return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict }; + if (b.id !== undefined) { + const start = r2(b.start); + const end = r2(b.end); + // A beat's gaps (trailer.mjs beatGaps: a clip's gap rule): refused here by the same sentences. + let gaps; + try { + gaps = beatGaps({ start, end, gaps: b.gaps }, `beat ${b.id}`); + } catch (e) { + throw new Error(e instanceof Error ? e.message : String(e)); + } + return { id: String(b.id), start, end, ...(gaps.length ? { gaps } : {}), ...label, ...verdict, ...anchorOf(b) }; + } + return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict, ...anchorOf(b) }; +} + +/** @typedef {((beat: Record<string, any>) => Record<string, any> | null) | null} AnchorFor */ + +/** The take an anchorFor writes against (anchorContext tags it), for the history. */ +const anchorTake = (anchorFor) => (anchorFor && typeof anchorFor.take === "string" ? anchorFor.take : null); + +/** A beat with the anchor of the take it was written against (reelAnchor.mjs anchorContext); none when it does not map there. */ +function stamp(b, anchorFor) { + if (!anchorFor) return b; + const { anchor: _old, ...rest } = b; + const a = anchorFor(rest); + return a ? { ...rest, anchor: a } : rest; +} + +/** + * Anchor beats to a take (reelAnchor.mjs anchorContext's `anchorFor`): all of + * them, or the 0-based `only`. A beat that does not map onto the take loses + * its anchor (it is said on load). + * @param {string} dir + * @param {NonNullable<AnchorFor>} anchorFor + * @param {BeatsWriteOpts & { only?: number[] | null, take?: string }} [opts] + */ +export async function anchorTrailerBeats(dir, anchorFor, { token = null, reel = DEFAULT_REEL, only = null, take = "" } = {}) { + return beatsWrite(dir, token, (beats) => { + const which = only ?? beats.map((_, k) => k); + for (const k of which) beats[indexIn(beats, k)] = stamp(beats[k], anchorFor); + return { anchored: which.length }; + }, { reel, what: `anchor ${only ? `beat${only.length === 1 ? "" : "s"} ${only.map((k) => k + 1).join(", ")}` : "every beat"}${take ? ` to take ${take}` : ""}`, take: take || null }); } const indexIn = (beats, i, what = "beat") => { @@ -302,11 +352,11 @@ const indexIn = (beats, i, what = "beat") => { * Add a beat at index `at` (default: where the cut's order puts it, else the end). * @param {string} dir * @param {Record<string, unknown>} beat - * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null, reel?: string }} [opts] + * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null, reel?: string, anchorFor?: AnchorFor }} [opts] */ -export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null, reel = DEFAULT_REEL } = {}) { +export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null, reel = DEFAULT_REEL, anchorFor = null } = {}) { return beatsWrite(dir, token, (beats) => { - const b = cleanBeat(beat); + const b = stamp(cleanBeat(beat), anchorFor); let i = beats.length; if (at !== null && at !== undefined) { i = Number(at); @@ -322,7 +372,7 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif } beats.splice(i, 0, b); return { index: i, beat: b }; - }, { reel, what: `add ${beat?.id ?? "a master beat"}` }); + }, { reel, what: `add ${beat?.id ?? "a master beat"}`, take: anchorTake(anchorFor) }); } /** @@ -330,22 +380,34 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif * @param {string} dir * @param {number} i * @param {Record<string, unknown>} patch - * @param {BeatsWriteOpts} [opts] + * @param {BeatsWriteOpts & { anchorFor?: AnchorFor }} [opts] `anchorFor`: the take the edit was made against (its anchor is written) */ -export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL } = {}) { +export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL, anchorFor = null } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); - if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, label?, verdict? }"); + if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, gaps?, id?, label?, verdict? }"); const b = { ...beats[n] }; for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k]; + // Re-pointed to another clip of the cut (a beat whose clip is gone): its seconds go with it. + if (patch.id !== undefined) { + if (b.id === undefined) throw new Error("a master beat has no clip to re-point"); + if (typeof patch.id !== "string" || !patch.id) throw new Error("id is a clip id"); + b.id = patch.id; + } + // The beat's gaps, the whole list ([] or null: none). A clip beat only. + if (patch.gaps !== undefined) { + if (b.id === undefined) throw new Error("only a clip beat has source seconds to take out; a master beat is { at, dur }"); + if (patch.gaps === null || (Array.isArray(patch.gaps) && !patch.gaps.length)) delete b.gaps; + else b.gaps = patch.gaps; + } for (const k of ["label", "verdict"]) { if (patch[k] === undefined) continue; if (patch[k] === null || patch[k] === "") delete b[k]; else b[k] = patch[k]; } - beats[n] = cleanBeat(b); + beats[n] = stamp(cleanBeat(b), anchorFor); return { index: n, beat: beats[n] }; - }, { reel, what: `beat ${Number(i) + 1}: ${Object.keys(isObj(patch) ? patch : {}).join(", ") || "set"}` }); + }, { reel, what: `beat ${Number(i) + 1}: ${Object.keys(isObj(patch) ? patch : {}).join(", ") || "set"}`, take: anchorTake(anchorFor) }); } /** @@ -448,6 +510,31 @@ export async function setTrailerSettings(dir, patch, { token = null, reel = DEFA }, { reel, what: `settings: ${Object.keys(isObj(patch) ? patch : {}).join(", ")}` }); } +/** + * A reel's VERSION as its cut sees it: a fingerprint of what the cut reads + * (each beat's clip and seconds and gaps, the crossfade, the intro) -- not a + * verdict, a label or an anchor, which change nothing cut. Named in a cut's + * record, so the reel's Play can say the cut is older than the reel. + * + * @param {{ beats: any[], settings?: Record<string, any> }} doc + */ +export function reelVersion(doc) { + const beats = (doc?.beats ?? []).map((b) => (isObj(b) ? [b.id ?? null, b.start ?? b.at ?? null, b.end ?? b.dur ?? null, b.gaps ?? null] : b)); + const s = doc?.settings ?? {}; + return createHash("sha256").update(JSON.stringify({ beats, xfade: s.xfade ?? null, intro: s.intro ?? null })).digest("hex").slice(0, 16); +} + +/** Spans merged where they touch or overlap, sorted. */ +function unionSpans(list) { + const out = []; + for (const g of [...list].filter((x) => isObj(x) && Number.isFinite(x.from) && Number.isFinite(x.to)).sort((x, y) => x.from - y.from)) { + const last = out[out.length - 1]; + if (last && g.from <= last.to) last.to = Math.max(last.to, g.to); + else out.push({ from: g.from, to: g.to }); + } + return out; +} + /** Clip id → its place among the cut's clips. */ function cutOrder(manifest) { const order = new Map(); @@ -511,7 +598,8 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT if (raw.end > hi + EPS) problems.push(`ends ${(raw.end - hi).toFixed(2)} s after ${raw.id}'s window (${lo}–${hi})`); const a = Math.max(raw.start, lo); const b = Math.min(raw.end, hi); - seconds = b > a ? gappedLength(a, b, gapsOf(e)) : 0; + // What plays: the clip's gaps (its render left them out) and the beat's own, as one list. + seconds = b > a ? gappedLength(a, b, unionSpans([...gapsOf(e), ...(Array.isArray(raw.gaps) ? raw.gaps : [])])) : 0; const k = order.get(raw.id); if (k < lastKey) inOrder = false; lastKey = Math.max(lastKey, k); @@ -528,7 +616,7 @@ export function trailerView(manifest, doc, { introSeconds = null, reel = DEFAULT return { n: i + 1, kind, - ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end } : { at: raw?.at, dur: raw?.dur }), + ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end, ...(Array.isArray(raw.gaps) && raw.gaps.length ? { gaps: raw.gaps } : {}) } : { at: raw?.at, dur: raw?.dur }), label: typeof raw?.label === "string" ? raw.label : null, verdict: BEAT_VERDICTS.includes(raw?.verdict) ? raw.verdict : null, seconds: r2(seconds), diff --git a/umtool/lib/report/trailerBeats.test.mjs b/umtool/lib/report/trailerBeats.test.mjs @@ -220,3 +220,32 @@ test("every write is an undo point: undo puts the file back as it was, one write await rm(dir, { recursive: true, force: true }); } }); + +test("a beat's gaps (lane/reel-bench): written as a list through the one writer, refused by the clip gap rule, counted out of its length; undo puts them back", async () => { + const dir = await project([{ id: "a", start: 11, end: 19 }]); + try { + let tok = await beatsToken(dir); + const r = await updateTrailerBeat(dir, 0, { gaps: [{ from: 15.004, to: 17 }, { from: 12, to: 13 }] }, { token: tok }); + assert.deepEqual(r.beat.gaps, [{ from: 12, to: 13 }, { from: 15, to: 17 }]); + assert.deepEqual(JSON.parse(await fileOf(dir))[0], { id: "a", start: 11, end: 19, gaps: [{ from: 12, to: 13 }, { from: 15, to: 17 }] }); + // 8 s of beat, 3 s cut: the view counts 5; and the clip's own gaps with them on another beat. + const v = trailerView(manifest(), await readTrailerBeats(dir)); + assert.equal(v.rows[0].seconds, 5); + assert.deepEqual(v.rows[0].gaps, [{ from: 12, to: 13 }, { from: 15, to: 17 }]); + const both = trailerView(manifest(), { beats: [{ id: "b", start: 30, end: 50, gaps: [{ from: 39, to: 44 }] }] }); + // b's own gap 35–40 and the beat's 39–44: 9 s out of 20. + assert.equal(both.rows[0].seconds, 11); + tok = await beatsToken(dir); + await assert.rejects(updateTrailerBeat(dir, 0, { gaps: [{ from: 11.2, to: 12 }] }, { token: tok }), /keep at least 0.5 s/); + await assert.rejects(updateTrailerBeat(dir, 0, { gaps: [{ from: 14, to: 14.1 }] }, { token: tok }), /under 0.2 s/); + // Moving the edges inside a gap is refused too: the edges and the gaps are one rule. + await assert.rejects(updateTrailerBeat(dir, 0, { end: 17.2 }, { token: tok }), /before the beat's end/); + await updateTrailerBeat(dir, 0, { gaps: [] }, { token: tok }); + assert.deepEqual(JSON.parse(await fileOf(dir))[0], { id: "a", start: 11, end: 19 }); + const { undoTrailerBeats } = await import("./trailerBeats.mjs"); + await undoTrailerBeats(dir); + assert.equal(JSON.parse(await fileOf(dir))[0].gaps.length, 2); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerBeatsCli.mjs b/umtool/lib/report/trailerBeatsCli.mjs @@ -8,7 +8,11 @@ // Beats are numbered from 1, as `umtool trailer`'s refusals number them. // // Plain ESM: the CLI runs under bare node. +import { editGaps } from "umtool-report-to-video/gaps"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { clampPatch } from "./reelAnchor.mjs"; +import { readReelHistory } from "./reelHistory.mjs"; +import { anchorContextOf, reelPlayView } from "./reelPlay.mjs"; import { readManifest } from "../projects/report.mjs"; import { BEAT_VERDICTS, @@ -16,6 +20,7 @@ import { DEFAULT_REEL, TRAILER_LIMITS, addTrailerBeat, + anchorTrailerBeats, beatsToken, clockOf, createReel, @@ -42,23 +47,32 @@ export const TRAILER_BEATS_USAGE = [ " a clip beat (default: the clip's whole cut), in the cut's order unless --at N", " umtool trailer-beats <project> add-raw <at> <dur> [--at N] [--label L] master seconds", " umtool trailer-beats <project> set <n> <from>-<to> [--label L] beat n's source seconds", + " umtool trailer-beats <project> gap <n> add <from>-<to> | remove <second> | clear", + " seconds cut out of beat n's middle (a clip's gap rule): it plays as one beat of jump cuts", " umtool trailer-beats <project> remove <n> | move <n> --to <m> | order (the cut's order)", ` umtool trailer-beats <project> limit <seconds|m:ss|${TRAILER_LIMITS.map((l) => l.id).join("|")}> | xfade <s> | intro on|off`, " umtool trailer-beats <project> candidates [--add] the walk's ★ clips not yet beats (--add: all of them)", ` umtool trailer-beats <project> verdict <n> ${BEAT_VERDICTS.join("|")}|clear the walk's word on beat n`, " umtool trailer-beats <project> title <text>|none | take <take>|none the reel's name, the take it is cut from", " umtool trailer-beats <project> undo the reel as it was before its last write (each write is an undo point)", + " umtool trailer-beats <project> status [--take <t>] [--json] each beat against the take the reel plays now:", + " unchanged, rerendered, edges, look, clipped, orphan, unanchored (what it was cut against)", + " umtool trailer-beats <project> anchor [<n>…] --take <t> anchor beats (all, or n…) to that take's master", + " umtool trailer-beats <project> clamp <n> [--take <t>] | repoint <n> <clip> [--take <t>]", + " a clipped beat pulled inside its clip's new limits; an orphan's seconds on another clip", + " umtool trailer-beats <project> history [--json] every write to the reel: what moved, old and new", " umtool trailer-beats <project> reels [--json] the project's reels", " umtool trailer-beats <project> new-reel <name> [--from <reel>] [--title T] a new reel (empty, or a copy)", "", "--reel <name> on any of these: that reel (promo/<name>-beats.json); the default is `trailer`, promo/trailer-beats.json.", + "--take <t> on an edit: the take it is made against -- the beat is anchored to that take's master.", "`umtool trailer <p> --reel <name> [--take <t>]` cuts it.", ].join("\n"); class CliError extends Error {} function parse(args) { - const valued = new Set(["--at", "--to", "--label", "--reel", "--from", "--title"]); + const valued = new Set(["--at", "--to", "--label", "--reel", "--from", "--title", "--take"]); /** @type {Record<string, string>} */ const flags = {}; const positional = []; @@ -101,8 +115,9 @@ export function viewLines(v) { const lines = []; for (const r of v.rows) { const what = r.kind === "clip" ? `${r.id.padEnd(8)} ${String(r.start).padStart(9)}–${String(r.end).padEnd(9)}` : `(master) at ${r.at} for ${r.dur}`.padEnd(29); + const gaps = r.gaps?.length ? ` gaps ${r.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : ""; const flag = r.problems.length ? ` ! ${r.problems.join("; ")}` : ""; - lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${flag}`); + lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${gaps}${flag}`); } lines.push( `${v.rows.length} beat(s): ${clockOf(v.total)} of ${clockOf(v.limit)}${v.over ? ` — OVER by ${(v.total - v.limit).toFixed(1)} s` : ` (${v.remaining.toFixed(1)} s to spare)`}` + @@ -136,6 +151,11 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const label = p.has("--label") ? p.flags["--label"] : undefined; const at = p.has("--at") ? beatNo(p.flags["--at"], "--at") : null; let did = null; + // An edit made against a take (--take): the beats written are anchored to it (reelAnchor.mjs). + const anchorTake = p.has("--take") ? p.flags["--take"] : null; + const ctx = anchorTake && verb !== "status" ? await anchorContextOf(project.dir, anchorTake) : null; + if (anchorTake && verb !== "status" && !ctx) throw new CliError(`--take ${anchorTake}: no finished master to anchor to`); + const anchorFor = ctx?.anchorFor ?? null; switch (verb) { case "ls": break; @@ -145,7 +165,7 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const e = (manifest.timeline ?? []).find((x) => x?.id === id && x.type === "clip"); if (!e) throw new CliError(`no clip ${id} in the cut`); const span = rest[1] ? spanOf(rest[1]) : { start: e.cutStart ?? e.start, end: e.cutEnd ?? e.end }; - const res = await addTrailerBeat(project.dir, { id, ...span, ...(label ? { label } : {}) }, { token, at, manifest, reel }); + const res = await addTrailerBeat(project.dir, { id, ...span, ...(label ? { label } : {}) }, { token, at, manifest, reel, anchorFor }); did = `added beat ${res.index + 1}: ${id} ${res.beat.start}–${res.beat.end}`; break; } @@ -161,8 +181,30 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) const i = beatNo(rest[0]); const patch = { ...(rest[1] ? spanOf(rest[1]) : {}), ...(label !== undefined ? { label } : {}) }; if (!Object.keys(patch).length) throw new CliError("set <n> <from>-<to> [--label L]"); - const res = await updateTrailerBeat(project.dir, i, patch, { token, reel }); - did = `beat ${i + 1}: ${JSON.stringify(res.beat)}`; + const res = await updateTrailerBeat(project.dir, i, patch, { token, reel, anchorFor }); + const { anchor: _a, ...shown } = res.beat; + did = `beat ${i + 1}: ${JSON.stringify(shown)}`; + break; + } + case "gap": { + const i = beatNo(rest[0]); + const op = rest[1]; + const doc = await readTrailerBeats(project.dir, { reel }); + const b = doc.beats[i]; + if (!b) throw new CliError(`no beat ${i + 1}`); + if (b.id === undefined) throw new CliError(`beat ${i + 1} is master seconds ({ at, dur }): only a clip beat has gaps`); + let next; + if (op === "add") { + const sp = spanOf(rest[2]); + next = editGaps(b.gaps ?? [], { add: { from: sp.start, to: sp.end } }); + } else if (op === "remove") { + const t = Number(rest[2]); + if (!Number.isFinite(t)) throw new CliError("gap <n> remove <second>: a source second inside (or at) the gap"); + next = editGaps(b.gaps ?? [], { remove: t }); + } else if (op === "clear") next = []; + else throw new CliError("gap <n> add <from>-<to> | remove <second> | clear"); + const res = await updateTrailerBeat(project.dir, i, { gaps: next }, { token, reel, anchorFor }); + did = `beat ${i + 1}: ${(res.beat.gaps ?? []).length ? `gaps ${res.beat.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps"}`; break; } case "remove": { @@ -219,6 +261,55 @@ export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) did = `beat ${i + 1}: ${v === "clear" ? "verdict cleared" : v}`; break; } + case "status": { + const v = await reelPlayView(project, { reel, take: anchorTake }); + if (!v.status) throw new CliError(v.noMaster?.why ?? "no take to classify the beats against"); + const rows = (v.rows ?? []).map((r) => ({ n: r.n, id: r.id, beat: r.beat, state: r.status?.state ?? null, why: r.status?.why ?? null, was: r.status?.was ?? null, now: r.status?.now ?? null })); + if (p.has("--json")) out(JSON.stringify({ project: project.id, reel, take: v.take?.id ?? null, ...v.status, rows }, null, 2)); + else { + out(`reel ${reel} on take ${v.take?.id} (${v.take?.why}): ${v.status.line}`); + for (const r of rows) out(`${String(r.n).padStart(3)} ${(r.id ?? "(master)").padEnd(10)} ${(r.state ?? "?").padEnd(11)} ${r.why ?? ""}`); + } + return 0; + } + case "anchor": { + if (!anchorFor) throw new CliError("anchor [<n>…] --take <t>: the take whose master the beats are anchored to"); + const only = rest.length ? rest.map((x) => beatNo(x)) : null; + await anchorTrailerBeats(project.dir, anchorFor, { token, reel, only, take: anchorTake ?? "" }); + did = `anchored ${only ? `beat${only.length === 1 ? "" : "s"} ${only.map((k) => k + 1).join(", ")}` : "every beat"} to take ${anchorTake}`; + break; + } + case "clamp": + case "repoint": { + const i = beatNo(rest[0]); + const v = await reelPlayView(project, { reel, take: anchorTake }); + const row = (v.rows ?? [])[i]; + const doc = await readTrailerBeats(project.dir, { reel }); + const b = doc.beats[i]; + if (!row || !b) throw new CliError(`no beat ${i + 1}`); + const useFor = anchorFor ?? (v.take ? (await anchorContextOf(project.dir, v.take.id))?.anchorFor ?? null : null); + if (verb === "clamp") { + if (row.status?.state !== "clipped" || !row.status.now) throw new CliError(`beat ${i + 1} is ${row.status?.state ?? "not classified"}: only a clipped beat is clamped`); + const patch = clampPatch(b, { clip: row.status.now }); + if (!patch) throw new CliError(`beat ${i + 1}: nothing of it is left inside ${b.id}'s new limits — re-place it (set) or remove it`); + await updateTrailerBeat(project.dir, i, patch, { token, reel, anchorFor: useFor }); + did = `beat ${i + 1}: clamped to ${patch.start}–${patch.end}`; + } else { + const id = rest[1]; + if (!id) throw new CliError("repoint <n> <clip>"); + if (!(manifest.timeline ?? []).some((x) => x?.id === id && x.type === "clip")) throw new CliError(`no clip ${id} in the cut`); + await updateTrailerBeat(project.dir, i, { id }, { token, reel, anchorFor: useFor }); + did = `beat ${i + 1}: re-pointed to ${id}`; + } + break; + } + case "history": { + const h = await readReelHistory(project.dir, reelFileOf(reel)); + if (p.has("--json")) out(JSON.stringify({ project: project.id, reel, entries: h }, null, 2)); + else if (!h.length) out(`no history for the reel ${reel} yet (it starts with the next write)`); + else for (const e of h) out(`${e.at} ${e.what}${e.take ? ` (take ${e.take})` : ""}${e.changes?.length ? `: ${e.changes.map((c) => (c.op ? `${c.op}${c.n ? ` ${c.n}` : ""}` : `${c.n}.${c.field} ${JSON.stringify(c.old)} → ${JSON.stringify(c.new)}`)).join("; ")}` : ""}`); + return 0; + } case "undo": { const u = await undoTrailerBeats(project.dir, { token, reel }); did = `undone: ${u.undone} (${u.left} undo point${u.left === 1 ? "" : "s"} left)`; diff --git a/umtool/lib/report/trailerBeatsCli.test.mjs b/umtool/lib/report/trailerBeatsCli.test.mjs @@ -0,0 +1,89 @@ +// `umtool trailer-beats ... gap` (lane/reel-bench): a beat's gaps from a +// terminal, through the beats' one writer -- the page's twin. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { trailerBeatsCommand } from "./trailerBeatsCli.mjs"; + +async function root() { + const r = await mkdtemp(path.join(tmpdir(), "umtool-tbcli-")); + const dir = path.join(r, "p1"); + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "p1", title: "P1", timeline: [{ type: "clip", id: "a", video: "v", start: 10, end: 30 }] })); + await writeFile(path.join(dir, "promo", "trailer-beats.json"), JSON.stringify([{ id: "a", start: 11, end: 29 }, { at: 3, dur: 2 }])); + return { r, dir }; +} + +test("gap <n> add / remove / clear: written through the writer, said, refused by name", async () => { + const { r, dir } = await root(); + const out = []; + const err = []; + const run = (...a) => trailerBeatsCommand(["p1", ...a], { root: r, out: (s) => out.push(s), err: (s) => err.push(s) }); + try { + assert.equal(await run("gap", "1", "add", "14-17"), 0); + assert.match(out.join("\n"), /beat 1: gaps 14–17/); + assert.match(out.join("\n"), /gaps 14–17/); + assert.equal(await run("gap", "1", "add", "20-22"), 0); + const beats = () => readFile(path.join(dir, "promo", "trailer-beats.json"), "utf8").then(JSON.parse); + assert.deepEqual((await beats())[0].gaps, [{ from: 14, to: 17 }, { from: 20, to: 22 }]); + assert.equal(await run("gap", "1", "remove", "15"), 0); + assert.deepEqual((await beats())[0].gaps, [{ from: 20, to: 22 }]); + assert.equal(await run("gap", "1", "clear"), 0); + assert.equal((await beats())[0].gaps, undefined); + assert.equal(await run("gap", "1", "add", "11.1-12"), 1); + assert.match(err.join("\n"), /keep at least 0.5 s/); + assert.equal(await run("gap", "2", "add", "3.5-4"), 2); + assert.match(err.join("\n"), /only a clip beat has gaps/); + } finally { + await rm(r, { recursive: true, force: true }); + } +}); + +test("status / anchor / clamp: a reel anchored to one take, read against another that moved a clip's end; the clipped beat clamped", async () => { + const r = await mkdtemp(path.join(tmpdir(), "umtool-tbcli-st-")); + const dir = path.join(r, "p1"); + const takeOf = async (id, aEnd, builtAt) => { + const t = path.join(dir, "takes", id); + await mkdir(path.join(t, "out", "sourced", "segments"), { recursive: true }); + await writeFile(path.join(t, "video.manifest.json"), JSON.stringify({ slug: "p1", render: { fps: 30 }, timeline: [] })); + await writeFile(path.join(t, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "reference", summary: "", changes: [], preview: "preview.mp4", seconds: 10, builtAt, style: null, patch: null, window: "full" })); + await writeFile(path.join(t, "out", "p1.mp4"), "x"); + await writeFile(path.join(t, "out", "sourced", "schedule.json"), JSON.stringify({ version: 1, fps: 30, transition: 0, total: aEnd - 100 + 10, segments: [ + { id: "a", type: "clip", start: 0, duration: aEnd - 100, end: aEnd - 100 }, + { id: "b", type: "clip", start: aEnd - 100, duration: 10, end: aEnd - 90 }, + ] })); + await writeFile(path.join(t, "out", "sourced", "segments", "a.cut.json"), JSON.stringify({ id: "a", start: 100, end: aEnd })); + await writeFile(path.join(t, "out", "sourced", "segments", "b.cut.json"), JSON.stringify({ id: "b", start: 200, end: 210 })); + }; + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "p1", title: "P1", timeline: [{ type: "clip", id: "a", video: "v", start: 100, end: 110 }, { type: "clip", id: "b", video: "v", start: 200, end: 210 }] })); + await writeFile(path.join(dir, "promo", "trailer-beats.json"), JSON.stringify([{ id: "a", start: 101, end: 109 }, { id: "b", start: 201, end: 205 }])); + await takeOf("t1", 110, "2026-11-01T00:00:00Z"); + await takeOf("t2", 107, "2026-11-02T00:00:00Z"); + const out = []; + const err = []; + const run = (...a) => trailerBeatsCommand(["p1", ...a], { root: r, out: (s) => out.push(s), err: (s) => err.push(s) }); + try { + assert.equal(await run("anchor", "--take", "t1"), 0, err.join("\n")); + out.length = 0; + assert.equal(await run("status", "--take", "t2", "--json"), 0, err.join("\n")); + const st = JSON.parse(out.join("\n")); + assert.equal(st.line, "cut against t1; take t2 changes beat 1"); + assert.deepEqual(st.rows.map((x) => x.state), ["clipped", "rerendered"]); + assert.deepEqual(st.rows[0].now, { start: 100, end: 107, gaps: [] }); + assert.equal(await run("clamp", "1", "--take", "t2"), 0, err.join("\n")); + const beats = JSON.parse(await readFile(path.join(dir, "promo", "trailer-beats.json"), "utf8")); + assert.equal(beats[0].end, 107); + assert.equal(beats[0].anchor.take, "t2"); + out.length = 0; + await run("history"); + assert.match(out.join("\n"), /beat 1: start, end \(take t2\): 1\.end 109 → 107; 1\.anchor "t1" → "t2"/); + assert.equal(await run("clamp", "2", "--take", "t2"), 2); + assert.match(err.join("\n"), /only a clipped beat is clamped/); + } finally { + await rm(r, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -14,7 +14,7 @@ import { takesDirOf } from "./takes.mjs"; import { readManifest } from "../projects/report.mjs"; import { candidateBeats, trailerCandidates } from "./trailerCandidates.mjs"; import { pickReelTake, reelCuts, reelOutArg, takeMasters } from "./reelPlay.mjs"; -import { isReelId, readTrailerBeats, reelFileOf } from "./trailerBeats.mjs"; +import { isReelId, readTrailerBeats, reelFileOf, reelVersion } from "./trailerBeats.mjs"; import { TRAILER_ESTIMATE_MB, TRAILER_XFADE_DEFAULT, @@ -153,6 +153,7 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c /** The reel's own settings, under the flags. */ let reelSettings = /** @type {Record<string, any>} */ ({}); let reelBeats = null; + let reelProvenance = null; let outArg = p.flags["--out"] ?? null; if (reel !== null) { if (!isReelId(reel)) throw new CliError(`--reel ${reel}: a reel name (lower case, digits and dashes)`); @@ -161,6 +162,8 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c if (!doc.exists) throw new CliError(`no reel ${reel}: ${reelFileOf(reel)} is not there (\`umtool trailer-beats ${r.project.id} new-reel ${reel}\`)`); reelSettings = doc.settings ?? {}; reelBeats = doc.beats; + // The reel's version, named in the cut's record: a later edit makes the cut stale. + reelProvenance = { name: reel, file: reelFileOf(reel), version: reelVersion(doc) }; const masters = await takeMasters(r.project.dir); if (!take) { const chosen = pickReelTake({ pinned: reelSettings.take ?? null, cuts: await reelCuts(masters, reel), masters }); @@ -194,6 +197,7 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c out: outArg, dryRun: p.has("--dry-run"), snap: !p.has("--no-snap"), + ...(reelProvenance ? { reel: reelProvenance } : {}), ...(deps.measure ? { measure: deps.measure } : {}), ...(deps.run ? { run: deps.run } : {}), ...(deps.probe ? { probe: deps.probe } : {}), diff --git a/umtool/report-to-video/gaps.mjs b/umtool/report-to-video/gaps.mjs @@ -172,6 +172,53 @@ export function validateGaps(entry, where = `timeline entry ${entry?.id ?? "?"}` return errors; } +/** + * A clip beat's GAPS (lane/reel-bench): source seconds cut out of its middle, + * so two moments of one clip play as one beat of jump cuts -- the same shape + * and the same rule as a clip's gaps (gaps.mjs): each `{ from, to }` at least + * GAP_LIMITS.min long, in order, inside the beat with at least GAP_LIMITS.keep + * seconds kept before, between and after them, at most GAP_LIMITS.max. + * Returned sorted, each edge at 2 dp; absent or [] is none. Dependency-free, + * like the rest of this module: the reel's walk checks a gap with it before it + * is sent, and trailer.mjs (beatGaps) refuses with it. + * + * @param {{ start: number, end: number, gaps?: unknown }} b + * @param {string} where + * @returns {Array<{ from: number, to: number }>} + */ +export function beatGapsOf(b, where = "beat") { + const v = b?.gaps; + if (v === undefined || v === null) return []; + if (!Array.isArray(v)) throw new Error(`${where}: gaps is a list of { from, to } in source seconds`); + if (v.length > GAP_LIMITS.max) throw new Error(`${where}: at most ${GAP_LIMITS.max} gaps in one beat (it has ${v.length})`); + const r2 = (n) => Number(Number(n).toFixed(2)); + const list = v.map((g, k) => { + if (!g || typeof g !== "object" || !Number.isFinite(g.from) || !Number.isFinite(g.to)) throw new Error(`${where}: gaps[${k}] must be { from, to } in source seconds`); + if (g.to - g.from < GAP_LIMITS.min - 1e-6) throw new Error(`${where}: the gap ${g.from}–${g.to} is under ${GAP_LIMITS.min} s — too short to hear as a cut`); + return { from: r2(g.from), to: r2(g.to) }; + }).sort((x, y) => x.from - y.from); + let before = b.start; + list.forEach((g, k) => { + if (g.from - before < GAP_LIMITS.keep - WIN_EPS) { + throw new Error( + g.from < before + ? `${where}: the gap ${g.from}–${g.to} ${k ? "overlaps the gap before it — merge them" : `starts before the beat (${b.start})`}` + : `${where}: the gap ${g.from}–${g.to} leaves ${Math.max(0, g.from - before).toFixed(2)} s after ${k ? "the gap before it" : "the beat's start"}; keep at least ${GAP_LIMITS.keep} s`, + ); + } + before = g.to; + }); + if (list.length && b.end - before < GAP_LIMITS.keep - WIN_EPS) { + const g = list[list.length - 1]; + throw new Error( + g.to > b.end + ? `${where}: the gap ${g.from}–${g.to} runs past the beat's end (${b.end})` + : `${where}: the gap ${g.from}–${g.to} leaves ${Math.max(0, b.end - before).toFixed(2)} s before the beat's end; keep at least ${GAP_LIMITS.keep} s`, + ); + } + return list; +} + /** Every clip's gaps in the timeline, checked: the build refuses with these before it fetches. */ export function validateGapEntries(manifest) { const errors = []; @@ -359,24 +406,25 @@ const n3 = (v) => Number(v.toFixed(6)).toString(); * poster stands in; no sound: none). Empty `parts` without gaps. * * @param {{ gaps: Array<{ from: number, to: number }>, seconds: number, vIn?: string | null, aIn?: string | null, - * vOut?: string, aOut?: string, fade?: number }} o + * vOut?: string, aOut?: string, fade?: number, tag?: string }} o + * `tag` goes into the filter's own labels, so two of them sit in one graph (a trailer's runs) * @returns {{ parts: string[], v: string | null, a: string | null }} */ -export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vOut = "[gv]", aOut = "[ga]", fade = GAP_FADE }) { +export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vOut = "[gv]", aOut = "[ga]", fade = GAP_FADE, tag = "" }) { if (!gaps?.length) return { parts: [], v: vIn, a: aIn }; const pieces = keptSpans(0, seconds, gaps); const K = pieces.length; const parts = []; if (vIn) { - const outs = pieces.map((_, k) => `[gvs${k}]`); + const outs = pieces.map((_, k) => `[g${tag}vs${k}]`); parts.push(`${vIn}split=${K}${outs.join("")}`); pieces.forEach((p, k) => { - parts.push(`${outs[k]}trim=start=${n3(p.from)}:end=${n3(p.to)},setpts=PTS-STARTPTS[gvp${k}]`); + parts.push(`${outs[k]}trim=start=${n3(p.from)}:end=${n3(p.to)},setpts=PTS-STARTPTS[g${tag}vp${k}]`); }); - parts.push(`${pieces.map((_, k) => `[gvp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); + parts.push(`${pieces.map((_, k) => `[g${tag}vp${k}]`).join("")}concat=n=${K}:v=1:a=0${vOut}`); } if (aIn) { - const outs = pieces.map((_, k) => `[gas${k}]`); + const outs = pieces.map((_, k) => `[g${tag}as${k}]`); parts.push(`${aIn}asplit=${K}${outs.join("")}`); pieces.forEach((p, k) => { const len = p.to - p.from; @@ -385,9 +433,9 @@ export function gapFilterParts({ gaps, seconds, vIn = "[0:v]", aIn = "[0:a]", vO // Only at a join: the segment's own edges are the crossfade's and room's. if (k > 0) f.push(`afade=t=in:st=0:d=${n3(d)}`); if (k < K - 1) f.push(`afade=t=out:st=${n3(Math.max(0, len - d))}:d=${n3(d)}`); - parts.push(`${outs[k]}${f.join(",")}[gap${k}]`); + parts.push(`${outs[k]}${f.join(",")}[g${tag}ap${k}]`); }); - parts.push(`${pieces.map((_, k) => `[gap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); + parts.push(`${pieces.map((_, k) => `[g${tag}ap${k}]`).join("")}concat=n=${K}:v=0:a=1${aOut}`); } return { parts, v: vIn ? vOut : null, a: aIn ? aOut : null }; } diff --git a/umtool/report-to-video/trailer-gaps.test.mjs b/umtool/report-to-video/trailer-gaps.test.mjs @@ -0,0 +1,131 @@ +// trailer.mjs: a GAPPED beat (lane/reel-bench) -- two moments of one clip as +// one beat of jump cuts, cut from the master as its kept pieces joined the +// way a clip's gap renders (hard cuts, the sound faded GAP_FADE), not by the +// trailer's beat-to-beat crossfade. The rule, the plan, the graph, and one +// real encode of a synthesized master. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { TrailerError, beatGaps, parseBeats, pieceFrames, planTrailer, trailerArgs, trailerRuns } from "./trailer.mjs"; + +const SCHEDULE = { + version: 1, kind: "deck", fps: 30, transition: 0.5, total: 40.167, + segments: [ + { id: "brand-intro", type: "intro", start: 0, duration: 4.167, end: 4.167 }, + { id: "c1", type: "clip", start: 3.667, duration: 12, end: 15.667 }, + { id: "c2", type: "clip", start: 15.167, duration: 10, end: 25.167 }, + { id: "c3", type: "clip", start: 24.667, duration: 15.5, end: 40.167 }, + ], +}; +const RECORDS = new Map([ + ["c1", { version: 1, id: "c1", start: 100.2, end: 112.2 }], + // c2's render left 504–505 out: its segment plays 500–504 then 505–511. + ["c2", { version: 1, id: "c2", start: 500, end: 511, gaps: [{ from: 504, to: 505 }] }], + ["c3", { version: 1, id: "c3", start: 2000, end: 2015.5 }], +]); +const plan = (beats, o = {}) => planTrailer({ schedule: SCHEDULE, records: RECORDS, beats: parseBeats(beats), snap: false, ...o }); +const close = (a, b, eps = 1 / 60) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b}`); + +test("beatGaps: a clip's gap rule on a beat -- sorted, 2 dp, refused by name", () => { + assert.deepEqual(beatGaps({ start: 1, end: 9, gaps: [{ from: 6.004, to: 7 }, { from: 2, to: 3.5 }] }), [{ from: 2, to: 3.5 }, { from: 6, to: 7 }]); + assert.deepEqual(beatGaps({ start: 1, end: 9 }), []); + const no = (gaps, re) => assert.throws(() => beatGaps({ start: 1, end: 9, gaps }, "beat 2 (c1)"), (e) => e instanceof TrailerError && re.test(e.message)); + no([{ from: 2, to: 2.1 }], /beat 2 \(c1\): the gap 2–2.1 is under 0.2 s/); + no([{ from: 1.2, to: 3 }], /leaves 0.20 s after the beat's start; keep at least 0.5 s/); + no([{ from: 2, to: 4 }, { from: 3, to: 5 }], /overlaps the gap before it/); + no([{ from: 7, to: 8.8 }], /leaves 0.20 s before the beat's end/); + no([{ from: 7, to: 9.5 }], /runs past the beat's end/); + no("2-3", /gaps is a list/); + // parseBeats carries them on a clip beat. + assert.deepEqual(parseBeats([{ id: "c1", start: 1, end: 9, gaps: [{ from: 2, to: 3 }] }])[0].gaps, [{ from: 2, to: 3 }]); +}); + +test("a gapped beat is one piece: its span on the master, the gap's master seconds cut, the kept seconds counted", () => { + const p = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }]); + const [c] = p.pieces; + // 3.667 + (102 − 100.2) = 5.467 → frame 164; 8 s = 240 frames; the gap 104–106 is master 7.467–9.467. + assert.equal(c.frames.start, 164); + assert.equal(c.frames.count, 240); + assert.equal(c.cuts.length, 1); + assert.deepEqual(c.cuts[0].frames, { start: 224, count: 60 }); + close(c.cuts[0].from, 7.467); + assert.equal(c.seconds, 6); + assert.equal(pieceFrames(c), 180); + assert.equal(p.total, 6); + assert.deepEqual(c.gaps, [{ from: 104, to: 106 }]); +}); + +test("one gapped beat runs as long as the two beats it replaces, less their crossfade (within the 0.35 s the brief allows)", () => { + const two = plan([{ id: "c1", start: 102, end: 104 }, { id: "c1", start: 106, end: 110 }], { xfade: 0.3 }); + const one = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }], { xfade: 0.3 }); + assert.equal(two.total, 5.7); + assert.equal(one.total, 6); + assert.ok(Math.abs(one.total - two.total) <= 0.35); + // Among other beats, it lands and is counted by what it plays. + const p = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }, { id: "c3", start: 2001, end: 2004 }], { xfade: 0.3 }); + close(p.pieces[1].at, 6 - 0.3, 1e-6); + close(p.total, 6 + 3 - 0.3, 1e-6); +}); + +test("over a gap the master already cut: the master seconds either side; wholly inside one: refused by name", () => { + // c2's 504–505 is out of the master: a beat gap 503.5–506 cuts master 15.167+3.5 → 15.167+5 (1.5 s, not 2.5). + const p = plan([{ id: "c2", start: 501, end: 509, gaps: [{ from: 503.5, to: 506 }] }]); + const [c] = p.pieces; + close(c.cuts[0].from, 18.667); + close(c.cuts[0].to, 20.167); + // 8 s of source, 1 s already out of the master, 1.5 s more cut: 5.5 s. + close(c.seconds, 5.5, 1e-6); + assert.throws(() => plan([{ id: "c2", start: 501, end: 509, gaps: [{ from: 504.2, to: 504.8 }] }]), /c2's gap 504.2–504.8 lies inside a gap the master already cut out/); +}); + +test("the graph: the gapped run's cuts as a gap filter with its own labels, the crossfade offset on the kept seconds", () => { + const p = plan([{ id: "c1", start: 102, end: 110, gaps: [{ from: 104, to: 106 }] }, { id: "c3", start: 2001, end: 2004 }], { xfade: 0.3 }); + const runs = trailerRuns(p); + assert.deepEqual(runs[0], { start: 164, count: 240, cuts: [{ start: 224, count: 60 }], kept: 180 }); + assert.equal(runs[1].count, 90); + assert.equal(runs[1].cuts, undefined); + const argv = trailerArgs({ plan: p, master: "/m.mp4", render: { fps: 30 }, outPath: "/o.mp4" }); + const graph = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(graph, /\[m0v\]trim=start=[\d.]+:end=[\d.]+,setpts=PTS-STARTPTS\[r0v\]/); + assert.match(graph, /\[r0v\]split=2\[gr0vs0\]\[gr0vs1\]/); + assert.match(graph, /\[gr0vs0\]trim=start=0:end=2,setpts=PTS-STARTPTS\[gr0vp0\]/); + assert.match(graph, /\[gr0vs1\]trim=start=4:end=8,setpts=PTS-STARTPTS\[gr0vp1\]/); + assert.match(graph, /concat=n=2:v=1:a=0\[g0v\]/); + // Every picture on one timebase: xfade refuses two (the gapped run's concat is on the default one). + assert.match(graph, /\[g0v\]settb=AVTB\[v0\]/); + assert.match(graph, /\[m1v\]trim=[^;]*,setpts=PTS-STARTPTS,settb=AVTB\[v1\]/); + assert.match(graph, /afade=t=out:st=1\.975:d=0\.025/); + assert.match(graph, /concat=n=2:v=0:a=1\[a0\]/); + // The crossfade into the next beat starts 0.3 s before the gapped beat's KEPT end (6 s). + assert.match(graph, /\[v0\]\[v1\]xfade=transition=fade:duration=0\.300000:offset=5\.700000\[xv1\]/); +}); + +test("a real encode: a gapped beat cut from a synthesized master, crossfaded into the next, runs its kept seconds", { timeout: 60_000 }, async (t) => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + } catch { + t.skip("no ffmpeg"); + return; + } + const dir = await mkdtemp(path.join(tmpdir(), "trailer-gaps-")); + try { + const master = path.join(dir, "m.mp4"); + execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=30:duration=12", "-f", "lavfi", "-i", "sine=frequency=440:duration=12", + "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-preset", "ultrafast", "-g", "15", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", master]); + const schedule = { version: 1, kind: "deck", fps: 30, transition: 0, total: 12, segments: [{ id: "c", type: "clip", start: 0, duration: 6, end: 6 }, { id: "d", type: "clip", start: 6, duration: 6, end: 12 }] }; + const records = new Map([["c", { id: "c", start: 10, end: 16 }], ["d", { id: "d", start: 50, end: 56 }]]); + // A gapped beat crossfaded into the next: 5 s less its 1 s gap, then 4 s, less the 0.3 s crossfade. + const p = planTrailer({ schedule, records, beats: parseBeats([{ id: "c", start: 10.5, end: 15.5, gaps: [{ from: 12, to: 13 }] }, { id: "d", start: 51, end: 55 }]), xfade: 0.3, snap: false }); + assert.equal(p.total, 7.7); + const out = path.join(dir, "t.mp4"); + execFileSync("ffmpeg", trailerArgs({ plan: p, master, render: { fps: 30, crf: 35, preset: "ultrafast", audioBitrate: "64k", audioRate: 48000, audioChannels: 2 }, outPath: out })); + const dur = Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", out], { encoding: "utf8" }).trim()); + close(dur, 7.7, 0.1); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -66,7 +66,7 @@ import { execFile } from "node:child_process"; import { rmSync } from "node:fs"; -import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; @@ -74,7 +74,7 @@ import { encodeArgs } from "./build-video.mjs"; import { clipWords } from "./clip-words.mjs"; import { DEFAULT_CHANNELS_DIR } from "./cues.mjs"; import { detectSilence } from "./cut-points.mjs"; -import { offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; +import { beatGapsOf, gapFilterParts, offsetIn, recordGaps, sourceAtOffset } from "./gaps.mjs"; import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; const execFileP = promisify(execFile); @@ -131,7 +131,8 @@ export function parseBeats(value) { if (typeof b.id !== "string" || !b.id) throw new TrailerError(`${where}: id is a clip id (a string)`); if (!num("start") || !num("end")) throw new TrailerError(`${where} (${b.id}): start and end are source seconds (numbers)`); if (b.end <= b.start) throw new TrailerError(`${where} (${b.id}): end ${b.end} is not after start ${b.start}`); - return { kind: "clip", id: b.id, start: b.start, end: b.end, ...(label ? { label } : {}) }; + const gaps = beatGaps(b, `${where} (${b.id})`); + return { kind: "clip", id: b.id, start: b.start, end: b.end, ...(gaps.length ? { gaps } : {}), ...(label ? { label } : {}) }; } if (b.at !== undefined || b.dur !== undefined) { if (!num("at") || !num("dur")) throw new TrailerError(`${where}: at and dur are master seconds (numbers)`); @@ -143,6 +144,21 @@ export function parseBeats(value) { } /** + * A clip beat's GAPS (gaps.mjs beatGapsOf: a clip's gap rule, on a beat), + * refused as a TrailerError. + * + * @param {{ start: number, end: number, gaps?: unknown }} b + * @param {string} where + */ +export function beatGaps(b, where = "beat") { + try { + return beatGapsOf(b, where); + } catch (e) { + throw new TrailerError(e instanceof Error ? e.message : String(e)); + } +} + +/** * Each segment's span in the master, by id: `{ id, type, index, start, end }`. * `end` is the schedule's own (a deck schedule writes it), else start + * duration, else where the next segment's crossfade ends (a rail schedule @@ -233,7 +249,19 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = if (gaps.some((g) => g.from < e && g.to > s)) { notes.push(`beat ${n + 1}: ${beat.id} ${beat.start}–${beat.end} spans a gap — it plays the master's jump cut (${fmt(b - a)} s)`); } - want.push({ kind: "clip", id: beat.id, beat, n: n + 1, rec, seg, gaps, a, b }); + // The beat's OWN gaps (beatGaps), as spans of the master to leave out. The + // master runs on across a gap its render already cut, so a beat gap over + // one is the master seconds either side of it; one wholly inside it has + // nothing left to cut, and is refused. + const cuts = (beat.gaps ?? []).map((g) => { + const ca = seg.start + offsetIn(Math.max(g.from, s), rec.start, gaps); + const cb = seg.start + offsetIn(Math.min(g.to, e), rec.start, gaps); + if (cb - ca < 1 / fps) { + throw new TrailerError(`beat ${n + 1}: ${beat.id}'s gap ${g.from}–${g.to} lies inside a gap the master already cut out of the clip — nothing of it plays there to cut`); + } + return { from: ca, to: cb }; + }); + want.push({ kind: "clip", id: beat.id, beat, n: n + 1, rec, seg, gaps, cuts, a, b }); }); if (finale != null) { if (!Number.isFinite(finale) || finale <= 0) throw new TrailerError(`--finale ${finale}: seconds > 0`); @@ -336,7 +364,28 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = const fa = Math.round(a * fps); const frames = Math.round(b * fps) - fa; const name = w.kind === "clip" ? w.id : w.kind === "intro" ? "intro" : w.kind === "finale" ? "finale" : `beat ${i + 1}`; - if (frames < 1 || frames / fps <= xIn + xOut) { + // The beat's gaps on frames, inside what is left of it: each cut keeps at + // least a frame either side, so the beat starts and ends on its own material. + const cutFrames = []; + for (const c of w.cuts ?? []) { + const cs = Math.max(fa + 1, Math.round(c.from * fps)); + const ce = Math.min(fa + frames - 1, Math.round(c.to * fps)); + if (ce - cs < 1) { + notes.push(`${name}: its gap at master ${fmt(c.from)}–${fmt(c.to)} falls outside what is left of the beat — not cut`); + continue; + } + cutFrames.push({ start: cs, count: ce - cs }); + } + const kept = frames - cutFrames.reduce((n, c) => n + c.count, 0); + if (cutFrames.length) { + const first = cutFrames[0].start - fa; + const lastC = cutFrames[cutFrames.length - 1]; + const tail = fa + frames - (lastC.start + lastC.count); + if (first / fps <= xIn || tail / fps <= xOut) { + throw new TrailerError(`${name}: a gap leaves ${fmt(Math.min(first, tail) / fps)} s at the beat's ${first / fps <= xIn ? "start" : "end"} — too short for the ${fmt(x)} s crossfade`); + } + } + if (frames < 1 || kept / fps <= xIn + xOut) { throw new TrailerError( `${name}: ${fmt(Math.max(0, frames / fps))} s left once it is out of the master's crossfades — too short for ` + `${xIn || xOut ? `a ${fmt(x)} s crossfade either side` : "a cut"}`, @@ -350,6 +399,15 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = ...(w.beat?.label ? { label: w.beat.label } : {}), master: { start: r3(start), end: r3(start + duration), duration: r3(duration) }, frames: { start: fa, count: frames }, + // A gapped beat: the master spans it leaves out (each a hard cut, the sound + // faded GAP_FADE either side, as a clip's gap renders) and the seconds it plays. + ...(cutFrames.length + ? { + cuts: cutFrames.map((c) => ({ from: r3(c.start / fps), to: r3((c.start + c.count) / fps), frames: c })), + seconds: r3(kept / fps), + gaps: w.beat.gaps, + } + : {}), ...(seam[i] ? { seamless: true } : {}), // The source seconds it plays, its gaps counted: a beat after a gap is // that much later in its source than in its segment. @@ -384,7 +442,7 @@ export function planTrailer({ schedule, records, beats, intro = false, finale = pieces.forEach((p, i) => { const over = i > 0 && !p.seamless ? x : 0; p.at = r3(acc - over); - acc = acc + p.frames.count / fps - over; + acc = acc + pieceFrames(p) / fps - over; }); // The same master seconds twice: the operator's call, but said. @@ -406,16 +464,25 @@ function pieceName(p, i) { return p.kind === "clip" ? p.id : p.kind === "raw" ? `beat at ${fmt(at)}` : p.kind ?? `piece ${i + 1}`; } +/** The frames a piece plays: its span, less its gaps' cuts. */ +export const pieceFrames = (p) => p.frames.count - (p.cuts ?? []).reduce((n, c) => n + c.frames.count, 0); + /** * The runs of the master a plan reads: its pieces, a seamless one folded into - * the run before it (its frames follow on). `{ start, count }` in frames. + * the run before it (its frames follow on). `{ start, count }` in frames; a run + * holding a gapped beat also carries its `cuts` (`{ start, count }`, master + * frames) and the frames it `kept`. */ export function trailerRuns(plan) { const runs = []; for (const p of plan.pieces) { const last = runs[runs.length - 1]; - if (p.seamless && last) last.count = p.frames.start + p.frames.count - last.start; + const run = p.seamless && last ? last : null; + if (run) run.count = p.frames.start + p.frames.count - run.start; else runs.push({ start: p.frames.start, count: p.frames.count }); + const r = runs[runs.length - 1]; + if (p.cuts?.length) r.cuts = [...(r.cuts ?? []), ...p.cuts.map((c) => ({ ...c.frames }))]; + if (r.cuts) r.kept = r.count - r.cuts.reduce((n, c) => n + c.count, 0); } return runs; } @@ -454,29 +521,41 @@ export function trailerArgs({ plan, master, render, outPath, threads = TRAILER_D const half = 0.5 / fps; const src = filterPath(master); const parts = []; + // A gapped run's concat puts its picture on the default timebase (1/1000000), and + // xfade wants both inputs on one: with any gapped run, every run's picture is put there. + const tb = runs.some((r) => r.cuts?.length) ? ",settb=AVTB" : ""; runs.forEach((r, i) => { const a = r.start / fps; const n = r.count; const d = (n / fps).toFixed(6); const seek = Math.max(0, a - PRE_ROLL); parts.push(`movie=filename=${src}:seek_point=${seek.toFixed(6)}:streams=dv+da:dec_threads=${threads}[m${i}v][m${i}a]`); - parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS[v${i}]`); + const cut = r.cuts?.length; + parts.push(`[m${i}v]trim=start=${Math.max(0, a - half).toFixed(6)}:end=${(a + n / fps - half).toFixed(6)},setpts=PTS-STARTPTS${cut ? "" : tb}[${cut ? `r${i}v` : `v${i}`}]`); parts.push( `[m${i}a]atrim=start=${a.toFixed(6)}:end=${(a + n / fps).toFixed(6)},asetpts=PTS-STARTPTS,` + - `apad=whole_dur=${d},atrim=end=${d}[a${i}]`, + `apad=whole_dur=${d},atrim=end=${d}[${cut ? `r${i}a` : `a${i}`}]`, ); + // A gapped beat: its cuts left out of the run as a clip's gaps are of its + // segment (gaps.mjs gapFilterParts: hard cuts, the sound faded either side). + if (cut) { + const gaps = r.cuts.map((c) => ({ from: (c.start - r.start) / fps, to: (c.start + c.count - r.start) / fps })); + parts.push(...gapFilterParts({ gaps, seconds: n / fps, vIn: `[r${i}v]`, aIn: `[r${i}a]`, vOut: `[g${i}v]`, aOut: `[a${i}]`, tag: `r${i}` }).parts); + parts.push(`[g${i}v]settb=AVTB[v${i}]`); + } }); + const keptOf = (r) => (r.kept ?? r.count) / fps; let vlab = "[v0]"; let alab = "[a0]"; if (runs.length > 1 && x > 0) { - let acc = runs[0].count / fps; + let acc = keptOf(runs[0]); for (let i = 1; i < runs.length; i += 1) { const off = acc - x; parts.push(`${vlab}[v${i}]xfade=transition=fade:duration=${x.toFixed(6)}:offset=${off.toFixed(6)}[xv${i}]`); parts.push(`${alab}[a${i}]acrossfade=d=${x.toFixed(6)}:c1=tri:c2=tri[xa${i}]`); vlab = `[xv${i}]`; alab = `[xa${i}]`; - acc = acc + runs[i].count / fps - x; + acc = acc + keptOf(runs[i]) - x; } } else if (runs.length > 1) { parts.push(`${runs.map((_, i) => `[v${i}][a${i}]`).join("")}concat=n=${runs.length}:v=1:a=1[cv][ca]`); @@ -633,7 +712,7 @@ export async function runFfmpeg(argv) { export async function makeTrailer({ takeDir, beats, intro = false, finale = null, xfade = TRAILER_XFADE_DEFAULT, out = null, dryRun = false, run = runFfmpeg, probe = probeMasterSeconds, slot = (fn) => fn(), now = Date.now, - snap = true, measure = (build, list) => trailerPauses({ build, beats: list }), + snap = true, measure = (build, list) => trailerPauses({ build, beats: list }), reel = null, }) { const build = await loadTakeBuild(takeDir); // Checked once without the pauses first: a beat that is refused is refused @@ -652,12 +731,19 @@ export async function makeTrailer({ const outPath = trailerOutPath(takeDir, build.slug, out); if (path.resolve(outPath) === path.resolve(build.master)) throw new TrailerError(`--out ${out}: that is the master`); const recordPath = trailerRecordPath(outPath); + // What it was cut from, named so a later read can say the cut is stale: the + // master by its mtime and the take's build, the reel by its file's version. + const masterStat = await stat(build.master).catch(() => null); + const takeMeta = await readFile(path.join(takeDir, "take.json"), "utf8").then(JSON.parse, () => null); const record = { version: 1, kind: "trailer", + ...(reel ? { reel } : {}), source: { take: path.basename(takeDir), + build: typeof takeMeta?.builtAt === "string" ? takeMeta.builtAt : null, master: build.master, + masterMtimeMs: masterStat ? Math.round(masterStat.mtimeMs) : null, masterSeconds: r3(masterSeconds), schedule: path.join(takeDir, "out", "sourced", "schedule.json"), }, @@ -724,8 +810,8 @@ export function describePlan(plan) { : p.kind === "raw" ? `${"(master)".padEnd(22)} at ${fmt(p.asked.at)} for ${fmt(p.asked.dur)}` : `${`(${p.kind})`.padEnd(22)}`; const span = `master ${clock(p.master.start)}–${clock(p.master.end)}`; - const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}`; - return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.master.duration)} s${marks}`; + const marks = `${p.moved ? " (edge moved)" : ""}${p.snapped ? " (into a pause)" : ""}${p.cuts?.length ? ` (${p.cuts.length} gap${p.cuts.length === 1 ? "" : "s"} cut)` : ""}`; + return `${String(i + 1).padStart(2)}. ${clock(p.at).padStart(6)} ${what.padEnd(48)} ${span} ${fmt(p.seconds ?? p.master.duration)} s${marks}`; }); lines.push(`total ${clock(plan.total)} (${fmt(plan.total)} s), ${plan.pieces.length} pieces, crossfade ${fmt(plan.xfade)} s`); return lines;