commit e14ce9384e941070590c5d7cf0919fea20aa4290
parent 810e58efd7329dda3fe46d67f9dd595cae6a23a4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 24 Oct 2026 02:54:24 -0400
Play the cut plays the render's edges; the bench draws where the render cuts
The plan (playCut.mjs playPlan, `cuts`) takes each clip's render cut from
the cut-points route and re-times the clock by it: every clip plays from the
render's first source second to its last, every later entry moved by what
the clips before it gained or lost. The chrome, composed on the estimate's
clock, is seeked by the source second playing (chromeTime), the counter's
steps placed back by the same rule (playTimeOfChrome), and a note seeks by
its clip and source second. The Approximate line says whose edges play.
The clip bench draws a faint ghost at each edge the render will cut at,
with its offset ("render: +0.52 s"), snapped live from the measured
silences by snap.mjs as an edge is dragged (RenderGhosts.tsx).
play-cut.spec.ts reads the render's clock; play-engine.spec.ts (on its
own fixture project) checks the edges Play schedules, the ghosts, and that
an edge moved in the bench is what Play plays next.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 543 insertions(+), 65 deletions(-)
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -18,6 +18,7 @@ import { cn } from "@/lib/utils";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import CopyCitation from "./bench/CopyCitation";
import EdgeStrip from "./bench/EdgeStrip";
+import RenderGhosts from "./bench/RenderGhosts";
// 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.
@@ -3184,6 +3185,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
</div>
</>
)}
+ {/* Where the render will actually cut: each edge snapped to its silence, faint. */}
+ <RenderGhosts project={data.project} clip={clip} sel={sel} view={view} />
{/* Armed: the next click places the mark rather than an edge. */}
{mutePick && (
<div
diff --git a/umtool/components/projects/bench/RenderGhosts.tsx b/umtool/components/projects/bench/RenderGhosts.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { renderCut } from "umtool-report-to-video/snap";
+
+// WHERE THE RENDER WILL CUT THIS CLIP, over the bench's waveform: a faint
+// ghost at each edge the build will actually cut at -- the play window (the
+// cut with its lead-in, else the extent, as drafted) snapped to the nearest
+// silence (snap.mjs, the build's own arithmetic) -- with how far it is from
+// the edge drawn ("render +0.52 s"). The silences come from the cut-points
+// route (lib/report/cutPoints.mjs: the build's file, the build's
+// silencedetect, measured once and cached); the snap runs here, so a ghost
+// follows a drag with no request. A draft that reaches past what was measured
+// snaps there as unsnapped, until it is saved and measured again.
+
+type Silence = { s: number; e: number };
+type Row = {
+ id: string;
+ silences?: Silence[];
+ fetchStart?: number;
+ sound?: [number, number];
+ montage?: boolean;
+ missing?: boolean;
+ error?: string;
+};
+type Got = { knobs: Record<string, number | null>; leadIn: number; clips: Row[] };
+
+/** The play window (deck.mjs playWindow) of a drafted extent and the saved cut. */
+function playWindowOf(sel: { from: number; to: number }, cut: { cutStart: number | null; cutEnd: number | null }, leadIn: number) {
+ const has = cut.cutStart != null && cut.cutEnd != null;
+ return {
+ from: has ? Math.max(sel.from, cut.cutStart! - leadIn) : sel.from,
+ to: has ? Math.min(sel.to, cut.cutEnd!) : sel.to,
+ };
+}
+
+export default function RenderGhosts({
+ project,
+ clip,
+ sel,
+ view,
+}: {
+ project: string;
+ clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null };
+ sel: { from: number; to: number };
+ view: { from: number; to: number };
+}) {
+ const [got, setGot] = useState<{ key: string; row: Row | null; knobs: Got["knobs"]; leadIn: number } | null>(null);
+ // Measured again when what was SAVED moves (the extent picks the file and the span).
+ const key = `${project}|${clip.id}|${clip.start}|${clip.end}|${clip.cutStart}|${clip.cutEnd}`;
+ useEffect(() => {
+ let live = true;
+ const q = new URLSearchParams({ project, clip: clip.id });
+ fetch(`/api/report/cut-points?${q}`, { cache: "no-store" })
+ .then((r) => (r.ok ? (r.json() as Promise<Got>) : null))
+ .then((j) => {
+ if (live && j) setGot({ key, row: j.clips.find((c) => c?.id === clip.id) ?? null, knobs: j.knobs, leadIn: j.leadIn });
+ })
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ }, [key, project, clip.id]);
+ const row = got?.row;
+ if (!row || !row.silences || row.fetchStart == null || row.montage) return null;
+ const pw = playWindowOf(sel, clip, got!.leadIn);
+ const render = {
+ snapWindow: got!.knobs.snapWindow ?? undefined,
+ snapLead: got!.knobs.snapLead ?? undefined,
+ snapTail: got!.knobs.snapTail ?? undefined,
+ };
+ const cut = renderCut({ sil: row.silences, fetchStart: row.fetchStart, playFrom: pw.from, playTo: pw.to, render });
+ const span = Math.max(1e-6, view.to - view.from);
+ const pct = (t: number) => `${((t - view.from) / span) * 100}%`;
+ const edges = [
+ { edge: "start", at: cut.start, from: pw.from, snapped: cut.snapped.start },
+ { edge: "end", at: cut.end, from: pw.to, snapped: cut.snapped.end },
+ ] as const;
+ return (
+ <>
+ {edges.map((g) => {
+ if (g.at < view.from || g.at > view.to) return null;
+ const d = g.at - g.from;
+ const label = Math.abs(d) < 0.005 ? "render: here" : `render: ${d > 0 ? "+" : "−"}${Math.abs(d).toFixed(2)} s`;
+ return (
+ <div
+ key={g.edge}
+ data-render-edge={g.edge}
+ data-render-at={g.at}
+ data-render-offset={Number(d.toFixed(3))}
+ data-render-snapped={g.snapped ? "" : undefined}
+ title={`the render cuts here (${g.snapped ? "snapped to a silence" : "no silence near: as drawn"}); ${label}`}
+ className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-text)_45%,transparent)]"
+ style={{ left: pct(g.at) }}
+ >
+ <span
+ className={`absolute ${g.edge === "start" ? "right-full mr-0.5" : "left-full ml-0.5"} top-3 whitespace-nowrap rounded bg-[color-mix(in_srgb,var(--color-panel-2)_80%,transparent)] px-1 font-mono text-[9px] leading-tight text-[var(--color-dim)]`}
+ >
+ {label}
+ </span>
+ </div>
+ );
+ })}
+ </>
+ );
+}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -12,7 +12,7 @@ import { cn } from "@/lib/utils";
import { footageAt } from "@/lib/report/footage-move.mjs";
import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
import {
- counterSteps, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, runningTime, seamsOf, sourceAt, startOf,
+ chromeTime, counterSteps, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, playTimeOfChrome, runningTime, seamsOf, sourceAt, startOf,
} from "@/lib/report/playCut.mjs";
import { tallyVerdicts } from "umtool-report-to-video/factcheck";
import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur";
@@ -20,6 +20,7 @@ import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from ".
import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
import { drawFootage, type FootageBlur } from "./footageCanvas";
import ReelStrip, { type StripCounter } from "./ReelStrip";
+import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -29,9 +30,13 @@ import ReelStrip, { type StripCounter } from "./ReelStrip";
//
// THE CLOCK is one cut clock across every entry (lib/report/playCut.mjs):
// the estimate's segments (the live preview's schedule when the cut has a
-// deck: posts' holds included), each clip played from its cached source
+// deck: posts' holds included), re-timed by the RENDER'S EDGES -- each clip
+// snapped to its silences exactly as the build snaps it (the cut-points
+// route, lib/report/cutPoints.mjs) -- each clip played from its cached source
// window -- the bench's own media route, /api/report/raw, `take` for a take's
// clip -- and the crossfades played as HARD CUTS at the middle of each one.
+// The chrome, composed on the estimate's clock, is seeked by the source
+// second playing (chromeTime), so a stamp lands on its word.
// While a clip plays the clock IS its <video>'s position mapped through the
// play window (liveClock.mjs's rule), so the deck's rail pip, the tally, the
// stamps and the finale advance exactly as the live preview places them; a
@@ -156,8 +161,18 @@ const KEYS: { keys: string; what: string }[] = [
{ keys: "?", what: "these keys" },
];
-const APPROXIMATE =
- "Approximate: crossfades are hard cuts at their middle, cards and teasers are placeholders, edges are not snapped to silence, the sound is the recording's own, the clock is the estimate's."
+/** What Play does not do as the render does: the line under the picture. */
+function approximateLine(edges: RenderCuts) {
+ const edge =
+ edges.state === "render"
+ ? edges.montage
+ ? "edges snapped as plain cuts (a montage's phrase cuts are not modelled)"
+ : "edges are the render's, snapped to silence"
+ : edges.state === "measuring"
+ ? "edges are the manifest's until the render's are measured"
+ : `edges are the manifest's (the render's could not be measured: ${edges.why ?? "no answer"})`;
+ return `Approximate: crossfades are hard cuts at their middle, cards and teasers are placeholders, the sound is the recording's own, the chrome is composed on the estimate's clock; ${edge}.`;
+}
/** The pinned player as a strip, once the transport is under it (a phone). */
const STRIP_H = 120;
@@ -219,7 +234,10 @@ export default function PlayCut({
const schedule = doc?.schedule ?? null;
const segments = schedule?.segments ?? view.segments;
const leadIn = doc?.leadIn ?? view.leadIn;
- const plan = useMemo(() => playPlan(segments, view.entries, { leadIn }), [segments, view.entries, leadIn]);
+ // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change.
+ const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd])), [view.entries]);
+ const edges = useRenderCuts(project, take, edgesKey);
+ const plan = useMemo(() => playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), [segments, view.entries, leadIn, edges.cuts]);
const entryOf = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
const planRef = useRef(plan);
planRef.current = plan;
@@ -362,10 +380,13 @@ export default function PlayCut({
publish();
}, [plan, enter, publish]);
- // `?clip=&at=` (back from the clip bench): that clip, that far in -- placed
- // again when the composed schedule replaces the estimate's, since the two
- // clocks differ, and let go once the composition has settled.
- const anchor = useRef(initialAt);
+ // `?clip=&at=` (back from the clip bench): that clip, that far in -- the
+ // offset turned into the SOURCE second it shows once the render's edges are
+ // in, and that second
+ // placed again (cutAtSource) whenever the plan is re-timed under it: the
+ // composed schedule replacing the estimate's, the render's edges arriving.
+ // Let go once both have settled. A card keeps its offset.
+ const anchor = useRef<{ clip: string; at: number; src?: number } | null>(initialAt);
useEffect(() => {
const a = anchor.current;
if (!a) return;
@@ -375,9 +396,12 @@ export default function PlayCut({
return;
}
const it = plan.items[i];
- seekTo(Math.min(it.from + a.at, Math.max(it.from, it.to - 0.05)));
- if (composeState !== "composing") anchor.current = null;
- }, [plan, composeState, seekTo]);
+ const inside = (v: number) => Math.min(Math.max(it.from, v), Math.max(it.from, it.to - 0.05));
+ // (The offset was taken on the render's clock: turned into a source second once the render's edges are in.)
+ if (it.clip && a.src === undefined && edges.state !== "measuring") a.src = sourceAt(it, inside(it.from + a.at)) ?? undefined;
+ seekTo(it.clip && a.src !== undefined ? inside(cutAtSource(it, a.src)) : inside(it.from + a.at));
+ if (composeState !== "composing" && edges.state !== "measuring") anchor.current = null;
+ }, [plan, composeState, edges.state, seekTo]);
useEffect(() => {
eng.current.rate = rate;
@@ -494,6 +518,12 @@ export default function PlayCut({
() => notes.notes.filter((n) => n.anchor.kind === "cut" && (n.anchor.take ?? null) === take).sort((a, b) => (a.anchor as CutAnchor).t - (b.anchor as CutAnchor).t),
[notes.notes, take],
);
+ // A note's second on this clock: by its clip and source second when it has them (the
+ // render's edges re-time the cut; a note stays on the word it was taken on), else its t.
+ const noteT = useCallback((a: CutAnchor) => {
+ const it = a.entry && Number.isFinite(a.sourceT) ? planRef.current.items.find((x) => x.id === a.entry && x.clip) : null;
+ return it ? Math.min(it.to, Math.max(it.from, cutAtSource(it, a.sourceT as number))) : a.t;
+ }, []);
const [drafting, setDrafting] = useState<CutAnchor | null>(null);
const [pauseWhileWriting, setPauseWhileWriting] = useState(true);
useEffect(() => {
@@ -526,11 +556,11 @@ export default function PlayCut({
const stepNote = useCallback(
(d: 1 | -1) => {
const t = eng.current.t;
- const ts = mine.map((n) => (n.anchor as CutAnchor).t);
+ const ts = mine.map((n) => noteT(n.anchor as CutAnchor));
const to = d > 0 ? ts.find((x) => x > t + 0.05) : [...ts].reverse().find((x) => x < t - 0.05);
if (to !== undefined) seekTo(to);
},
- [mine, seekTo],
+ [mine, seekTo, noteT],
);
// `?note=<id>` (the Inbox's link): seek to it once the notes are read.
@@ -540,8 +570,8 @@ export default function PlayCut({
const n = mine.find((x) => x.id === initialNote);
if (!n) return;
sought.current = true;
- seekTo((n.anchor as CutAnchor).t);
- }, [initialNote, mine, seekTo]);
+ seekTo(noteT(n.anchor as CutAnchor));
+ }, [initialNote, mine, seekTo, noteT]);
// ---- edit this clip ----------------------------------------------------------------
const editHref = useCallback(() => {
@@ -599,17 +629,19 @@ export default function PlayCut({
// ---- what is on screen -------------------------------------------------------------
const t = ui.t;
+ // The chrome was composed on the estimate's clock: seeked by the source second playing.
+ const tc = chromeTime(plan, t);
const item = plan.items[ui.cur] ?? null;
const entry = item ? entryOf.get(item.id) : null;
const g = doc?.geometry ?? null;
const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
- const move = schedule ? footageAt(schedule, t) : null;
+ const move = schedule ? footageAt(schedule, tc) : null;
const rect: Rect | null = move?.rect ?? box;
const order = useMemo(() => (schedule?.factcheck ? tallyVerdicts(schedule.factcheck.stamps) : []), [schedule]);
- const tally = schedule?.factcheck ? tallyAt(schedule, t, order) : [];
- const stamp = schedule ? stampAt(schedule, t) : null;
- const finaleNow = !!schedule && finaleUp(schedule, t);
- const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, t) : null;
+ const tally = schedule?.factcheck ? tallyAt(schedule, tc, order) : [];
+ const stamp = schedule ? stampAt(schedule, tc) : null;
+ const finaleNow = !!schedule && finaleUp(schedule, tc);
+ const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null;
const missing = !!item?.clip && !entry?.media;
const broken = !!item && !!failed[item.id];
const placeholder = item && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
@@ -620,10 +652,12 @@ export default function PlayCut({
const stamps = (schedule?.factcheck?.stamps as { landed: number; verdict: string; count?: number }[] | undefined) ?? view.counter.stamps;
const labels = new Map(view.counter.verdicts.map((v) => [v.id, v.label]));
const ids = [...new Set(stamps.map((s) => s.verdict))];
- return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(stamps, id) }));
- }, [schedule, view.counter, doc?.verdictLabels]);
+ // Landed on the estimate's clock: placed on this one by the source second they land on.
+ const placed = stamps.map((x) => ({ ...x, landed: playTimeOfChrome(plan, x.landed) }));
+ return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(placed, id) }));
+ }, [schedule, view.counter, doc?.verdictLabels, plan]);
const seams = useMemo(() => seamsOf(view.entries, view.markers), [view.entries, view.markers]);
- const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: (n.anchor as CutAnchor).t, text: n.text, open: n.status === "open" })), [mine]);
+ const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]);
const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
const placeholderCard = placeholder ? (
@@ -707,11 +741,15 @@ export default function PlayCut({
data-play-cut={take ?? ""}
// The clip on screen's play window, in source seconds: what an edit on
// the bench changes, and what "Back to the cut" must play.
- data-play-source={item?.clip ? `${item.clip.sourceFrom}-${item.clip.sourceTo}` : ""}
+ // (The manifest's, before the render's edges re-time the plan: `est`.)
+ data-play-source={item?.clip ? `${item.est?.sourceFrom ?? item.clip.sourceFrom}-${item.est?.sourceTo ?? item.clip.sourceTo}` : ""}
data-play-state={ui.ended ? "ended" : ui.playing ? (ui.waiting ? "waiting" : "playing") : "paused"}
data-play-t={String(Math.round(t * 100) / 100)}
data-play-item={item?.id ?? ""}
data-play-compose={composeState}
+ data-play-edges={edges.state}
+ // The render's cut of the clip on screen (the edges it plays), in source seconds.
+ data-play-span={item?.clip ? `${item.clip.sourceFrom}-${item.clip.sourceTo}` : ""}
className="flex flex-col min-[900px]:min-h-0 min-[900px]:flex-1 min-[900px]:overflow-hidden max-md:gap-3 max-md:px-4 max-md:pb-[calc(88px+env(safe-area-inset-bottom))]"
>
{/* ---- the head: the cut's title, what plays, the running time ---- */}
@@ -773,16 +811,16 @@ export default function PlayCut({
</div>
<div className="relative">
{doc && g && box ? (
- <DeckFrame preview={doc} t={t} texts={{}} testid="play-deck">
+ <DeckFrame preview={doc} t={tc} texts={{}} testid="play-deck">
<div className="absolute inset-0" style={{ background: bg }} />
{footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)}
{placeholderCard}
- {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={t} testid="play-feed" />}
- {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={t} />}
- {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={t} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
+ {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
+ {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
+ {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
{doc.finale && finaleNow && (
<div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale="">
- <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={t} ready="finale:ready" testid="play-finale" name="finale" />
+ <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={tc} ready="finale:ready" testid="play-finale" name="finale" />
</div>
)}
</DeckFrame>
@@ -893,7 +931,7 @@ export default function PlayCut({
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[11px] text-muted" data-play-approximate="">
<span>
- {APPROXIMATE}
+ {approximateLine(edges)}
{!view.blurRendered ? " Blurred clips play unblurred (render.blur off)." : ""}
{view.note ? ` ${view.note}.` : ""}
</span>
@@ -937,7 +975,7 @@ export default function PlayCut({
}}
onNote={noteHere}
onClose={closeDraft}
- onSeek={(n) => seekTo((n.anchor as CutAnchor).t)}
+ onSeek={(n) => seekTo(noteT(n.anchor as CutAnchor))}
onApplied={() => {
router.refresh();
if (view.deckOn) void compose();
diff --git a/umtool/components/projects/review/playEngine/useRenderCuts.ts b/umtool/components/projects/review/playEngine/useRenderCuts.ts
@@ -0,0 +1,56 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { RenderCut } from "@/lib/report/playCut.mjs";
+
+// Where the render will cut each clip (GET /api/report/cut-points: the build's
+// own snap, lib/report/cutPoints.mjs), for the Play view's plan. Asked again
+// whenever the cut's entries change (a reload after an edge was moved in the
+// bench): the route measures only what moved. Until it answers the plan plays
+// the manifest's edges, and says so.
+
+type Row = RenderCut & { id: string; missing?: boolean; error?: string; montage?: boolean };
+export type RenderCuts = {
+ state: "measuring" | "render" | "estimate";
+ cuts: Map<string, RenderCut> | null;
+ /** render.transitionStyle, as the route read it. */
+ style: string;
+ /** A montage cuts each clip to its phrase, which the route does not model. */
+ montage: boolean;
+ why: string | null;
+};
+
+export function useRenderCuts(project: string, take: string | null, key: string): RenderCuts {
+ const [got, setGot] = useState<RenderCuts>({ state: "measuring", cuts: null, style: "fade", montage: false, why: null });
+ const cutOf = useRef("");
+ useEffect(() => {
+ let live = true;
+ // Another cut (a take): nothing of the last one's applies. The same cut with an edge moved: its
+ // edges stand until the new ones are measured (only what moved is).
+ const which = `${project}|${take ?? ""}`;
+ if (cutOf.current !== which) {
+ cutOf.current = which;
+ setGot({ state: "measuring", cuts: null, style: "fade", montage: false, why: null });
+ }
+ const q = new URLSearchParams({ project, ...(take ? { take } : {}) });
+ fetch(`/api/report/cut-points?${q}`, { cache: "no-store" })
+ .then(async (r) => {
+ const j = (await r.json().catch(() => null)) as { clips?: Row[]; transitionStyle?: string; montage?: boolean; error?: string } | null;
+ if (!live) return;
+ if (!r.ok || !j?.clips) {
+ setGot({ state: "estimate", cuts: null, style: "fade", montage: false, why: j?.error ?? `HTTP ${r.status}` });
+ return;
+ }
+ const cuts = new Map<string, RenderCut>();
+ for (const c of j.clips) if (c && !c.missing && !c.error && Number.isFinite(c.cutStart) && Number.isFinite(c.cutEnd)) cuts.set(c.id, c);
+ setGot({ state: "render", cuts, style: j.transitionStyle ?? "fade", montage: !!j.montage, why: null });
+ })
+ .catch((e: unknown) => {
+ if (live) setGot({ state: "estimate", cuts: null, style: "fade", montage: false, why: e instanceof Error ? e.message : String(e) });
+ });
+ return () => {
+ live = false;
+ };
+ }, [project, take, key]);
+ return got;
+}
diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs
@@ -4,7 +4,8 @@
// window on the estimate's clock -- with a card between clips, a clip whose
// source was never fetched (a placeholder, not a stall), and two takes: one
// made (takes/short/take.json, its own timeline: c04 then c01) and one only
-// a recipe names (quick-joins, a hard-cut look).
+// a recipe names (quick-joins, a hard-cut look). And play-engine-fixture, the
+// same cut for play-engine.spec.ts, which writes.
//
// c01 vid1 1.0-3.0 c02 vid1 3.5-5.5 (k1 at 4.5) k01 card 1.5 s
// c03 nofetch 2-4 (no window on disk) c04 vid1 6.0-8.0 (k2, counts 2)
@@ -56,6 +57,14 @@ export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name =
) + "\n",
);
copyFileSync(cachedWindow, path.join(dir, "takes", "short", "preview.mp4"));
+ // play-engine.spec.ts's own copy of the cut (no takes): it WRITES (a bench
+ // edge edit), so play-cut.spec.ts's numbers never depend on which ran first.
+ if (name === "play-cut-fixture") {
+ const eng = path.join(reports, "play-engine-fixture");
+ mkdirSync(path.join(eng, "out", "clips-raw"), { recursive: true });
+ writeFileSync(path.join(eng, "video.manifest.json"), JSON.stringify({ ...m, slug: "play-engine-fixture", title: "The Play Engine Fixture" }, null, 2) + "\n");
+ copyFileSync(cachedWindow, path.join(eng, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ }
// A take only a recipe names: never rendered, still playable.
writeFileSync(
path.join(dir, "takes", "recipe.json"),
diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts
@@ -11,6 +11,13 @@ import * as urls from "./urls";
// and an unfetched clip play as placeholders), the reel strip scrubs and
// carries the counter's staircase, a note taken at the playhead (with its
// kind) lists, pins and seeks, and a take plays its own timeline.
+//
+// The clock is the RENDER'S: each clip at its snapped edges (the cut-points
+// route). On vid1's window (silences 2.90-3.11 and 5.92-6.11) c01 plays
+// 1.000-3.082, c02 3.011-6.101, c04 6.007-8.000, so with the 0.2 s
+// crossfades: c01 0-2.082 (shown to 1.982), c02 1.882-4.972 (shown 1.982-
+// 4.872), k01 4.772-6.272 (shown to 6.172), c03 6.072-8.072 (shown to
+// 7.972), c04 7.872-9.865. play-engine.spec.ts covers the edges themselves.
// Screenshots at 1280 and 390 px land in test-results. Fixture:
// e2e/fixtures/play-cut-fixture.mjs.
// ---------------------------------------------------------------------------
@@ -23,6 +30,11 @@ const DIR = path.join(FIXTURE, "reports", "play-cut-fixture");
const root = (page: Page) => page.locator("[data-play-cut]");
const tNow = async (page: Page) => Number(await root(page).getAttribute("data-play-t"));
const rows = (page: Page) => page.locator("[data-play-row]");
+/** Arrived, with the render's edges measured (until then the plan is the manifest's). */
+const ready = async (page: Page) => {
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+};
test.beforeEach(() => {
test.setTimeout(120_000);
@@ -31,21 +43,21 @@ test.beforeEach(() => {
test("the cut plays clip after clip on one clock; prev / next / keys; the strip scrubs; placeholders never stall", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
await page.goto(urls.playHref(PROJECT));
- await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await ready(page);
await expect(rows(page)).toHaveCount(5);
expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "c02", "k01", "c03", "c04"]);
await expect(page.locator('[data-play-row="c03"][data-play-row-missing]')).toHaveCount(1);
await expect(page.locator('[data-play-row="c01"]')).toHaveAttribute("aria-current", "true");
- await expect(page.locator("[data-play-approximate]")).toContainText("hard cut");
+ await expect(page.locator("[data-play-approximate]")).toContainText("edges are the render's, snapped to silence");
// The strip: the section seam before c03 dated by its first dated clip, the counter's staircase and its total.
await expect(page.locator('[data-play-seam-date="c03"]')).toHaveText("27 Feb 2025");
await expect(page.locator("[data-play-staircase] path")).toHaveCount(1);
await expect(page.locator("[data-play-counter-end]")).toHaveText("Seizures 3");
await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 0");
- await expect(page.locator("[data-play-clock]")).toContainText("00:00 / 00:08");
+ await expect(page.locator("[data-play-clock]")).toContainText("00:00 / 00:09");
// Hovering a cell names it: the clip, its recording's date, how long it plays.
await page.locator('[data-play-row="c02"]').hover();
- await expect(page.locator('[data-play-strip-hover="c02"]')).toHaveText("c02 · 2 Dec 2024 · 1.8 s");
+ await expect(page.locator('[data-play-strip-hover="c02"]')).toHaveText("c02 · 2 Dec 2024 · 2.9 s");
await page.locator('[data-play-row="c03"]').hover();
await expect(page.locator('[data-play-strip-hover="c03"]')).toContainText("no media — fetch it");
@@ -53,13 +65,13 @@ test("the cut plays clip after clip on one clock; prev / next / keys; the strip
await page.locator("[data-play-toggle]").click();
await expect(root(page)).toHaveAttribute("data-play-item", "c01");
await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(0.5);
- // ...and carries on into clip 2 (c01 is shown to 1.9 s on the estimate's clock).
+ // ...and carries on into clip 2 (c01 is shown to 1.982 s on the render's clock).
await expect(root(page)).toHaveAttribute("data-play-item", "c02", { timeout: 20_000 });
await expect(page.locator('[data-play-row="c02"]')).toHaveAttribute("aria-current", "true");
await expect
.poll(() => page.locator('video[data-play-slot-item="c02"]').evaluate((v: HTMLVideoElement) => !v.paused && v.readyState >= 2), { timeout: 15_000 })
.toBe(true);
- await expect.poll(() => tNow(page)).toBeGreaterThan(1.9);
+ await expect.poll(() => tNow(page)).toBeGreaterThan(1.982);
// NOW: c02 on the reader, the next entry named.
await expect(page.locator('[data-play-now="c02"]')).toBeVisible();
await expect(page.locator("[data-play-next-up]")).toHaveAttribute("data-play-next-up", "k01");
@@ -70,7 +82,7 @@ test("the cut plays clip after clip on one clock; prev / next / keys; the strip
await page.locator("[data-play-next]").click();
await expect(root(page)).toHaveAttribute("data-play-item", "k01");
await expect(page.locator('[data-play-placeholder="card"]')).toContainText("Between the clips");
- expect(await tNow(page)).toBeCloseTo(3.7, 1);
+ expect(await tNow(page)).toBeCloseTo(4.872, 2);
// The stamp on c02 (k1 at source 4.5) has landed by now: the counter at the playhead says so.
await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 1");
// n: the clip whose source was never fetched -- named, not waited on.
@@ -87,22 +99,23 @@ test("the cut plays clip after clip on one clock; prev / next / keys; the strip
await expect(root(page)).toHaveAttribute("data-play-item", "c03");
await page.locator("[data-play-prev]").click();
await expect(root(page)).toHaveAttribute("data-play-item", "k01");
- // ← is 5 s back: from 3.7, the cut's first second.
+ // ← is 5 s back: from 4.872, the cut's first second.
await page.keyboard.press("ArrowLeft");
await expect(root(page)).toHaveAttribute("data-play-item", "c01");
expect(await tNow(page)).toBe(0);
+ // → is 5 s on: the card's second (it is shown 4.872-6.172).
await page.keyboard.press("ArrowRight");
- await expect(root(page)).toHaveAttribute("data-play-item", "c03");
+ await expect(root(page)).toHaveAttribute("data-play-item", "k01");
expect(await tNow(page)).toBeCloseTo(5, 1);
// A cell's Enter jumps to its start; a click on the strip scrubs to that second.
await page.locator('[data-play-row="c02"]').press("Enter");
await expect(root(page)).toHaveAttribute("data-play-item", "c02");
- expect(await tNow(page)).toBeCloseTo(1.9, 1);
+ expect(await tNow(page)).toBeCloseTo(1.982, 2);
const cells = page.locator("[data-play-cells]");
const box = (await cells.boundingBox())!;
await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2);
await expect(root(page)).toHaveAttribute("data-play-item", "c04");
- expect(Math.abs((await tNow(page)) - 0.9 * 8.7)).toBeLessThan(0.15);
+ expect(Math.abs((await tNow(page)) - 0.9 * 9.865)).toBeLessThan(0.15);
// ? lists the keys; Esc closes it.
await page.keyboard.press("?");
@@ -114,12 +127,13 @@ test("the cut plays clip after clip on one clock; prev / next / keys; the strip
test("a note at the playhead: its kind, the cut second, the clip and its source second; listed, pinned, [ ] and a click seek", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
await page.goto(urls.playHref(PROJECT));
- await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await ready(page);
await expect(page.locator("[data-play-note-list]")).toContainText("Press M while it plays to note this moment.");
await page.locator('[data-play-row="c02"]').press("Enter");
- await page.keyboard.press("ArrowRight"); // 1.9 + 5 = 6.9: c04
+ await page.keyboard.press("ArrowRight"); // 1.982 + 5 = 6.982: c03 (shown to 7.972)
+ await page.keyboard.press("n"); // 7.972: c04's first shown second
await expect(root(page)).toHaveAttribute("data-play-item", "c04");
- await expect(page.locator("[data-play-note-add]")).toHaveText("Note at 00:06.9");
+ await expect(page.locator("[data-play-note-add]")).toHaveText("Note at 00:07.9");
// Paused, the clip's frame is in the picture (the fixture's window is dark green), not a black box.
await expect
.poll(
@@ -134,7 +148,7 @@ test("a note at the playhead: its kind, the cut second, the clip and its source
await page.keyboard.press("m");
const input = page.getByTestId("play-note-input");
await expect(input).toBeFocused();
- await expect(page.locator("[data-play-note-at]")).toHaveAttribute("data-play-note-at", "6.9");
+ await expect(page.locator("[data-play-note-at]")).toHaveAttribute("data-play-note-at", "7.97");
await input.fill("start this one later");
await input.press("Alt+t");
await expect(page.locator('[data-play-ask="trim"]')).toHaveAttribute("aria-pressed", "true");
@@ -142,15 +156,16 @@ test("a note at the playhead: its kind, the cut second, the clip and its source
const note = page.locator("[data-play-note]");
await expect(note).toHaveCount(1);
await expect(note).toContainText("start this one later");
- await expect(note.locator("[data-play-note-seek]")).toHaveText("00:06.9");
+ await expect(note.locator("[data-play-note-seek]")).toHaveText("00:07.9");
await expect(note.locator("[data-play-note-ask]")).toHaveText("trim");
await expect(page.locator("[data-play-pin]")).toHaveCount(1);
await expect(page.locator("[data-play-send-all]")).toHaveText("Send 1 open note to the assistant");
- // Written through the notes store: the cut anchor, the clip, its source second (c04 starts at 6.7: 6.0 + 0.2), the kind.
+ // Written through the notes store: the cut anchor, the clip, its source second (c04's segment starts at 7.872 at
+ // source 6.007, so 7.972 is 6.107), the kind.
const doc = JSON.parse(readFileSync(path.join(DIR, "notes.json"), "utf8"));
const n = doc.notes.find((x: { text: string }) => x.text === "start this one later");
- expect(n.anchor).toEqual({ kind: "cut", t: 6.9, entry: "c04", sourceT: 6.2, ask: "trim" });
+ expect(n.anchor).toEqual({ kind: "cut", t: 7.97, entry: "c04", sourceT: 6.107, ask: "trim" });
expect(n.author).toBe("operator");
// Elsewhere, then ] (the next note) and the note's timecode: back where it was taken.
@@ -158,11 +173,11 @@ test("a note at the playhead: its kind, the cut second, the clip and its source
await expect(root(page)).toHaveAttribute("data-play-item", "c01");
await page.keyboard.press("]");
await expect(root(page)).toHaveAttribute("data-play-item", "c04");
- expect(await tNow(page)).toBeCloseTo(6.9, 1);
+ expect(await tNow(page)).toBeCloseTo(7.972, 2);
await page.locator('[data-play-row="c01"]').press("Enter");
await note.locator("[data-play-note-seek]").click();
await expect(root(page)).toHaveAttribute("data-play-item", "c04");
- expect(await tNow(page)).toBeCloseTo(6.9, 1);
+ expect(await tNow(page)).toBeCloseTo(7.972, 2);
// How it looks: the desk at 1280, the stack at a phone's 390 (no sideways scroll).
await page.setViewportSize({ width: 1280, height: 860 });
@@ -186,25 +201,30 @@ test("a take plays its own timeline (its patch over the project's manifest); a r
await page.goto(urls.takesHref(PROJECT));
await expect(page.locator('a[data-play-take="short"]')).toHaveAttribute("href", urls.playHref(PROJECT, { take: "short" }));
+ // The take's clip comes through the raw route with the take named (whichever path decodes it).
+ const takeMedia = page.waitForRequest((r) => {
+ const u = new URL(r.url());
+ return u.pathname === "/api/report/raw" && u.searchParams.get("clip") === "c01" && u.searchParams.get("take") === "short";
+ });
await page.goto(urls.playHref(PROJECT, { take: "short" }));
await expect(root(page)).toHaveAttribute("data-play-cut", "short");
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
await expect(page.locator('[data-play-take="short"]')).toContainText("take “Short”");
await expect(page.locator('[data-play-take-link="short"]')).toHaveAttribute("aria-current", "page");
await expect(rows(page)).toHaveCount(2);
expect(await rows(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c04", "c01"]);
await page.locator("[data-play-toggle]").click();
await expect(root(page)).toHaveAttribute("data-play-item", "c01", { timeout: 20_000 });
- // The take's clip came through the raw route with the take named.
- const src = await page.locator('video[data-play-slot-item="c01"]').getAttribute("src");
- expect(new URL(String(src), "http://x").searchParams.get("take")).toBe("short");
+ await takeMedia;
await page.keyboard.press("Space");
// The recipe's take: listed, not made, playing the project's timeline with its look.
await page.locator('[data-play-take-link="quick-joins"]').click();
await expect(root(page)).toHaveAttribute("data-play-cut", "quick-joins");
await expect(page.locator('[data-play-take="quick-joins"]')).toContainText("not rendered yet");
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
await expect(rows(page)).toHaveCount(5);
- // A hard-cut look: each entry is its segment, so c02 starts at 2 s, not 1.9.
+ // A hard-cut look: each entry is its segment, so c02 starts where c01's render cut ends (2.082 s), not mid-fade.
await page.locator('[data-play-row="c02"]').press("Enter");
- expect(await tNow(page)).toBeCloseTo(2, 2);
+ expect(await tNow(page)).toBeCloseTo(2.082, 2);
});
diff --git a/umtool/e2e/play-engine.spec.ts b/umtool/e2e/play-engine.spec.ts
@@ -0,0 +1,76 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The Play view plays the render's cut, edges first:
+//
+// - the EDGES are the render's: each clip snapped to its silences by the
+// build's own code (the cut-points route), and the bench draws where
+// the render will cut as a ghost with its offset
+// - an edge moved in the bench is what Play schedules next
+//
+// Fixture: e2e/fixtures/play-cut-fixture.mjs's play-engine-fixture (the
+// play-cut cut, which this spec WRITES). On vid1's window (silences
+// 2.90-3.11, 5.92-6.11) the render cuts c01 at 1.000-3.082, c02 3.011-6.101,
+// c04 6.007-8.000.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = "reports/play-engine-fixture";
+const MANIFEST = path.join(HERE, "..", ".e2e-song", "reports", "play-engine-fixture", "video.manifest.json");
+
+const root = (page: Page) => page.locator("[data-play-cut]");
+const tNow = async (page: Page) => Number(await root(page).getAttribute("data-play-t"));
+type Stats = {
+ scheduled: { id: string; at: number; stop: number; late: number }[];
+ framesDrawn: number;
+ framesOff: number;
+ worstFrames: number;
+ decoders: number;
+ decoded: number;
+ contextTime: number | null;
+ sound: string;
+};
+const stats = (page: Page) => page.evaluate(() => (window as unknown as { __umtoolPlayEngine: { stats: unknown } }).__umtoolPlayEngine.stats as Stats);
+
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+});
+
+test("the render's edges: Play schedules each clip as the build cuts it, and says so", async ({ page }) => {
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ // c01's end snapped into the pause after it; its start had none near.
+ await expect(root(page)).toHaveAttribute("data-play-span", "1-3.082");
+ await page.locator('[data-play-row="c02"]').press("Enter");
+ await expect(root(page)).toHaveAttribute("data-play-span", "3.011-6.101");
+ await expect(page.locator("[data-play-approximate]")).toContainText("edges are the render's, snapped to silence");
+ // The route itself: the silences it snapped on, and which edge moved.
+ const got = await (await page.request.get(`/api/report/cut-points?project=${encodeURIComponent(PROJECT)}`)).json();
+ const c01 = got.clips.find((c: { id: string }) => c.id === "c01");
+ expect(c01).toMatchObject({ cutStart: 1, cutEnd: 3.082, snapped: { start: false, end: true }, playFrom: 1, playTo: 3 });
+ expect(got.clips.find((c: { id: string }) => c.id === "c03")).toEqual({ id: "c03", missing: true });
+});
+
+test("the bench draws where the render will cut; an edge moved there is what Play schedules", async ({ page }) => {
+ await page.goto(urls.clipBenchHref(PROJECT, "c01"));
+ const end = page.locator('[data-render-edge="end"]');
+ const start = page.locator('[data-render-edge="start"]');
+ await expect(end).toHaveAttribute("data-render-offset", "0.082", { timeout: 30_000 });
+ await expect(end).toHaveText("render: +0.08 s");
+ await expect(end).toHaveAttribute("data-render-snapped", "");
+ await expect(start).toHaveText("render: here");
+ // The start moved 0.2 s later (no pause near it: the render cuts where it is drawn), the ghost with it, unsaved.
+ for (let i = 0; i < 4; i += 1) await page.locator("body").press("]");
+ await expect(start).toHaveAttribute("data-render-at", "1.2");
+ await page.locator("[data-save-window]").click();
+ await expect.poll(() => JSON.parse(readFileSync(MANIFEST, "utf8")).timeline.find((e: { id: string }) => e.id === "c01").start).toBe(1.2);
+ // Play schedules the new edge.
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ await expect(root(page)).toHaveAttribute("data-play-span", "1.2-3.082");
+});
diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs
@@ -36,6 +36,7 @@ import { loudnessGain, montageOn, parseIntegratedLoudness } from "umtool-report-
import { loudnessTargetOf } from "umtool-report-to-video/look";
import { ROOM, clipRoom } from "umtool-report-to-video/room";
import { renderCut, snapKnobs } from "umtool-report-to-video/snap";
+import { transitionStyleOf } from "umtool-report-to-video/transition";
import { CACHE_DIR } from "../paths.mjs";
import { channelsDirFor, cuesForSource, hasShadowChannels, readManifest } from "../projects/report.mjs";
@@ -164,7 +165,10 @@ export async function cutPointsFor(project, { take = null, clips = null, concurr
}
};
await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, work));
- return { knobs: snapKnobs(render), transition: D, montage, clips: out };
+ return {
+ knobs: snapKnobs(render), leadIn: fin(render.leadIn) ? render.leadIn : 0.4,
+ transition: D, transitionStyle: transitionStyleOf(render), montage, clips: out,
+ };
}
/** One clip's render cut (cutPointsFor's row). */
@@ -240,6 +244,8 @@ async function clipCutPoints(entry, ctx) {
}
const audio = clipAudioOf(entry);
if (audio) row.audio = audio;
+ // The mute mark (a finale's ending sound): the build fades the sound out to it at the join.
+ if (fin(entry.muteFrom)) row.muteFrom = entry.muteFrom;
return row;
}
diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs
@@ -16,6 +16,18 @@
import { clockText, livePlayWindow } from "./liveClock.mjs";
+// THE RENDER'S EDGES (`cuts`, lib/report/cutPoints.mjs): the build snaps every
+// clip edge to a silence, so the clip it renders is longer or shorter than
+// its play window -- by up to a second at each edge on the Huck cut. Given
+// them, the plan plays each clip from the render's first source second to its
+// last, and every later entry moves by what the clips before it gained or
+// lost: Play's clock is the render's. The chrome was composed on the
+// estimate's clock, so each item keeps its estimate (`est`), and
+// `chromeTime` maps a Play second to the second the pages are seeked to: by
+// SOURCE second inside a clip (a stamp lands on its claim's word, as the
+// render lands it), held at the item's own handover where the render plays
+// more than the estimate did.
+
/** @typedef {{ id: string, start: number, duration: number, hold?: number }} Segment */
/**
* @typedef {{
@@ -23,6 +35,8 @@ import { clockText, livePlayWindow } from "./liveClock.mjs";
* start: number, end: number, the segment, in the cut's seconds
* from: number, to: number, what the page shows of it: midpoint to midpoint
* clip: null | { sourceFrom: number, sourceTo: number, playEnd: number, hold: number },
+ * est?: { start: number, end: number, from: number, to: number, sourceFrom?: number, sourceTo?: number, playEnd?: number },
+ * with the render's edges: the item on the estimate's clock
* }} PlayItem
*/
@@ -30,16 +44,117 @@ const fin = (v) => typeof v === "number" && Number.isFinite(v);
const round = (v) => Math.round(v * 1000) / 1000;
/**
+ * @typedef {{ cutStart: number, cutEnd: number, snapped?: { start: boolean, end: boolean },
+ * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number }} RenderCut
+ */
+
+/**
* The cut as the page plays it: one item per segment, in the cut's order.
* `entries` are the cut's timeline entries (the variant's), matched to the
- * segments by id; a segment with no entry plays as a placeholder.
+ * segments by id; a segment with no entry plays as a placeholder. With
+ * `cuts` (id → the render's cut, cutPoints.mjs), each clip plays the render's
+ * edges and the clock is re-timed by them (see THE RENDER'S EDGES above).
*
* @param {Segment[]} segments
* @param {Array<Record<string, any>>} entries
- * @param {{ leadIn?: number }} [opts]
- * @returns {{ items: PlayItem[], total: number }}
+ * @param {{ leadIn?: number, cuts?: Map<string, RenderCut> | Record<string, RenderCut> | null }} [opts]
+ * @returns {{ items: PlayItem[], total: number, edges: "estimate" | "render" }}
*/
-export function playPlan(segments, entries, { leadIn = 0.4 } = {}) {
+export function playPlan(segments, entries, { leadIn = 0.4, cuts = null } = {}) {
+ const est = estimatePlan(segments, entries, { leadIn });
+ if (!cuts) return est;
+ const cutOf = (id) => (cuts instanceof Map ? cuts.get(id) : cuts[id]) ?? null;
+ let shift = 0;
+ const items = est.items.map((it) => {
+ const before = shift;
+ const c = it.clip ? cutOf(it.id) : null;
+ const ok = !!c && fin(c.cutStart) && fin(c.cutEnd) && c.cutEnd > c.cutStart;
+ const estAt = {
+ start: it.start, end: it.end, from: it.from, to: it.to,
+ ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}),
+ };
+ if (!ok) {
+ return { ...it, start: round(it.start + before), end: round(it.end + before), from: round(it.from + before), to: round(it.to + before),
+ clip: it.clip ? { ...it.clip, playEnd: round(it.clip.playEnd + before) } : null, est: estAt };
+ }
+ const foot = c.cutEnd - c.cutStart;
+ // The estimate's segment is its footage (at least a second) and its hold; the render's, its cut and the same hold.
+ const delta = foot + it.clip.hold - (it.end - it.start);
+ shift += delta;
+ const start = round(it.start + before);
+ return {
+ ...it,
+ start,
+ end: round(it.end + before + delta),
+ from: round(it.from + before),
+ to: round(it.to + before + delta),
+ clip: {
+ sourceFrom: c.cutStart, sourceTo: c.cutEnd, playEnd: round(start + foot), hold: it.clip.hold,
+ ...(Array.isArray(c.sound) ? { sound: c.sound } : {}),
+ ...(fin(c.gainDb) ? { gainDb: c.gainDb } : {}),
+ ...(c.audio ? { audio: c.audio } : {}),
+ ...(c.snapped ? { snapped: c.snapped } : {}),
+ ...(fin(c.muteFrom) ? { muteFrom: c.muteFrom } : {}),
+ },
+ est: estAt,
+ };
+ });
+ return { items, total: items.length ? items[items.length - 1].end : 0, edges: "render" };
+}
+
+/**
+ * The second the chrome (composed on the estimate's clock) is seeked to at
+ * Play's second t: t itself on a plan with no render edges; inside a clip,
+ * the estimate's second for the SOURCE second playing (clamped into the
+ * item's own share of the estimate, so the deck hands over at Play's join);
+ * in a hold, its last frame's second on; a card, its own second.
+ *
+ * @param {{ items: Array<PlayItem & { est?: Record<string, number> }> }} plan
+ * @param {number} t
+ */
+export function chromeTime(plan, t) {
+ const i = itemIndexAt(plan, t);
+ const it = plan?.items?.[i];
+ const e = it?.est;
+ if (!it || !e || !fin(t)) return t;
+ const clampTo = (v, lo, hi) => round(Math.min(hi, Math.max(lo, v)));
+ if (it.clip && fin(e.sourceFrom)) {
+ if (t > it.clip.playEnd) return clampTo(e.playEnd + (t - it.clip.playEnd), e.from, e.to);
+ const src = /** @type {number} */ (sourceAt(it, t));
+ return clampTo(e.start + (src - e.sourceFrom), e.from, it.clip.hold > 0 ? e.playEnd : e.to);
+ }
+ return clampTo(e.from + (t - it.from), e.from, e.to);
+}
+
+/**
+ * The inverse, for what the estimate places (a stamp's `landed`, the
+ * counter's steps): the Play second the estimate's second `tc` shows.
+ *
+ * @param {{ items: Array<PlayItem & { est?: Record<string, number> }> }} plan
+ * @param {number} tc
+ */
+export function playTimeOfChrome(plan, tc) {
+ const items = plan?.items ?? [];
+ if (!items.length || !items[0].est || !fin(tc)) return tc;
+ let k = 0;
+ for (let i = items.length - 1; i >= 0; i -= 1) {
+ if (tc >= /** @type {number} */ (items[i].est?.from)) {
+ k = i;
+ break;
+ }
+ }
+ const it = items[k];
+ const e = /** @type {Record<string, number>} */ (it.est);
+ const clampTo = (v) => round(Math.min(it.to, Math.max(it.from, v)));
+ if (it.clip && fin(e.sourceFrom)) {
+ if (tc > e.playEnd) return clampTo(it.clip.playEnd + (tc - e.playEnd));
+ return clampTo(cutAtSource(it, e.sourceFrom + (tc - e.start)));
+ }
+ return clampTo(it.from + (tc - e.from));
+}
+
+/** The plan on the estimate's clock alone (playPlan without the render's edges). */
+function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) {
const byId = new Map((entries ?? []).map((e) => [e?.id, e]));
const segs = (segments ?? []).filter((s) => s && fin(s.start) && fin(s.duration));
const items = segs.map((s, i) => {
@@ -59,7 +174,7 @@ export function playPlan(segments, entries, { leadIn = 0.4 } = {}) {
return { id: s.id, index: i, type: String(e?.type ?? "entry"), start: round(s.start), end: round(end), from: round(from), to: round(to), clip };
});
const total = items.length ? items[items.length - 1].end : 0;
- return { items, total: round(total) };
+ return { items, total: round(total), edges: /** @type {"estimate" | "render"} */ ("estimate") };
}
/** The item on screen at cut second t (the last whose `from` ≤ t); -1 for an empty plan. */
diff --git a/umtool/lib/report/playCut.test.mjs b/umtool/lib/report/playCut.test.mjs
@@ -10,7 +10,7 @@ import test from "node:test";
import { estimateSchedule } from "umtool-report-to-video/deck";
import { liveClock, cutTimeAt } from "./liveClock.mjs";
import {
- counterAt, counterSteps, cutAtSource, cutNotesRequest, cutPlace, dateKeyLabel, dateRamp, inHold, itemIndexAt, playPlan, rulerTicks,
+ chromeTime, counterAt, counterSteps, cutAtSource, cutNotesRequest, cutPlace, dateKeyLabel, dateRamp, inHold, itemIndexAt, playPlan, playTimeOfChrome, rulerTicks,
runningTime, seamsOf, shownSeconds, sourceAt, startOf,
} from "./playCut.mjs";
@@ -174,3 +174,52 @@ test("the reel strip: the date ramp, the seams, the counter's staircase, the rul
assert.equal(dateKeyLabel(20250227), "27 Feb 2025");
assert.equal(dateKeyLabel(null), null);
});
+
+test("the render's edges: each clip plays its snapped cut, and every later entry moves by what it gained", () => {
+ const m = manifest(0.5);
+ const segs = estimateSchedule(m).segments;
+ const est = playPlan(segs, m.timeline);
+ // a: snapped 0.5 s earlier at its start and 0.3 s later at its end (+0.8 s); b: its end 0.2 s earlier (-0.2 s).
+ const cuts = { a: { cutStart: 9.5, cutEnd: 14.3, gainDb: -2 }, b: { cutStart: 103.6, cutEnd: 107.8, snapped: { start: false, end: true } } };
+ const plan = playPlan(segs, m.timeline, { cuts });
+ assert.equal(plan.edges, "render");
+ assert.equal(est.edges, "estimate");
+ const [a, b, k, c] = plan.items;
+ assert.deepEqual([a.start, a.end], [0, 4.8]);
+ assert.deepEqual(a.clip, { sourceFrom: 9.5, sourceTo: 14.3, playEnd: 4.8, hold: 0, gainDb: -2 });
+ // b starts 0.8 later, lasts 0.2 less; the overlap with a is the crossfade's, unchanged.
+ assert.deepEqual([b.start, b.end, b.from], [4.3, 8.5, 4.55]);
+ assert.equal(b.clip.playEnd, 8.5);
+ // The card and c move by both: +0.6.
+ assert.deepEqual([k.start, c.start], [8, 10.5]);
+ assert.equal(plan.total, round3(est.total + 0.6));
+ assert.equal(c.clip.sourceFrom, 50);
+ // The items still tile the cut.
+ assert.equal(round3(plan.items.reduce((n, i) => n + shownSeconds(i), 0)), plan.total);
+ // The source second at a Play second, and back.
+ assert.equal(sourceAt(a, 0), 9.5);
+ assert.equal(cutAtSource(b, 105), round3(4.3 + 105 - 103.6));
+});
+
+test("the chrome's second: by source second inside a clip, held at the item's own handover, a card's own", () => {
+ const m = manifest(0.5);
+ const segs = estimateSchedule(m).segments;
+ const est = playPlan(segs, m.timeline);
+ const plan = playPlan(segs, m.timeline, { cuts: { a: { cutStart: 9.5, cutEnd: 14.3 } } });
+ // Without render edges, the identity.
+ assert.equal(chromeTime(est, 2.2), 2.2);
+ // a's extra head (source 9.5..10, before the estimate's window) holds at a's first second.
+ assert.equal(chromeTime(plan, 0.2), 0);
+ // Source 12 plays at Play 2.5; the estimate placed it at 2.
+ assert.equal(chromeTime(plan, 2.5), 2);
+ // a's extra tail holds just before the handover (the estimate's 3.75).
+ assert.equal(chromeTime(plan, 4.5), 3.75);
+ // b is the estimate shifted: source 105 at Play 4.3 + 1.4 is the estimate's 3.5 + 1.4.
+ assert.equal(chromeTime(plan, 5.7), 4.9);
+ // A stamp the estimate lands at 4.9 (b's source 105) lands at Play 5.7; one in a's held tail at the estimate's last second of a.
+ assert.equal(playTimeOfChrome(plan, 4.9), 5.7);
+ assert.equal(playTimeOfChrome(plan, 2), 2.5);
+ assert.equal(playTimeOfChrome(est, 4.9), 4.9);
+});
+
+const round3 = (v) => Math.round(v * 1000) / 1000;