commit fb7c3588fbca56ed84a7411cdb086eb972a1d3db
parent f60c232a6d75648dbf84e3e1548d3c2ae885ec45
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 24 Oct 2026 06:11:14 -0400
Merge lane/play-engine: Play the cut plays like the render (the render's own cut points from one shared snap module, the sound on one Web Audio clock with the cut's crossfades and loudness, the picture by WebCodecs with real dissolves; ghost edges in the bench and on the phone strip)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
32 files changed, 3946 insertions(+), 602 deletions(-)
diff --git a/umtool/app/api/report/audio/route.ts b/umtool/app/api/report/audio/route.ts
@@ -31,7 +31,10 @@ const CHANNELS = 2;
export async function GET(request: Request) {
const url = new URL(request.url);
- const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "");
+ // `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,
+ });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const windows = await windowsFor(r.project, r.clip);
diff --git a/umtool/app/api/report/cut-points/route.ts b/umtool/app/api/report/cut-points/route.ts
@@ -0,0 +1,30 @@
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
+import { walkProjects } from "@/lib/projects/walk.mjs";
+import { cutPointsFor } from "@/lib/report/cutPoints.mjs";
+
+export const dynamic = "force-dynamic";
+
+// Where the render will cut each clip (lib/report/cutPoints.mjs): the build's
+// own source resolution, silence detection and snap, cached on disk, so the
+// Play view plays the render's edges and the clip bench draws them.
+//
+// GET ?project[&take][&clip=<id>...] every clip of the cut (or the named
+// ones): { knobs, transition, montage, clips }
+//
+// Nothing is fetched and nothing in the project is written; the first read
+// of a clip measures its source (two ffmpeg passes over the clip and its pad),
+// every later one is read from the cache.
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const projectId = url.searchParams.get("project") ?? "";
+ const take = url.searchParams.get("take") || null;
+ const clips = url.searchParams.getAll("clip").filter(Boolean);
+ const project = (await walkProjects(REPORTS_ROOT)).find((p: { id: string }) => p.id === projectId);
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ try {
+ const got = await cutPointsFor(project, { take, clips: clips.length ? clips : null });
+ return Response.json(got, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 422 });
+ }
+}
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, { useRenderEdges } 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.
@@ -465,6 +466,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const [proposed, setProposed] = useState(data.proposed);
const [view, setView] = useState(data.view);
const [sel, setSel] = useState({ from: data.clip.start, to: data.clip.end });
+ // Where the render will actually cut the drafted selection (bench/RenderGhosts.tsx): the
+ // desk's waveform and the phone's edge strip both draw it.
+ const renderEdges = useRenderEdges(data.project, clip, sel);
// The mute mark as drafted. Like the edges it is unsaved until `save window`
// or `y`, and it is what the bench's own playback mutes at -- so a mark is
// heard before it is written.
@@ -2579,6 +2583,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
busy={!!busy}
fmt={hms}
onSel={onSel}
+ render={renderEdges}
onFetch={(edge, t) =>
void fetchMore(
edge === "end"
@@ -3184,6 +3189,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
</div>
</>
)}
+ {/* Where the render will actually cut: each edge snapped to its silence, faint. */}
+ <RenderGhosts edges={renderEdges} view={view} />
{/* Armed: the next click places the mark rather than an edge. */}
{mutePick && (
<div
diff --git a/umtool/components/projects/bench/EdgeStrip.tsx b/umtool/components/projects/bench/EdgeStrip.tsx
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { Peaks } from "@/components/Waveform";
import { usePalette } from "@/components/ui/use-palette";
import { cn } from "@/lib/utils";
+import { ghostLabel, type RenderEdges } from "./RenderGhosts";
import {
SNAP_RADIUS,
sentenceBoundaries,
@@ -57,6 +58,7 @@ export default function EdgeStrip({
fmt,
onSel,
onFetch,
+ render = null,
className,
}: {
/** The cached window, which the waveform spans. */
@@ -73,6 +75,8 @@ export default function EdgeStrip({
onSel: (next: { from: number; to: number }, dragging: boolean, edge: Edge) => void;
/** Fetch far enough to put `t` inside the cache, on `edge`'s side. */
onFetch: (edge: Edge, t: number) => void;
+ /** Where the render will cut (RenderGhosts.tsx useRenderEdges): a faint line on the waveform, its offset under each edge. */
+ render?: RenderEdges;
className?: string;
}) {
const pal = usePalette();
@@ -300,6 +304,18 @@ export default function EdgeStrip({
{playhead != null && inView(playhead) && (
<div aria-hidden className="pointer-events-none absolute inset-y-0 w-px bg-text" style={{ left: pct(playhead) }} />
)}
+ {render &&
+ (["start", "end"] as const).map((edge) =>
+ inView(render[edge].at) ? (
+ <div
+ key={`render-${edge}`}
+ aria-hidden
+ data-strip-render-edge={edge}
+ className="pointer-events-none absolute inset-y-0 border-l border-dotted border-[color-mix(in_srgb,var(--color-text)_45%,transparent)]"
+ style={{ left: pct(render[edge].at) }}
+ />
+ ) : null,
+ )}
</div>
{(["start", "end"] as const).map((edge) => {
const t = edge === "start" ? sel.from : sel.to;
@@ -350,6 +366,11 @@ export default function EdgeStrip({
<span className="text-center text-[12px] text-muted-2">
{edge}
<span className="block font-mono text-[11.5px] text-text-2">{fmt(edge === "start" ? sel.from : sel.to)}</span>
+ {render && (
+ <span className="block font-mono text-[10.5px] text-muted" data-strip-render-offset={render[edge].offset}>
+ {ghostLabel(render[edge])}
+ </span>
+ )}
</span>
<button type="button" data-edge-step={`${edge}-on`} disabled={busy || !on} onClick={() => step(edge, 1)} className={stepBtn}>
sentence ›
diff --git a/umtool/components/projects/bench/RenderGhosts.tsx b/umtool/components/projects/bench/RenderGhosts.tsx
@@ -0,0 +1,119 @@
+"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,
+ };
+}
+
+/** One edge as the render will cut it: where (source s), how far from the edge drawn, and whether a silence moved it. */
+export type GhostEdge = { at: number; offset: number; snapped: boolean };
+export type RenderEdges = { start: GhostEdge; end: GhostEdge } | null;
+
+/** "render: +0.52 s" (or "render: here"): a ghost's words. */
+export const ghostLabel = (g: GhostEdge) =>
+ Math.abs(g.offset) < 0.005 ? "render: here" : `render: ${g.offset > 0 ? "+" : "−"}${Math.abs(g.offset).toFixed(2)} s`;
+
+/**
+ * Where the render will cut this clip's drafted selection: the silences
+ * measured once per saved extent (the cut-points route), snapped here on
+ * every drag. null until measured, or when the route cannot say (no source on
+ * disk, a montage's phrase cut).
+ */
+export function useRenderEdges(
+ project: string,
+ clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null },
+ sel: { from: number; to: number },
+): RenderEdges {
+ 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 (!got || !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 });
+ return {
+ start: { at: cut.start, offset: Number((cut.start - pw.from).toFixed(3)), snapped: cut.snapped.start },
+ end: { at: cut.end, offset: Number((cut.end - pw.to).toFixed(3)), snapped: cut.snapped.end },
+ };
+}
+
+/** The ghosts over the desk's waveform: a faint line at each edge the render cuts at, with its offset. */
+export default function RenderGhosts({ edges, view }: { edges: RenderEdges; view: { from: number; to: number } }) {
+ if (!edges) return null;
+ const span = Math.max(1e-6, view.to - view.from);
+ const pct = (t: number) => `${((t - view.from) / span) * 100}%`;
+ return (
+ <>
+ {(["start", "end"] as const).map((edge) => {
+ const g = edges[edge];
+ if (g.at < view.from || g.at > view.to) return null;
+ const label = ghostLabel(g);
+ return (
+ <div
+ key={edge}
+ data-render-edge={edge}
+ data-render-at={g.at}
+ data-render-offset={g.offset}
+ 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 ${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,13 +12,14 @@ 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, 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";
import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from "../report/AssistBox";
import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
-import { drawFootage, type FootageBlur } from "./footageCanvas";
+import { usePlayEngine } from "./playEngine/usePlayEngine";
+import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
+import type { EngineInfo } from "./playEngine/engine";
import ReelStrip, { type StripCounter } from "./ReelStrip";
// ---------------------------------------------------------------------------
@@ -29,16 +30,20 @@ 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
-// 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.
-// 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
-// card, a hold or a clip with no media on disk advance it by the wall clock.
+// 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).
//
-// TWO <video> elements: the one playing and the next clip's, loaded and
-// seeked to its first shown second while this one plays, swapped at the cut.
+// THE ENGINE (playEngine/engine.ts): the sound decoded and scheduled on ONE
+// Web Audio clock, sample-exact at the render's edges, the crossfades as the
+// build's ramps, the loudness gain and room as gain automation; the clock of
+// the whole view is that context's time mapped through the plan, and the
+// chrome is seeked by the source second playing (chromeTime), so the rail,
+// the tally, the stamps and the finale land as the render lands them. The
+// picture follows the clock: WebCodecs where the browser has it (decoded
+// ahead, a real dissolve), else the two <video> elements slaved to it.
//
// THE CHROME is the live preview's (LiveDeckPreview.tsx): the build's own
// pages composed from the estimate (POST /api/report/chrome/preview,
@@ -156,8 +161,35 @@ 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, and which engine is playing: the
+ * line under the picture. The edges, the sound and the picture say what is
+ * true now (the render's edges once measured; Web Audio or the element's own
+ * sound; WebCodecs or <video>).
+ */
+function approximateLine(edges: RenderCuts, info: EngineInfo | null) {
+ 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"})`;
+ const sound = !info
+ ? "sound: not started"
+ : info.sound === "webaudio"
+ ? "sound: Web Audio, on one clock (the render's crossfades, loudness and room; no limiter)"
+ : "sound: each recording's own, from its element (no Web Audio here)";
+ const picture = !info ? "" : info.picture === "webcodecs" ? "picture: WebCodecs" : info.picture === "mixed" ? "picture: WebCodecs, some clips on <video>" : "picture: <video>";
+ const silent = info ? Object.keys(info.silent) : [];
+ return [
+ "Approximate: cards and teasers are placeholders, a push or a wipe is drawn as a dissolve, the chrome is composed on the estimate's clock;",
+ `${edge};`,
+ `${sound}${picture ? `; ${picture}` : ""}.`,
+ silent.length ? `No sound decoded for ${silent.join(", ")}.` : "",
+ ].filter(Boolean).join(" ");
+}
/** The pinned player as a strip, once the transport is under it (a phone). */
const STRIP_H = 120;
@@ -219,153 +251,36 @@ 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;
- const entryRef = useRef(entryOf);
- entryRef.current = entryOf;
- // ---- the engine ----------------------------------------------------------------
- const vA = useRef<HTMLVideoElement | null>(null);
- const vB = useRef<HTMLVideoElement | null>(null);
- const canvas = useRef<HTMLCanvasElement | null>(null);
- const slotEl = useCallback((k: number) => (k === 0 ? vA.current : vB.current), []);
- const eng = useRef({ t: 0, cur: 0, playing: false, ended: false, rate: 1, last: 0, active: 0, held: [-1, -1] as number[], failed: new Set<string>(), waiting: false });
- const [ui, setUi] = useState<Ui>({ t: 0, cur: 0, playing: false, ended: false, waiting: false });
- const [rate, setRate] = useState(1);
- const [failed, setFailed] = useState<Record<string, string>>({});
+ // ---- the engine (playEngine/: the sound on one Web Audio clock, the picture slaved to it) ----
const bg = doc?.background ?? "#000";
- const bgRef = useRef(bg);
- bgRef.current = bg;
-
const srcOf = useCallback(
(id: string, file: string) => `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file }).toString()}`,
[project, take],
);
- const hasVideo = useCallback((i: number) => {
- const item = planRef.current.items[i];
- const e = item ? entryRef.current.get(item.id) : null;
- return !!item?.clip && !!e?.media && !eng.current.failed.has(item.id);
- }, []);
-
- /** Put item i's media in a slot, at the source second cut second t shows. */
- const load = useCallback(
- (slot: number, i: number, t: number) => {
- const item = planRef.current.items[i];
- const e = item ? entryRef.current.get(item.id) : null;
- const v = slotEl(slot);
- if (!v || !item?.clip || !e?.media) return;
- const want = Math.max(0, (sourceAt(item, t) ?? item.clip.sourceFrom) - e.media.from);
- const url = srcOf(item.id, e.media.name);
- if (eng.current.held[slot] !== i || v.getAttribute("src") !== url) {
- v.setAttribute("src", url);
- v.dataset.playSlotItem = item.id;
- eng.current.held[slot] = i;
- }
- v.playbackRate = eng.current.rate;
- v.preservesPitch = true;
- const seek = () => {
- try {
- v.currentTime = want;
- } catch {
- // Not seekable yet: the metadata listener seeks.
- }
- };
- if (v.readyState >= 1) seek();
- else v.addEventListener("loadedmetadata", seek, { once: true });
- },
- [slotEl, srcOf],
- );
-
- /** Make item i the one on screen at cut second t, and load the next clip behind it. */
- const enter = useCallback(
- (i: number, t: number) => {
- const e = eng.current;
- const items = planRef.current.items;
- if (!items.length) return;
- e.cur = Math.max(0, Math.min(i, items.length - 1));
- e.t = t;
- if (hasVideo(e.cur)) {
- const other = 1 - e.active;
- const slot = e.held[e.active] === e.cur ? e.active : e.held[other] === e.cur ? other : e.active;
- if (slot !== e.active) {
- slotEl(e.active)?.pause();
- e.active = slot;
- }
- load(slot, e.cur, t);
- if (e.playing) void slotEl(slot)?.play().catch(() => {});
- } else {
- vA.current?.pause();
- vB.current?.pause();
- }
- // The next clip with media, ready behind this one before the cut.
- for (let j = e.cur + 1; j < items.length; j += 1) {
- if (!hasVideo(j)) continue;
- if (e.held[e.active] !== j) {
- load(1 - e.active, j, items[j].from);
- slotEl(1 - e.active)?.pause();
- }
- break;
- }
- },
- [hasVideo, load, slotEl],
- );
-
- const publish = useCallback(() => {
- const e = eng.current;
- setUi((u) =>
- Math.abs(u.t - e.t) > 1 / 30 || u.cur !== e.cur || u.playing !== e.playing || u.ended !== e.ended || u.waiting !== e.waiting
- ? { t: Math.round(e.t * 1000) / 1000, cur: e.cur, playing: e.playing, ended: e.ended, waiting: e.waiting }
- : u,
- );
- }, []);
-
- const seekTo = useCallback(
- (t: number) => {
- const p = planRef.current;
- const e = eng.current;
- const at = Math.max(0, Math.min(t, Math.max(0, p.total - 0.001)));
- e.ended = false;
- e.last = 0;
- enter(itemIndexAt(p, at), at);
- publish();
- },
- [enter, publish],
- );
-
- const setPlaying = useCallback(
- (on: boolean) => {
- const e = eng.current;
- if (on && e.ended) {
- e.ended = false;
- enter(0, 0);
- }
- e.playing = on;
- e.last = 0;
- const v = slotEl(e.active);
- if (on && hasVideo(e.cur) && e.held[e.active] === e.cur) void v?.play().catch(() => {});
- if (!on) {
- vA.current?.pause();
- vB.current?.pause();
- }
- publish();
- },
- [enter, hasVideo, publish, slotEl],
+ const audioOf = useCallback(
+ (id: string, file: string, from: number, to: number) =>
+ `/api/report/audio?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file, from: String(from), to: String(to) }).toString()}`,
+ [project, take],
);
+ const engine = usePlayEngine({ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style });
+ const { ui, rate, failed, seekTo, setPlaying, now } = engine;
+ const setRate = engine.setRate;
- // The first entry loaded on arrival; the plan changing (the composed
- // schedule replacing the estimate's segments) re-places the current second.
- useEffect(() => {
- const e = eng.current;
- enter(itemIndexAt(plan, e.t), e.t);
- 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,101 +290,17 @@ 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]);
-
- useEffect(() => {
- eng.current.rate = rate;
- for (const v of [vA.current, vB.current]) if (v) v.playbackRate = rate;
- }, [rate]);
-
- // A slot's media that will not play (gone, refused): that clip plays as a placeholder.
- const onMediaError = useCallback(
- (slot: number) => {
- const e = eng.current;
- const i = e.held[slot];
- const item = planRef.current.items[i];
- if (!item) return;
- e.failed.add(item.id);
- e.held[slot] = -1;
- setFailed((f) => ({ ...f, [item.id]: "the media did not load" }));
- },
- [],
- );
-
- // Every animation frame: the clock, the cut to the next entry, the picture.
- const lastDraw = useRef<{ key: string; el: HTMLCanvasElement | null }>({ key: "", el: null });
- useEffect(() => {
- let raf = 0;
- const tick = (now: number) => {
- raf = requestAnimationFrame(tick);
- const e = eng.current;
- const p = planRef.current;
- const items = p.items;
- if (!items.length) return;
- const dt = e.last ? Math.min(0.25, (now - e.last) / 1000) : 0;
- e.last = now;
- let item = items[e.cur];
- const ent = entryRef.current.get(item.id);
- const v = slotEl(e.active);
- const playingVideo = hasVideo(e.cur) && !!v && !!ent?.media && e.held[e.active] === e.cur;
- e.waiting = false;
- if (e.playing) {
- if (playingVideo && v && ent?.media && item.clip) {
- const src = ent.media.from + v.currentTime;
- if (src >= item.clip.sourceTo - 0.01 || v.ended) {
- // Past the footage (a carrying clip's hold): its last frame, the wall clock.
- if (!v.paused) v.pause();
- e.t += dt * e.rate;
- } else if (v.readyState >= 2 && !v.seeking) {
- if (v.paused) void v.play().catch(() => {});
- e.t = cutAtSource(item, src);
- } else e.waiting = true; // buffering: the clock waits for the picture
- } else e.t += dt * e.rate;
- if (e.t >= item.to - 0.001) {
- if (e.cur + 1 < items.length) {
- enter(e.cur + 1, item.to);
- item = items[e.cur];
- } else {
- e.t = p.total;
- e.playing = false;
- e.ended = true;
- vA.current?.pause();
- vB.current?.pause();
- }
- }
- }
- publish();
-
- // The picture: the playing clip's frame in the footage box, blurred as the build blurs it.
- const el = canvas.current;
- if (!el) return;
- const cur = items[e.cur];
- const ce = entryRef.current.get(cur.id);
- const pv = hasVideo(e.cur) && e.held[e.active] === e.cur ? slotEl(e.active) : null;
- const video = pv && pv.readyState >= 2 && pv.videoWidth > 0 ? pv : null;
- const src = video && ce?.media ? ce.media.from + video.currentTime : null;
- const b = ce?.blur && view.blurRendered ? ce.blur : null;
- const blurNow: FootageBlur =
- b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity)
- ? { strength: b.strength ?? BLUR_STRENGTH.default, caption: b.caption ?? BLUR_CAPTION_DEFAULT }
- : null;
- const key = `${cur.id}|${video ? video.currentTime : -1}|${bgRef.current}|${el.width}x${el.height}|${blurNow ? `${blurNow.strength}${blurNow.caption}` : ""}`;
- // A new canvas (the composed frame replacing the plain one) is drawn even while nothing moves.
- if (key === lastDraw.current.key && el === lastDraw.current.el) return;
- lastDraw.current = { key, el };
- el.dataset.playBlur = blurNow ? "on" : "off";
- drawFootage(el, video, bgRef.current, blurNow);
- };
- raf = requestAnimationFrame(tick);
- return () => cancelAnimationFrame(raf);
- }, [enter, hasVideo, publish, slotEl, view.blurRendered]);
+ 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]);
// ---- the controls ----------------------------------------------------------------
- const next = useCallback(() => seekTo(startOf(planRef.current, eng.current.cur + 1)), [seekTo]);
- const prev = useCallback(() => seekTo(startOf(planRef.current, eng.current.cur - 1)), [seekTo]);
- const skip = useCallback((d: number) => seekTo(eng.current.t + d), [seekTo]);
+ const next = useCallback(() => seekTo(startOf(planRef.current, now().cur + 1)), [seekTo, now]);
+ const prev = useCallback(() => seekTo(startOf(planRef.current, now().cur - 1)), [seekTo, now]);
+ const skip = useCallback((d: number) => seekTo(now().t + d), [seekTo, now]);
const changeRate = useCallback((r: number) => setRate(r), []);
// J tapped again within a moment steps further back each time (there is no true reverse).
const jTap = useRef({ at: 0, step: SKIP_S });
@@ -480,13 +311,13 @@ export default function PlayCut({
skip(-jTap.current.step);
}, [skip]);
const lPlay = useCallback(() => {
- if (!eng.current.playing) {
+ if (!now().playing) {
setPlaying(true);
return;
}
- const up = L_RATES.find((r) => r > eng.current.rate + 1e-6);
+ const up = L_RATES.find((r) => r > now().rate + 1e-6);
if (up) changeRate(up);
- }, [setPlaying, changeRate]);
+ }, [setPlaying, changeRate, now]);
// ---- the notes -------------------------------------------------------------------
const notes = useSharedNotes({ project });
@@ -494,6 +325,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(() => {
@@ -505,7 +342,7 @@ export default function PlayCut({
}, []);
const resumeAfter = useRef(false);
const noteHere = useCallback(() => {
- const e = eng.current;
+ const e = now();
const item = planRef.current.items[e.cur];
if (!item) return;
resumeAfter.current = false;
@@ -515,7 +352,7 @@ export default function PlayCut({
}
const src = item.clip ? sourceAt(item, e.t) : null;
setDrafting({ kind: "cut", t: Math.round(e.t * 100) / 100, entry: item.id, ...(src !== null ? { sourceT: src } : {}), ...(take ? { take } : {}) });
- }, [pauseWhileWriting, setPlaying, take]);
+ }, [pauseWhileWriting, setPlaying, take, now]);
const closeDraft = useCallback(() => {
setDrafting(null);
if (resumeAfter.current) {
@@ -525,12 +362,12 @@ export default function PlayCut({
}, [setPlaying]);
const stepNote = useCallback(
(d: 1 | -1) => {
- const t = eng.current.t;
- const ts = mine.map((n) => (n.anchor as CutAnchor).t);
+ const t = now().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, now, noteT],
);
// `?note=<id>` (the Inbox's link): seek to it once the notes are read.
@@ -540,16 +377,16 @@ 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(() => {
- const e = eng.current;
+ const e = now();
const it = planRef.current.items[e.cur];
if (!it?.clip) return null;
return clipBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100, take } });
- }, [project, take]);
+ }, [project, take, now]);
const editHere = useCallback(() => {
const h = editHref();
if (!h) return;
@@ -568,7 +405,7 @@ export default function PlayCut({
}
if (tgt && (tgt.closest("input, textarea, select, [contenteditable=true]") || ev.metaKey || ev.ctrlKey || ev.altKey)) return;
const k = ev.key;
- if (k === " ") setPlaying(!eng.current.playing);
+ if (k === " ") setPlaying(!now().playing);
else if (k === "j" || k === "J") back();
else if (k === "k" || k === "K") setPlaying(false);
else if (k === "l" || k === "L") lPlay();
@@ -595,21 +432,23 @@ export default function PlayCut({
window.removeEventListener("keydown", onKey);
window.removeEventListener("keyup", onUp);
};
- }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying]);
+ }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now]);
// ---- 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 +459,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 ? (
@@ -697,7 +538,7 @@ export default function PlayCut({
const dockBtn = cn(buttonVariants({ variant: "outline", size: "md" }), "h-12 min-w-0 px-1 text-[13px]");
const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
- <canvas ref={canvas} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
+ <canvas ref={engine.canvasRef} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
);
const iconBtn = cn(buttonVariants({ variant: "outline", size: "sm" }), "min-w-9 font-mono");
@@ -707,11 +548,17 @@ 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}
+ data-play-sound={engine.info?.sound ?? ""}
+ data-play-picture={engine.info?.picture ?? ""}
+ // 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 ---- */}
@@ -768,21 +615,21 @@ export default function PlayCut({
}
>
<div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
- <video ref={vA} data-play-slot="0" preload="auto" playsInline onError={() => onMediaError(0)} className="absolute inset-0 h-full w-full" />
- <video ref={vB} data-play-slot="1" preload="auto" playsInline onError={() => onMediaError(1)} className="absolute inset-0 h-full w-full" />
+ <video ref={engine.slotRef0} data-play-slot="0" preload="auto" playsInline muted onError={() => engine.onMediaError(0)} className="absolute inset-0 h-full w-full" />
+ <video ref={engine.slotRef1} data-play-slot="1" preload="auto" playsInline muted onError={() => engine.onMediaError(1)} className="absolute inset-0 h-full w-full" />
</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 +740,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, engine.info)}
{!view.blurRendered ? " Blurred clips play unblurred (render.blur off)." : ""}
{view.note ? ` ${view.note}.` : ""}
</span>
@@ -937,7 +784,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/footageCanvas.ts b/umtool/components/projects/review/footageCanvas.ts
@@ -7,33 +7,58 @@ import { blurCaptionLayout } from "umtool-report-to-video/clip-blur";
// through the canvas's own Gaussian -- the build's sigma, its strength as a %
// of the picture's height -- with its caption laid out by the build's own
// blurCaptionLayout (top centre, one box a line). No second decode: the
-// element that plays is the element drawn.
+// element that plays (or the frame the Play view's engine decoded) is the
+// picture drawn; a dissolve is two layers, the incoming at its progress.
/** The blur on screen now: its strength (% of the picture's height) and its caption; null when none. */
export type FootageBlur = { strength: number; caption: string } | null;
+/**
+ * One picture to draw: an element or a decoded frame (WebCodecs' VideoFrame,
+ * the Play view's engine), its size, how opaque (a dissolve draws the
+ * incoming clip over the outgoing at its progress), and its blur.
+ */
+export type FootageLayer = { source: CanvasImageSource; width: number; height: number; alpha: number; blur: FootageBlur };
+
export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | null, bg: string, blur: FootageBlur) {
+ drawFootageLayers(el, video ? [{ source: video, width: video.videoWidth, height: video.videoHeight, alpha: 1, blur }] : [], bg);
+}
+
+/** The footage box's ground, then each layer in order, fitted, at its alpha, blurred as the build blurs it. */
+export function drawFootageLayers(el: HTMLCanvasElement, layers: FootageLayer[], bg: string) {
const ctx = el.getContext("2d");
if (!ctx) return;
+ ctx.globalAlpha = 1;
ctx.fillStyle = bg;
ctx.fillRect(0, 0, el.width, el.height);
- if (!video) return;
- const k = Math.min(el.width / video.videoWidth, el.height / video.videoHeight);
- const w = video.videoWidth * k;
- const hh = video.videoHeight * k;
+ for (const layer of layers) {
+ if (!(layer.width > 0 && layer.height > 0) || !(layer.alpha > 0)) continue;
+ ctx.save();
+ ctx.globalAlpha = Math.min(1, layer.alpha);
+ drawOne(ctx, el, layer, bg);
+ ctx.restore();
+ }
+}
+
+function drawOne(ctx: CanvasRenderingContext2D, el: HTMLCanvasElement, layer: FootageLayer, bg: string) {
+ const { source, blur } = layer;
+ const k = Math.min(el.width / layer.width, el.height / layer.height);
+ const w = layer.width * k;
+ const hh = layer.height * k;
const x = (el.width - w) / 2;
const y = (el.height - hh) / 2;
if (!blur) {
- ctx.drawImage(video, x, y, w, hh);
+ ctx.drawImage(source, x, y, w, hh);
return;
}
+ const alpha = ctx.globalAlpha;
// The build's blur: gblur on the picture as it plays, sigma = strength % of its height.
ctx.save();
ctx.beginPath();
ctx.rect(x, y, w, hh);
ctx.clip();
ctx.filter = `blur(${((blur.strength / 100) * hh).toFixed(1)}px)`;
- ctx.drawImage(video, x, y, w, hh);
+ ctx.drawImage(source, x, y, w, hh);
ctx.restore();
const lay = blurCaptionLayout(blur.caption, w, hh);
ctx.font = `bold ${lay.fontSize}px "IBM Plex Mono", ui-monospace, monospace`;
@@ -41,10 +66,10 @@ export function drawFootage(el: HTMLCanvasElement, video: HTMLVideoElement | nul
lay.lines.forEach((line, i) => {
const tw = ctx.measureText(line).width;
const ty = y + lay.top + i * lay.lineHeight;
- ctx.globalAlpha = 0.78;
+ ctx.globalAlpha = 0.78 * alpha;
ctx.fillStyle = bg;
ctx.fillRect(x + (w - tw) / 2 - lay.pad, ty - lay.pad, tw + 2 * lay.pad, lay.fontSize + 2 * lay.pad);
- ctx.globalAlpha = 1;
+ ctx.globalAlpha = alpha;
ctx.fillStyle = "#fff";
ctx.fillText(line, x + (w - tw) / 2, ty);
});
diff --git a/umtool/components/projects/review/playEngine/audioBank.ts b/umtool/components/projects/review/playEngine/audioBank.ts
@@ -0,0 +1,154 @@
+import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs";
+
+// THE PLAY VIEW'S DECODED SOUND (the engine's, engine.ts): each clip's sound,
+// fetched as PCM from the bench's /api/report/audio -- ffmpeg's decode of the
+// same cached window the picture comes from, so the samples are the ones the
+// build cuts, with no browser AAC priming to argue about -- and decoded once
+// into an AudioBuffer. One buffer per CLIP (its sound and a quarter second
+// either side, playSchedule.mjs decodeSpanOf), never a window: a window can be
+// a two-minute excerpt and a cut has fifty clips, so the bank holds the clips
+// around the playhead and lets the rest go, oldest use first, past a budget
+// of decoded bytes (a 20-minute cut never holds 20 minutes of PCM).
+//
+// At a speed but 1x a clip is time-stretched at its own pitch (the bench's
+// timeStretch.mjs, WSOLA) and the stretched copy played at 1x -- the bench's
+// rule, so a voice at 1.5x sounds the same in both.
+
+/** A clip's decoded sound: its buffer and the source second of its first sample. */
+export type ClipSound = { key: string; from: number; buf: AudioBuffer };
+
+type Slot = {
+ key: string;
+ state: "loading" | "ready" | "failed";
+ p: Promise<ClipSound | null>;
+ sound: ClipSound | null;
+ why: string | null;
+ bytes: number;
+ used: number;
+};
+
+/** About 3 minutes of 48 kHz stereo as 32-bit floats. */
+const DEFAULT_BUDGET = 72 * 1024 * 1024;
+/** Stretched copies kept (the clip playing and the next few). */
+const STRETCHED_KEPT = 6;
+
+export class AudioBank {
+ private slots = new Map<string, Slot>();
+ private stretched: { key: string; buf: AudioBuffer }[] = [];
+ private clock = 0;
+
+ constructor(
+ private urlOf: (id: string, file: string, from: number, to: number) => string,
+ private budget = DEFAULT_BUDGET,
+ ) {}
+
+ static keyOf(id: string, file: string, span: { from: number; to: number }) {
+ return `${id}|${file}|${span.from}|${span.to}`;
+ }
+
+ /** The decode of a clip's span: started once, shared by every caller. */
+ request(id: string, file: string, span: { from: number; to: number }): Promise<ClipSound | null> {
+ const key = AudioBank.keyOf(id, file, span);
+ const have = this.slots.get(key);
+ if (have) {
+ have.used = ++this.clock;
+ return have.p;
+ }
+ const slot: Slot = { key, state: "loading", p: Promise.resolve(null), sound: null, why: null, bytes: 0, used: ++this.clock };
+ slot.p = (async () => {
+ try {
+ const r = await fetch(this.urlOf(id, file, span.from, span.to));
+ 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");
+ // Decoded on an offline context: a buffer belongs to no context and
+ // plays in the real one, which need not exist yet.
+ const buf = await new Offline(2, 1, 48000).decodeAudioData(bytes);
+ slot.sound = { key, from, buf };
+ slot.bytes = buf.length * buf.numberOfChannels * 4;
+ slot.state = "ready";
+ this.trim();
+ return slot.sound;
+ } catch (e) {
+ slot.state = "failed";
+ slot.why = e instanceof Error ? e.message : String(e);
+ return null;
+ }
+ })();
+ this.slots.set(key, slot);
+ return slot.p;
+ }
+
+ /** What the bank has for a clip now, without waiting: the sound, "loading", or "failed". */
+ peek(id: string, file: string, span: { from: number; to: number }): ClipSound | "loading" | "failed" | null {
+ const s = this.slots.get(AudioBank.keyOf(id, file, span));
+ if (!s) return null;
+ s.used = ++this.clock;
+ return s.state === "ready" ? s.sound : s.state;
+ }
+
+ /** Why a clip's sound did not decode (said in the Approximate line). */
+ why(id: string, file: string, span: { from: number; to: number }) {
+ return this.slots.get(AudioBank.keyOf(id, file, span))?.why ?? null;
+ }
+
+ /** Mark these as in use now, so the trim keeps them. */
+ touch(keys: Iterable<string>) {
+ for (const k of keys) {
+ const s = this.slots.get(k);
+ if (s) s.used = ++this.clock;
+ }
+ }
+
+ /** The sound at `rate`: itself at 1x, else a stretched copy (made once, kept for the clips near the playhead). */
+ atRate(sound: ClipSound, rate: number): AudioBuffer {
+ if (!wantsStretch(rate)) return sound.buf;
+ const key = `${sound.key}|${rate}`;
+ const hit = this.stretched.find((x) => x.key === key);
+ if (hit) return hit.buf;
+ const d = sound.buf;
+ const channels: Float32Array[] = [];
+ for (let c = 0; c < d.numberOfChannels; c++) channels.push(d.getChannelData(c));
+ const out = timeStretch(channels, d.sampleRate, rate) as Float32Array[];
+ const buf = new AudioBuffer({ length: Math.max(1, out[0]?.length ?? 0), numberOfChannels: Math.max(1, out.length), sampleRate: d.sampleRate });
+ out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array<ArrayBuffer>, c));
+ this.stretched = [{ key, buf }, ...this.stretched.filter((x) => x.key !== key)].slice(0, STRETCHED_KEPT);
+ return buf;
+ }
+
+ hasRate(sound: ClipSound, rate: number) {
+ return !wantsStretch(rate) || this.stretched.some((x) => x.key === `${sound.key}|${rate}`);
+ }
+
+ /** Decoded bytes held now (the budget's measure). */
+ get bytes() {
+ let n = 0;
+ for (const s of this.slots.values()) n += s.bytes;
+ return n;
+ }
+
+ get size() {
+ return this.slots.size;
+ }
+
+ /** Over the budget: the least recently used decodes go (a failure is kept, it is small and says why). */
+ private trim() {
+ const ready = [...this.slots.values()].filter((s) => s.state === "ready").sort((a, b) => a.used - b.used);
+ let total = this.bytes;
+ for (const s of ready) {
+ if (total <= this.budget) break;
+ this.slots.delete(s.key);
+ total -= s.bytes;
+ }
+ }
+
+ clear() {
+ this.slots.clear();
+ this.stretched = [];
+ }
+}
diff --git a/umtool/components/projects/review/playEngine/codecPicture.ts b/umtool/components/projects/review/playEngine/codecPicture.ts
@@ -0,0 +1,343 @@
+import { FrameQueue } from "@/lib/report/frameQueue.mjs";
+import { seekPoint, topBoxes, videoTrackOf } from "@/lib/report/mp4Index.mjs";
+
+// THE PICTURE BY WEBCODECS (the engine's first choice, engine.ts): each clip
+// on screen -- and the next one, before its join -- decoded from its cached
+// window by a VideoDecoder of its own, a few frames ahead into a small bounded
+// queue (frameQueue.mjs), and the frame due at the AUDIO clock drawn into the
+// footage canvas. No <video> element in the way: no seek latency at a join
+// (the next clip's first frame is decoded before its cut), a frame exactly
+// where the clock is (not wherever an element's own clock drifted to), and a
+// real dissolve (two clips' frames, the incoming at its progress).
+//
+// The bytes are the bench's media route's (/api/report/raw, byte ranges): the
+// `moov` found and read (mp4Index.mjs; the head and the tail asked for at
+// once), then the samples a block at a time, from the keyframe before the
+// second wanted -- never a whole GOP up front: a long one is megabytes, and
+// the first frame should not wait for its last. A file this cannot read (fragmented, a
+// codec the browser's decoder refuses) is `unsupported`, and the engine plays
+// that clip on a <video> instead. Every VideoFrame is closed: by the queue as
+// the clock passes it, on a seek, and when the clip is let go.
+
+type Track = NonNullable<ReturnType<typeof videoTrackOf>>;
+
+/** Frames decoded ahead of the one on screen, at most. */
+const MAX_FRAMES = 10;
+/** How far ahead of the clock (s, in decode order) chunks are fed. */
+const AHEAD_S = 0.6;
+/**
+ * A byte-range read: up to this many samples (four seconds at 30 fps) or
+ * bytes, whichever comes first -- few round trips, since a busy server answers
+ * each in a few hundred ms -- and the blocks a clip keeps.
+ */
+const BLOCK = 120;
+const BLOCK_BYTES = 2 * 1024 * 1024;
+const BLOCKS_KEPT = 4;
+/** The file's tail read beside its head: a window written without faststart keeps its moov at the end. */
+const TAIL_BYTES = 512 * 1024;
+
+export const codecsAvailable = () =>
+ typeof window !== "undefined" && typeof window.VideoDecoder === "function" && typeof window.EncodedVideoChunk === "function";
+
+async function range(url: string, a: number, b: number, signal: AbortSignal): Promise<ArrayBuffer> {
+ const r = await fetch(url, { headers: { Range: `bytes=${a}-${b}` }, signal });
+ if (r.status === 206) return r.arrayBuffer();
+ if (r.status === 200) return (await r.arrayBuffer()).slice(a, b + 1);
+ throw new Error(`the media route answered ${r.status}`);
+}
+
+/** The `moov` box's bytes: in the head when it leads (faststart), in the tail when it trails, else walked to box by box. */
+async function readMoov(url: string, signal: AbortSignal): Promise<ArrayBuffer> {
+ const tailP = fetch(url, { headers: { Range: `bytes=-${TAIL_BYTES}` }, signal })
+ .then(async (r) => (r.status === 206 ? { buf: await r.arrayBuffer(), range: r.headers.get("content-range") } : null))
+ .catch(() => null);
+ const head = await range(url, 0, 256 * 1024 - 1, signal);
+ let boxes = topBoxes(head);
+ const inHead = boxes.find((b) => b.type === "moov");
+ if (inHead && inHead.offset + inHead.size <= head.byteLength) return head.slice(inHead.offset, inHead.offset + inHead.size);
+ // The tail: where the walk would end up, already here.
+ const tail = await tailP;
+ const m = tail?.range ? /^bytes (\d+)-(\d+)\/(\d+)$/.exec(tail.range) : null;
+ for (let hops = 0; hops < 16; hops += 1) {
+ const moov = boxes.find((b) => b.type === "moov");
+ if (moov) {
+ if (moov.offset + moov.size <= head.byteLength) return head.slice(moov.offset, moov.offset + moov.size);
+ if (tail && m && moov.offset >= Number(m[1]) && moov.offset + moov.size - 1 <= Number(m[2])) {
+ return tail.buf.slice(moov.offset - Number(m[1]), moov.offset - Number(m[1]) + moov.size);
+ }
+ return range(url, moov.offset, moov.offset + moov.size - 1, signal);
+ }
+ const last = boxes[boxes.length - 1];
+ if (!last || last.size <= 0) break;
+ const at = last.offset + last.size;
+ if (tail && m && at >= Number(m[1]) && at + 16 <= Number(m[2]) + 1) {
+ boxes = topBoxes(tail.buf.slice(at - Number(m[1]), at - Number(m[1]) + 16), at);
+ } else boxes = topBoxes(await range(url, at, at + 15, signal), at);
+ if (!boxes.length) break;
+ }
+ throw new Error("no moov box");
+}
+
+/**
+ * Each window's track, read once per page: a clip seeked away from and back
+ * to (its decoder closed and made again) does not read its moov again.
+ */
+const tracks = new Map<string, Promise<Track | null>>();
+function trackOf(url: string): Promise<Track | null> {
+ let p = tracks.get(url);
+ if (!p) {
+ // Its own controller: a decoder closed mid-read must not abort what the next one will want.
+ p = readMoov(url, new AbortController().signal).then((m) => videoTrackOf(m));
+ p.catch(() => tracks.delete(url));
+ tracks.set(url, p);
+ if (tracks.size > 32) tracks.delete(tracks.keys().next().value!);
+ }
+ return p;
+}
+
+class ClipDecoder {
+ state: "opening" | "ready" | "unsupported" | "failed" | "closed" = "opening";
+ why = "";
+ private track: Track | null = null;
+ private dec: VideoDecoder | null = null;
+ private config: VideoDecoderConfig | null = null;
+ private q = new FrameQueue({ max: MAX_FRAMES });
+ private feed = -1;
+ private skipBeforeUs = -Infinity;
+ private flushed = false;
+ /** Byte-range reads of runs of samples: the first sample's index → its bytes (null: on its way). */
+ private blocks = new Map<number, { end: number; base: number; buf: ArrayBuffer } | null>();
+ /** A read under way: its first sample → the sample after its last. */
+ private pending = new Map<number, number>();
+ private abort = new AbortController();
+ used = 0;
+
+ constructor(readonly url: string) {
+ void this.open();
+ }
+
+ private async open() {
+ try {
+ const track = await trackOf(this.url);
+ if (!track) return this.refuse("not a progressive mp4 with a known video codec");
+ const config: VideoDecoderConfig = {
+ codec: track.codec,
+ codedWidth: track.width,
+ codedHeight: track.height,
+ ...(track.description ? { description: track.description } : {}),
+ };
+ const sup = await VideoDecoder.isConfigSupported(config).catch(() => ({ supported: false }));
+ if (!sup.supported) return this.refuse(`${track.codec} is not decoded by this browser`);
+ if (this.state === "closed") return;
+ this.track = track;
+ this.config = config;
+ this.dec = new VideoDecoder({
+ output: (f) => this.onFrame(f),
+ error: (e) => {
+ this.state = "failed";
+ this.why = e instanceof Error ? e.message : String(e);
+ this.q.clear();
+ },
+ });
+ this.dec.configure(config);
+ this.state = "ready";
+ } catch (e) {
+ if (this.state === "closed") return;
+ this.state = "failed";
+ this.why = e instanceof Error ? e.message : String(e);
+ }
+ }
+
+ private refuse(why: string) {
+ if (this.state === "closed") return;
+ this.state = "unsupported";
+ this.why = why;
+ }
+
+ private onFrame(f: VideoFrame) {
+ if (this.state !== "ready" || f.timestamp < this.skipBeforeUs) {
+ f.close();
+ return;
+ }
+ this.q.push(f);
+ }
+
+ /** The bytes of sample i, or null when they are not here yet (a read of its block is started). */
+ private bytesOf(i: number): Uint8Array | null {
+ const x = this.track!.samples[i];
+ for (const [start, b] of this.blocks) {
+ if (b && i >= start && i < b.end) return new Uint8Array(b.buf, x.offset - b.base, x.size);
+ if (!b && i >= start && i < start + BLOCK && this.pending.get(start)! > i) return null; // its read is under way
+ }
+ const ss = this.track!.samples;
+ let end = i;
+ let a = Infinity;
+ let z = 0;
+ let bytes = 0;
+ while (end < ss.length && end - i < BLOCK && (bytes < BLOCK_BYTES || end === i)) {
+ a = Math.min(a, ss[end].offset);
+ z = Math.max(z, ss[end].offset + ss[end].size);
+ bytes += ss[end].size;
+ end += 1;
+ }
+ this.blocks.set(i, null);
+ this.pending.set(i, end);
+ range(this.url, a, z - 1, this.abort.signal)
+ .then((buf) => {
+ if (this.state === "closed") return;
+ this.blocks.set(i, { end, base: a, buf });
+ this.pending.delete(i);
+ // Keep the blocks nearest the feed; let the rest go.
+ const keep = [...this.blocks.keys()].sort((x, y) => Math.abs(x - this.feed) - Math.abs(y - this.feed)).slice(0, BLOCKS_KEPT);
+ for (const k of [...this.blocks.keys()]) if (!keep.includes(k)) this.blocks.delete(k);
+ })
+ .catch((e) => {
+ this.blocks.delete(i);
+ this.pending.delete(i);
+ if (this.state === "closed" || this.abort.signal.aborted) return;
+ this.state = "failed";
+ this.why = e instanceof Error ? e.message : String(e);
+ });
+ return null;
+ }
+
+ private seek(t: number) {
+ const dec = this.dec!;
+ dec.reset();
+ dec.configure(this.config!);
+ this.q.clear();
+ const sp = seekPoint(this.track!.samples, t);
+ this.feed = sp.key;
+ // The frame due at t is the one that shows there: everything before it is decoded and closed unseen.
+ this.skipBeforeUs = Math.round((this.track!.samples[sp.frame]?.pts ?? 0) * 1e6);
+ this.flushed = false;
+ }
+
+ /** Decode toward media time t (s): seek when t is outside what is queued or coming, then feed ahead. */
+ want(t: number) {
+ if (this.state !== "ready" || !this.dec || !this.track) return;
+ const s = this.track.samples;
+ const tUs = t * 1e6;
+ const first = this.q.frames[0]?.timestamp;
+ const frameUs = (s[0]?.duration ?? 1 / 30) * 1e6;
+ const behind = first !== undefined ? tUs < first - frameUs / 2 : tUs < this.skipBeforeUs - frameUs / 2;
+ // Far ahead of what is queued AND past a keyframe the feed has not reached: jump to it. (Decoding
+ // toward t from a keyframe long before it -- a long GOP -- is not "behind", it is the way there.)
+ const farAhead = this.q.head < tUs - 1e6 && this.feed >= 0 && seekPoint(s, t).key > this.feed;
+ if (this.feed < 0 || behind || farAhead) this.seek(t);
+ try {
+ while (this.dec.decodeQueueSize + this.q.size < MAX_FRAMES && this.feed < s.length) {
+ const x = s[this.feed];
+ if (x.dts > t + AHEAD_S) break;
+ const data = this.bytesOf(this.feed);
+ if (!data) break;
+ this.dec.decode(new EncodedVideoChunk({
+ type: x.key ? "key" : "delta",
+ timestamp: Math.round(x.pts * 1e6),
+ duration: Math.round(x.duration * 1e6),
+ data,
+ }));
+ this.feed += 1;
+ this.flushed = false;
+ }
+ // The next block on its way before the feed reaches it: the one after the block the feed is in.
+ if (this.feed < s.length) {
+ let next = -1;
+ for (const [start, b] of this.blocks) {
+ const end = b ? b.end : this.pending.get(start);
+ if (end !== undefined && this.feed >= start && this.feed < end) next = end;
+ }
+ if (next > 0 && next < s.length) this.bytesOf(next);
+ }
+ // The track's end: the decoder's reorder buffer holds its last frames until it is flushed.
+ if (!this.flushed && this.feed >= s.length && this.dec.decodeQueueSize === 0) {
+ this.flushed = true;
+ void this.dec.flush().catch(() => {});
+ }
+ } catch (e) {
+ this.state = "failed";
+ this.why = e instanceof Error ? e.message : String(e);
+ }
+ }
+
+ /** The decoded frame due at media time t, or null when it has not been decoded yet. */
+ frameAt(t: number): VideoFrame | null {
+ if (this.state !== "ready") return null;
+ return (this.q.frameAt(Math.round(t * 1e6) + 500) as VideoFrame | null) ?? null;
+ }
+
+ close() {
+ this.state = "closed";
+ this.abort.abort();
+ this.q.clear();
+ try {
+ this.dec?.close();
+ } catch {
+ // Already closed (an error closes it).
+ }
+ this.dec = null;
+ this.blocks.clear();
+ this.pending.clear();
+ }
+}
+
+/** The decoders of the clips on screen and the next: one per cached window URL, let go when not wanted. */
+export class CodecPicture {
+ private clips = new Map<string, ClipDecoder>();
+ private tick = 0;
+
+ /** Decode toward each wanted (url, media time); close the decoders nobody wants now. */
+ sync(wants: { url: string; mediaTime: number }[]) {
+ this.tick += 1;
+ for (const w of wants) {
+ let d = this.clips.get(w.url);
+ if (!d) {
+ d = new ClipDecoder(w.url);
+ this.clips.set(w.url, d);
+ }
+ d.used = this.tick;
+ d.want(w.mediaTime);
+ }
+ for (const [url, d] of this.clips) {
+ // A refusal is remembered (cheap, and asking again would fetch the moov again); anything else unwanted is closed.
+ if (d.used !== this.tick && d.state !== "unsupported" && d.state !== "failed") {
+ d.close();
+ this.clips.delete(url);
+ }
+ }
+ }
+
+ /** The frame due for a window at media time t, or null. */
+ frameFor(url: string, t: number): VideoFrame | null {
+ return this.clips.get(url)?.frameAt(t) ?? null;
+ }
+
+ /** "opening" | "ready" | "unsupported" | "failed", or null when nothing was asked of it. */
+ status(url: string) {
+ const d = this.clips.get(url);
+ return d ? d.state : null;
+ }
+
+ why(url: string) {
+ return this.clips.get(url)?.why ?? "";
+ }
+
+ /** Give up on a window (it could not keep up with the clock): closed, and remembered as refused, so it plays on an element. */
+ demote(url: string, why: string) {
+ const d = this.clips.get(url);
+ if (!d) return;
+ d.close();
+ d.state = "failed";
+ d.why = why;
+ }
+
+ /** How many decoders are open (a bound the tests read). */
+ get open() {
+ return [...this.clips.values()].filter((d) => d.state === "ready" || d.state === "opening").length;
+ }
+
+ close() {
+ for (const d of this.clips.values()) d.close();
+ this.clips.clear();
+ }
+}
diff --git a/umtool/components/projects/review/playEngine/elementPicture.ts b/umtool/components/projects/review/playEngine/elementPicture.ts
@@ -0,0 +1,179 @@
+// THE PICTURE ON TWO <video> ELEMENTS, SLAVED TO THE SOUND (the engine's
+// fallback, and its path where WebCodecs is missing): the clips on screen --
+// one, or two through a crossfade -- and the next clip, loaded and seeked to
+// its first second behind them. Every element is MUTED (the sound is Web
+// Audio's, engine.ts); each one playing is held to the clock: the frame it
+// presented (requestVideoFrameCallback's mediaTime, else currentTime)
+// against the second the clock says, its speed nudged for a drift past a
+// frame and re-seeked past a quarter second -- a seek per frame of drift
+// would stall it in a loop of seeks, which is worse than the drift.
+
+export type Want = { index: number; id: string; url: string; mediaTime: number; play: boolean };
+
+/** Past this (s), an element is re-seeked rather than nudged. */
+const SEEK_PAST = 0.25;
+/** How hard a drift is pulled back: the speed changes by drift × this, at most ±MAX_NUDGE. */
+const NUDGE_GAIN = 1.5;
+const MAX_NUDGE = 0.15;
+
+type Slot = {
+ el: HTMLVideoElement | null;
+ index: number;
+ url: string;
+ /** The media time of the frame last presented (rVFC), or null when the element cannot say. */
+ presented: number | null;
+ presentedAt: number;
+ /** The picture's frame length, as the presented frames step (the shortest step seen; 0 until they have). */
+ frame: number;
+ rvfc: number;
+};
+
+export class ElementPicture {
+ private slots: Slot[] = [0, 1].map(() => ({ el: null, index: -1, url: "", presented: null, presentedAt: 0, rvfc: 0, frame: 0 }));
+ /** The element's sound is the fallback's (no Web Audio): unmuted on the clip the clock follows. */
+ soundFromElement = false;
+
+ attach(k: number, el: HTMLVideoElement | null) {
+ const s = this.slots[k];
+ if (s.el === el) return;
+ s.el = el;
+ s.index = -1;
+ s.url = "";
+ if (el) {
+ el.muted = true;
+ el.preservesPitch = true;
+ this.watch(s);
+ }
+ }
+
+ /** The element holding item `index`, ready to draw (a frame decoded), or null. */
+ sourceFor(index: number): HTMLVideoElement | null {
+ const s = this.slots.find((x) => x.index === index && x.el);
+ const v = s?.el ?? null;
+ return v && v.readyState >= 2 && v.videoWidth > 0 ? v : null;
+ }
+
+ /** The media time of the frame item `index`'s element last presented (requestVideoFrameCallback), when it is fresh. */
+ presentedFor(index: number): number | null {
+ const s = this.slots.find((x) => x.index === index && x.el);
+ return s && s.presented !== null && performance.now() - s.presentedAt < 250 ? s.presented : null;
+ }
+
+ /** The frame length of item `index`'s picture (1/30 until its frames have stepped). */
+ frameFor(index: number): number {
+ return this.slots.find((x) => x.index === index && x.el)?.frame || 1 / 30;
+ }
+
+ /** Which slot holds item `index` (-1: none). */
+ slotOf(index: number) {
+ return this.slots.findIndex((x) => x.index === index);
+ }
+
+ /** A slot's media failed to load: let it go, and say which item it held. */
+ fail(k: number): number {
+ const s = this.slots[k];
+ const i = s.index;
+ s.index = -1;
+ s.url = "";
+ return i;
+ }
+
+ /**
+ * Hold the elements to what the clock wants: `visible` (on screen now, the
+ * one the sound follows first) and `next` (loaded and seeked, paused).
+ */
+ sync(visible: Want[], next: Want | null, rate: number) {
+ const wanted = [...visible, ...(next ? [{ ...next, play: false }] : [])].slice(0, 2);
+ // Keep each wanted item in the slot that already holds it; give the rest the free slots.
+ const taken = new Set<number>();
+ const placed = new Map<number, number>();
+ for (const w of wanted) {
+ const k = this.slots.findIndex((s, j) => s.el && s.index === w.index && s.url === w.url && !taken.has(j));
+ if (k >= 0) {
+ taken.add(k);
+ placed.set(w.index, k);
+ }
+ }
+ for (const w of wanted) {
+ if (placed.has(w.index)) continue;
+ const k = this.slots.findIndex((s, j) => s.el && !taken.has(j));
+ if (k < 0) continue;
+ taken.add(k);
+ placed.set(w.index, k);
+ this.load(this.slots[k], w);
+ }
+ this.slots.forEach((s, j) => {
+ if (!taken.has(j) && s.el && !s.el.paused) s.el.pause();
+ });
+ wanted.forEach((w, n) => {
+ const k = placed.get(w.index);
+ if (k === undefined) return;
+ this.hold(this.slots[k], w, rate, n === 0);
+ });
+ }
+
+ pauseAll() {
+ for (const s of this.slots) if (s.el && !s.el.paused) s.el.pause();
+ }
+
+ private load(s: Slot, w: Want) {
+ const v = s.el!;
+ s.index = w.index;
+ s.url = w.url;
+ s.presented = null;
+ s.frame = 0;
+ if (v.getAttribute("src") !== w.url) {
+ v.setAttribute("src", w.url);
+ v.dataset.playSlotItem = w.id;
+ }
+ const seek = () => {
+ try {
+ v.currentTime = Math.max(0, w.mediaTime);
+ } catch {
+ // Not seekable yet: the metadata listener seeks.
+ }
+ };
+ if (v.readyState >= 1) seek();
+ else v.addEventListener("loadedmetadata", seek, { once: true });
+ }
+
+ /** One element to its wanted second: playing at the clock's speed with drift pulled back, or paused on the frame. */
+ private hold(s: Slot, w: Want, rate: number, lead: boolean) {
+ const v = s.el!;
+ v.muted = !(this.soundFromElement && lead && w.play);
+ if (v.readyState < 1) return;
+ const at = s.presented !== null && performance.now() - s.presentedAt < 250 && !v.paused ? s.presented : v.currentTime;
+ const drift = at - w.mediaTime;
+ if (!w.play) {
+ if (!v.paused) v.pause();
+ // Paused: on the exact frame (within half a frame), once the last seek has landed.
+ if (!v.seeking && Math.abs(v.currentTime - w.mediaTime) > 1 / 60) v.currentTime = Math.max(0, w.mediaTime);
+ return;
+ }
+ if (v.seeking) return;
+ if (Math.abs(drift) > SEEK_PAST * Math.max(1, rate)) {
+ // Seek a little ahead of the clock: the seek itself takes time.
+ v.currentTime = Math.max(0, w.mediaTime + 0.05 * rate);
+ return;
+ }
+ const nudge = Math.abs(drift) > 1 / 30 ? Math.max(-MAX_NUDGE, Math.min(MAX_NUDGE, -drift * NUDGE_GAIN)) : 0;
+ const want = rate * (1 + nudge);
+ if (Math.abs(v.playbackRate - want) > 1e-3) v.playbackRate = want;
+ if (v.paused) void v.play().catch(() => {});
+ }
+
+ /** requestVideoFrameCallback, where there is one: the media time of each frame as it is presented. */
+ private watch(s: Slot) {
+ const v = s.el as (HTMLVideoElement & { requestVideoFrameCallback?: (cb: (now: number, m: { mediaTime: number }) => void) => number }) | null;
+ if (!v?.requestVideoFrameCallback) return;
+ const on = (_now: number, m: { mediaTime: number }) => {
+ if (s.el !== v) return;
+ const step = s.presented !== null ? m.mediaTime - s.presented : 0;
+ if (step > 1 / 121 && step < 0.11) s.frame = s.frame ? Math.min(s.frame, step) : step;
+ s.presented = m.mediaTime;
+ s.presentedAt = performance.now();
+ s.rvfc = v.requestVideoFrameCallback!(on);
+ };
+ s.rvfc = v.requestVideoFrameCallback(on);
+ }
+}
diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts
@@ -0,0 +1,671 @@
+import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur";
+import { itemIndexAt, playPlan, sourceAt } from "@/lib/report/playCut.mjs";
+import { audioSpans, decodeSpanOf, scheduleFrom } from "@/lib/report/playSchedule.mjs";
+import { drawFootageLayers, type FootageLayer } from "../footageCanvas";
+import { AudioBank, type ClipSound } from "./audioBank";
+import { CodecPicture, codecsAvailable } from "./codecPicture";
+import { ElementPicture } from "./elementPicture";
+
+// ---------------------------------------------------------------------------
+// THE PLAY VIEW'S ENGINE (umtool/docs/knobs.md, "Play the cut"): the cut
+// played like the finished video, edges first.
+//
+// THE CLOCK IS THE SOUND'S. Every clip's sound is decoded (audioBank.ts) and
+// scheduled back to back on ONE AudioContext (playSchedule.mjs): each starts
+// at its segment's first second and stops at its footage's last, to the
+// sample, at the render's edges (lib/report/cutPoints.mjs, via the plan);
+// a crossfade is the build's -- two linear ramps over the overlap -- and the
+// loudness gain, room's muted edges, the clip's own audio knobs and the mute
+// mark are gain automation. The cut second everything reads (the rail, the
+// tally, the stamps, the finale, a note's anchor) is that context's time
+// mapped through the plan. Cards, holds and clips with no media are silence
+// on the same clock. A clip whose sound is not decoded by the time it is due
+// holds the clock (`waiting`) at its first second; nothing is skipped.
+//
+// THE PICTURE FOLLOWS THE CLOCK: by WebCodecs where the browser has it
+// (codecPicture.ts: the frame due at the clock, decoded ahead; a real
+// dissolve), else on two <video> elements slaved to it (elementPicture.ts).
+// Either way it is drawn into the footage canvas by footageCanvas.ts, blurred
+// as the build blurs it.
+//
+// No Web Audio at all (or a context that will not start): the clock runs on
+// the page's own, and the playing element's sound is heard -- the old way,
+// and the Approximate line says so.
+// ---------------------------------------------------------------------------
+
+export type Plan = ReturnType<typeof playPlan>;
+type Item = Plan["items"][number];
+export type EngineEntry = {
+ id: string;
+ media?: { name: string; from: number; to: number } | null;
+ blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null;
+};
+export type EngineUi = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean };
+export type EngineInfo = {
+ /** Where the sound comes from: decoded and scheduled on one context, or the playing element. */
+ sound: "webaudio" | "element";
+ /** How the picture is made: WebCodecs, <video> elements, or WebCodecs with some clips on elements. */
+ picture: "webcodecs" | "element" | "mixed";
+ /** Clips whose sound did not decode (they play silent), and why. */
+ silent: Record<string, string>;
+};
+
+type Opts = {
+ srcOf: (id: string, file: string) => string;
+ audioOf: (id: string, file: string, from: number, to: number) => string;
+ onUi: (ui: EngineUi) => void;
+ onFailed: (id: string, why: string) => void;
+ onInfo: (info: EngineInfo) => void;
+ /**
+ * The picture's path: "auto" (WebCodecs where the browser has it), or one
+ * forced by the URL's `?picture=element|webcodecs`, for comparing the two.
+ */
+ picture?: "auto" | "element" | "webcodecs";
+};
+
+/** How far ahead (wall s) sound is scheduled. */
+const LOOKAHEAD = 1.2;
+/** A start this close (wall s) with no decoded sound holds the clock. */
+const DUE = 0.06;
+/**
+ * Scheduled this far ahead of now, so a start is never in the past: the
+ * bench's 30 ms, and more -- a restart while the page is busy (a re-plan
+ * as the chrome composes) can be a frame or two from its next tick.
+ */
+const START_LEAD = 0.08;
+/** A WebCodecs clip this far behind the sound (s) for this long (ms) plays on an element instead. */
+const LAG_S = 0.25;
+const LAG_FOR = 700;
+/** Clips decoded ahead of and behind the playhead. */
+const DECODE_AHEAD = 3;
+const DECODE_BEHIND = 1;
+
+type Node = { key: string; src: AudioBufferSourceNode; gain: GainNode };
+
+export class PlayEngine {
+ plan: Plan = { items: [], total: 0, edges: "estimate" };
+ private entries = new Map<string, EngineEntry>();
+ private spans: ReturnType<typeof audioSpans> = [];
+ private failed = new Set<string>();
+ private silent: Record<string, string> = {};
+
+ t = 0;
+ cur = 0;
+ playing = false;
+ ended = false;
+ waiting = false;
+ rate = 1;
+ blurRendered = true;
+ bg = "#000";
+ style = "fade";
+
+ // The clock: cut second t0 at (context or page) time c0.
+ private t0 = 0;
+ private c0 = 0;
+ private ctx: AudioContext | null = null;
+ private master: GainNode | null = null;
+ private sound: "webaudio" | "element" = "webaudio";
+ private nodes: Node[] = [];
+ private plannedFrom: ReturnType<typeof scheduleFrom> = [];
+ private started = new Set<string>();
+
+ private bank: AudioBank;
+ private elements = new ElementPicture();
+ private codecs: CodecPicture | null;
+ private canvas: HTMLCanvasElement | null = null;
+ private raf = 0;
+ private lastUi: EngineUi = { t: -1, cur: -1, playing: false, ended: false, waiting: false };
+ private lastInfo = "";
+ private lastDraw = "";
+ /** A picture is on the canvas (kept, rather than a black frame, while the next one decodes). */
+ private shown = false;
+ /**
+ * What the engine measured of itself, for the e2e and for anyone asking
+ * (window.__umtoolPlayEngine.stats): each node's scheduled start and stop on
+ * the context clock and how late it was started (0: ahead of its time, so
+ * Web Audio starts it on the sample); and how far each frame drawn while
+ * playing was from the second the clock wanted (in frames of 1/30 s).
+ */
+ private measured = {
+ nodes: [] as { id: string; at: number; stop: number; late: number; run: number; from: number; to: number }[],
+ run: 0,
+ drawn: 0, off: 0, worst: 0,
+ late: [] as { id: string; want: number; at: number }[],
+ };
+ private restartedAt = 0;
+ /** WebCodecs windows behind the clock, and since when (performance.now). */
+ private lagging = new Map<string, number>();
+
+ constructor(private o: Opts) {
+ this.bank = new AudioBank(o.audioOf);
+ this.codecs = o.picture !== "element" && codecsAvailable() ? new CodecPicture() : null;
+ const loop = () => {
+ this.raf = requestAnimationFrame(loop);
+ this.tick();
+ };
+ this.raf = requestAnimationFrame(loop);
+ }
+
+ destroy() {
+ cancelAnimationFrame(this.raf);
+ this.stopNodes();
+ this.elements.pauseAll();
+ this.codecs?.close();
+ this.bank.clear();
+ void this.ctx?.close().catch(() => {});
+ this.ctx = null;
+ }
+
+ // ---- what plays -----------------------------------------------------------
+
+ setPlan(plan: Plan, entries: Map<string, EngineEntry>) {
+ const was = this.plan;
+ this.plan = plan;
+ this.entries = entries;
+ this.spans = audioSpans(plan as never);
+ if (was.items.length && plan.items.length) {
+ // The same moment of the same clip after a re-plan (the render's edges
+ // arriving, a reload): by its source second when it is a clip.
+ const it = was.items[this.cur];
+ const same = it ? plan.items.findIndex((x) => x.id === it.id) : -1;
+ if (same >= 0 && it && Math.abs(this.now() - it.from) < 1e-3) {
+ // At an entry's first second (the start, a jump to a clip): at its first second still.
+ this.t = plan.items[same].from;
+ } else if (it?.clip && same >= 0 && plan.items[same].clip) {
+ const src = sourceAt(it, this.now());
+ this.t = Math.max(plan.items[same].from, Math.min(plan.items[same].to - 0.001, plan.items[same].start + ((src ?? 0) - plan.items[same].clip!.sourceFrom)));
+ } else this.t = Math.min(this.now(), Math.max(0, plan.total - 0.001));
+ } else this.t = Math.min(this.t, Math.max(0, plan.total - 0.001));
+ this.cur = Math.max(0, itemIndexAt(plan, this.t));
+ if (this.playing) this.restart(this.t);
+ this.lastDraw = "";
+ }
+
+ attachCanvas(el: HTMLCanvasElement | null) {
+ this.canvas = el;
+ this.lastDraw = "";
+ this.shown = false;
+ }
+
+ attachSlot(k: number, el: HTMLVideoElement | null) {
+ this.elements.attach(k, el);
+ }
+
+ /** A slot's media will not play: that clip plays as a placeholder from here on. */
+ slotFailed(k: number) {
+ const i = this.elements.fail(k);
+ const item = this.plan.items[i];
+ if (!item) return;
+ this.failed.add(item.id);
+ this.o.onFailed(item.id, "the media did not load");
+ }
+
+ hasVideo(i: number) {
+ const item = this.plan.items[i];
+ const e = item ? this.entries.get(item.id) : null;
+ return !!item?.clip && !!e?.media && !this.failed.has(item.id);
+ }
+
+ // ---- the transport ------------------------------------------------------------
+
+ /** The cut second now: the clock's, while it runs. */
+ now() {
+ if (!this.playing || this.waiting) return this.t;
+ return this.t0 + Math.max(0, this.clockNow() - this.c0) * this.rate;
+ }
+
+ private clockNow() {
+ return this.sound === "webaudio" && this.ctx ? this.ctx.currentTime : performance.now() / 1000;
+ }
+
+ seek(t: number) {
+ const at = Math.max(0, Math.min(t, Math.max(0, this.plan.total - 0.001)));
+ this.ended = false;
+ this.t = at;
+ this.cur = Math.max(0, itemIndexAt(this.plan, at));
+ if (this.playing) this.restart(at);
+ this.lastDraw = "";
+ this.publish();
+ }
+
+ setPlaying(on: boolean) {
+ if (on && this.ended) {
+ this.ended = false;
+ this.t = 0;
+ this.cur = 0;
+ }
+ if (on) {
+ // The context is made HERE, inside the click or key that asked: that gesture is what lets it start.
+ this.openContext();
+ this.playing = true;
+ this.restart(this.t);
+ } else {
+ this.t = this.now();
+ this.playing = false;
+ this.waiting = false;
+ this.stopNodes();
+ this.elements.pauseAll();
+ }
+ this.publish();
+ }
+
+ setRate(r: number) {
+ if (r === this.rate) return;
+ const t = this.now();
+ this.rate = r;
+ if (this.playing) this.restart(t);
+ }
+
+ private openContext() {
+ if (this.ctx || this.sound === "element") return;
+ const AC = typeof window !== "undefined" ? window.AudioContext : undefined;
+ if (!AC) {
+ this.fallBackToElementSound();
+ return;
+ }
+ try {
+ this.ctx = new AC({ latencyHint: "playback" });
+ this.master = this.ctx.createGain();
+ this.master.connect(this.ctx.destination);
+ if (this.ctx.state !== "running") {
+ void this.ctx.resume().catch(() => {});
+ // No gesture ever reached the page (a typed URL, a test with no
+ // click): a context that has not started within a moment never will.
+ window.setTimeout(() => {
+ if (this.ctx && this.ctx.state !== "running") this.fallBackToElementSound();
+ }, 800);
+ }
+ } catch {
+ this.fallBackToElementSound();
+ }
+ }
+
+ private fallBackToElementSound() {
+ const t = this.now();
+ this.stopNodes();
+ void this.ctx?.close().catch(() => {});
+ this.ctx = null;
+ this.sound = "element";
+ this.elements.soundFromElement = true;
+ // The sound is the element's now, so the picture must be too: an element that is not playing makes none.
+ this.codecs?.close();
+ this.codecs = null;
+ if (this.playing) this.restart(t);
+ }
+
+ /** (Re)start the clock at cut second t, and the sound from there. */
+ private restart(t: number) {
+ this.stopNodes();
+ this.t = t;
+ this.waiting = false;
+ this.c0 = this.clockNow() + (this.sound === "webaudio" && this.ctx ? START_LEAD : 0);
+ this.t0 = t;
+ this.plannedFrom = this.sound === "webaudio" ? scheduleFrom(this.spans, t, this.rate) : [];
+ this.started.clear();
+ this.lastDraw = "";
+ this.restartedAt = performance.now();
+ this.measured.run += 1;
+ // The first nodes now, inside the lead, not at the next frame.
+ if (this.playing) this.schedule();
+ }
+
+ private stopNodes() {
+ for (const n of this.nodes) {
+ try {
+ n.src.stop();
+ } catch {
+ // Never started, or already stopped.
+ }
+ n.src.disconnect();
+ n.gain.disconnect();
+ }
+ this.nodes = [];
+ }
+
+ /** Hold the clock at cut second t until the sound due there is decoded. */
+ private hold(t: number) {
+ this.stopNodes();
+ this.t = t;
+ this.waiting = true;
+ this.elements.pauseAll();
+ }
+
+ // ---- the sound ------------------------------------------------------------------
+
+ private spanSound(id: string): { file: string; span: { from: number; to: number } } | null {
+ const e = this.entries.get(id);
+ const s = this.spans.find((x) => x.id === id);
+ if (!e?.media || !s) return null;
+ return { file: e.media.name, span: decodeSpanOf(s) };
+ }
+
+ /** Decode the clips around the playhead; the bank lets the far ones go. */
+ private prefetch() {
+ const keys: string[] = [];
+ for (let i = Math.max(0, this.cur - DECODE_BEHIND); i <= Math.min(this.plan.items.length - 1, this.cur + DECODE_AHEAD); i += 1) {
+ const it = this.plan.items[i];
+ if (!it.clip) continue;
+ const ss = this.spanSound(it.id);
+ if (!ss) continue;
+ keys.push(AudioBank.keyOf(it.id, ss.file, ss.span));
+ void this.bank.request(it.id, ss.file, ss.span).then((got) => {
+ if (!got && !this.silent[it.id]) {
+ this.silent = { ...this.silent, [it.id]: this.bank.why(it.id, ss.file, ss.span) ?? "no sound" };
+ }
+ });
+ }
+ this.bank.touch(keys);
+ }
+
+ /** Start every planned node due within the lookahead; hold the clock at one whose sound is not here. */
+ private schedule() {
+ const ctx = this.ctx;
+ if (!ctx || !this.master || this.sound !== "webaudio") return;
+ const nowWall = ctx.currentTime - this.c0;
+ for (const p of this.plannedFrom) {
+ const key = `${p.id}|${p.atWall}`;
+ if (this.started.has(key)) continue;
+ if (p.atWall > nowWall + LOOKAHEAD) break;
+ if (p.atWall + p.durWall <= nowWall) {
+ this.started.add(key);
+ continue;
+ }
+ const ss = this.spanSound(p.id);
+ const got = ss ? this.bank.peek(p.id, ss.file, ss.span) : "failed";
+ // (A clip whose PICTURE failed still sounds: its sound is decoded on the server, not by the element.)
+ if (got === "failed" || !ss) {
+ this.started.add(key); // silent: the clock goes on
+ continue;
+ }
+ const sound = got && got !== "loading" ? (got as ClipSound) : null;
+ if (!sound || !this.bank.hasRate(sound, this.rate)) {
+ if (sound && p.atWall - nowWall > DUE) {
+ // Stretch ahead of its start, off the frame that needs it now.
+ this.bank.atRate(sound, this.rate);
+ continue;
+ }
+ if (p.atWall - nowWall <= DUE) {
+ // Due and not here: the clock holds where it is, and goes on from there once it is.
+ this.hold(this.now());
+ return;
+ }
+ continue;
+ }
+ this.startNode(ctx, p, sound);
+ this.started.add(key);
+ }
+ }
+
+ private startNode(ctx: AudioContext, p: ReturnType<typeof scheduleFrom>[number], sound: ClipSound) {
+ const buf = this.bank.atRate(sound, this.rate);
+ const src = ctx.createBufferSource();
+ src.buffer = buf;
+ const gain = ctx.createGain();
+ src.connect(gain);
+ gain.connect(this.master!);
+ const at = Math.max(ctx.currentTime, this.c0 + p.atWall);
+ // A start in the past (a late tick) begins late at a LATER offset, so the sound stays on the clock.
+ const late = at - (this.c0 + p.atWall);
+ const offsetSrc = p.src + late * this.rate - sound.from;
+ const offset = Math.max(0, offsetSrc / (buf === sound.buf ? 1 : this.rate));
+ const stop = this.c0 + p.atWall + p.durWall;
+ const g = gain.gain;
+ g.cancelScheduledValues(0);
+ const env = p.env;
+ const level = (wall: number) => {
+ if (wall <= env[0][0]) return env[0][1];
+ for (let i = 1; i < env.length; i += 1) {
+ if (wall <= env[i][0]) {
+ const [a, ga] = env[i - 1];
+ const [b, gb] = env[i];
+ return b > a ? ga + ((gb - ga) * (wall - a)) / (b - a) : gb;
+ }
+ }
+ return env[env.length - 1][1];
+ };
+ g.setValueAtTime(level(at - this.c0) * p.gain, at);
+ for (const [w, v] of env) {
+ if (this.c0 + w <= at) continue;
+ g.linearRampToValueAtTime(v * p.gain, this.c0 + w);
+ }
+ src.start(at, offset);
+ src.stop(stop);
+ const cut = (wall: number) => Math.round((this.t0 + wall * this.rate) * 1e6) / 1e6;
+ this.measured.nodes = [
+ ...this.measured.nodes,
+ { id: p.id, at: this.c0 + p.atWall, stop, late, run: this.measured.run, from: cut(p.atWall), to: cut(p.atWall + p.durWall) },
+ ].slice(-40);
+ const node: Node = { key: p.id, src, gain };
+ src.onended = () => {
+ src.disconnect();
+ gain.disconnect();
+ this.nodes = this.nodes.filter((n) => n !== node);
+ };
+ this.nodes.push(node);
+ }
+
+ // ---- the frame --------------------------------------------------------------------
+
+ private tick() {
+ const items = this.plan.items;
+ if (!items.length) return;
+ if (this.playing && this.waiting) {
+ // Held: start again once what was due is decoded.
+ const p = this.plannedFrom.find((x) => !this.started.has(`${x.id}|${x.atWall}`) && this.t0 + (x.atWall + x.durWall) * this.rate > this.t);
+ const ss = p ? this.spanSound(p.id) : null;
+ // Asked for here too: a hold far from where the prefetch looks (a seek) must not wait on nothing.
+ if (p && ss) void this.bank.request(p.id, ss.file, ss.span);
+ const got = p && ss ? this.bank.peek(p.id, ss.file, ss.span) : null;
+ if (!p || !ss || got === "failed" || (got && got !== "loading" && this.bank.hasRate(got as ClipSound, this.rate))) {
+ this.restart(this.t);
+ } else if (got && got !== "loading") this.bank.atRate(got as ClipSound, this.rate);
+ }
+ let t = this.now();
+ if (this.playing && !this.waiting && t >= this.plan.total - 0.001) {
+ t = this.plan.total;
+ this.t = t;
+ this.playing = false;
+ this.ended = true;
+ this.stopNodes();
+ this.elements.pauseAll();
+ }
+ this.cur = Math.max(0, itemIndexAt(this.plan, Math.min(t, this.plan.total - 0.001)));
+ this.prefetch();
+ if (this.playing && !this.waiting) this.schedule();
+ this.picture(Math.min(t, Math.max(0, this.plan.total - 0.001)));
+ this.publish();
+ }
+
+ /** The clips on screen at t: the current one, and through a crossfade the other, each with its alpha. */
+ private visibleAt(t: number): { i: number; alpha: number }[] {
+ const items = this.plan.items;
+ const i = this.cur;
+ const it = items[i];
+ if (!it) return [];
+ const prev = items[i - 1];
+ const next = items[i + 1];
+ const pair = (out: number, inc: number) => {
+ const a = items[out];
+ const b = items[inc];
+ const D = Math.max(1e-6, a.end - b.start);
+ const p = Math.min(1, Math.max(0, (t - b.start) / D));
+ // fadeblack / fadewhite dip through the ground; every other style dissolves (a push is drawn as one).
+ if (this.style === "fadeblack" || this.style === "fadewhite") {
+ return [{ i: out, alpha: Math.max(0, 1 - 2 * p) }, { i: inc, alpha: Math.max(0, 2 * p - 1) }];
+ }
+ return [{ i: out, alpha: 1 }, { i: inc, alpha: p }];
+ };
+ if (prev && t < prev.end && t >= it.start) return pair(i - 1, i);
+ if (next && t >= next.start && t < it.end) return pair(i, i + 1);
+ return [{ i, alpha: 1 }];
+ }
+
+ private mediaUrl(i: number) {
+ const it = this.plan.items[i];
+ const e = it ? this.entries.get(it.id) : null;
+ return it && e?.media ? this.o.srcOf(it.id, e.media.name) : null;
+ }
+
+ private mediaTimeOf(i: number, t: number) {
+ const it = this.plan.items[i];
+ const e = this.entries.get(it.id);
+ const src = sourceAt(it, t) ?? it.clip?.sourceFrom ?? 0;
+ return Math.max(0, src - (e?.media?.from ?? 0));
+ }
+
+ private picture(t: number) {
+ const items = this.plan.items;
+ const vis = this.visibleAt(t).filter((v) => this.hasVideo(v.i));
+ // The next clip with media, readied before its join.
+ let nextI = -1;
+ for (let j = this.cur + 1; j < items.length; j += 1) {
+ if (this.hasVideo(j) && !vis.some((v) => v.i === j)) {
+ nextI = j;
+ break;
+ }
+ }
+ const runs = this.playing && !this.waiting;
+ const inFootage = (i: number) => !!items[i].clip && t <= items[i].clip!.playEnd && t >= items[i].start;
+ const layers: { i: number; alpha: number; source: CanvasImageSource | null; w: number; h: number }[] = [];
+ const viaElement: { i: number; alpha: number }[] = [];
+ const codecWants: { url: string; mediaTime: number }[] = [];
+ for (const v of vis) {
+ const url = this.mediaUrl(v.i)!;
+ const st = this.codecs?.status(url);
+ if (this.codecs && st !== "unsupported" && st !== "failed") codecWants.push({ url, mediaTime: this.mediaTimeOf(v.i, t) });
+ else viaElement.push(v);
+ }
+ const nextUrl = nextI >= 0 ? this.mediaUrl(nextI) : null;
+ const nextSt = nextUrl && this.codecs ? this.codecs.status(nextUrl) : "unsupported";
+ if (nextUrl && this.codecs && nextSt !== "unsupported" && nextSt !== "failed") {
+ codecWants.push({ url: nextUrl, mediaTime: this.mediaTimeOf(nextI, items[nextI].start) });
+ }
+ this.codecs?.sync(codecWants);
+ // The elements hold what WebCodecs does not: the clips it refused, and the next one when it refused that.
+ const elementNext = nextI >= 0 && (!this.codecs || nextSt === "unsupported" || nextSt === "failed") ? nextI : -1;
+ this.elements.sync(
+ viaElement.map((v) => ({ index: v.i, id: items[v.i].id, url: this.mediaUrl(v.i)!, mediaTime: this.mediaTimeOf(v.i, t), play: runs && inFootage(v.i) })),
+ elementNext >= 0 ? { index: elementNext, id: items[elementNext].id, url: this.mediaUrl(elementNext)!, mediaTime: this.mediaTimeOf(elementNext, items[elementNext].start), play: false } : null,
+ this.rate,
+ );
+ for (const v of vis) {
+ const url = this.mediaUrl(v.i)!;
+ if (this.codecs && !viaElement.includes(v)) {
+ const want = this.mediaTimeOf(v.i, t);
+ const f = this.codecs.frameFor(url, want);
+ if (f && runs) this.measure(items[v.i].id, f.timestamp / 1e6, want, (f.duration ?? 33_333) / 1e6);
+ if (runs && inFootage(v.i)) this.keepingUp(url, f ? want - f.timestamp / 1e6 : Infinity);
+ layers.push({ ...v, source: f, w: f?.displayWidth ?? 0, h: f?.displayHeight ?? 0 });
+ } else {
+ const el = this.elements.sourceFor(v.i);
+ if (el && runs && inFootage(v.i)) this.measure(items[v.i].id, this.elements.presentedFor(v.i) ?? el.currentTime, this.mediaTimeOf(v.i, t), this.elements.frameFor(v.i));
+ layers.push({ ...v, source: el, w: el?.videoWidth ?? 0, h: el?.videoHeight ?? 0 });
+ }
+ }
+ this.reportInfo();
+ this.draw(t, layers);
+ }
+
+ /**
+ * WebCodecs that cannot keep up with the clock (a busy machine, a slow
+ * server answering each byte range late, a long GOP to decode through
+ * before every seek) is worse than the element: a clip whose picture runs
+ * more than LAG_S behind the sound for longer than LAG_FOR plays on a
+ * <video> from there on, and the Approximate line says some clips do.
+ */
+ private keepingUp(url: string, lag: number) {
+ const now = performance.now();
+ if (now - this.restartedAt < 400 || lag <= LAG_S) {
+ this.lagging.delete(url);
+ return;
+ }
+ const since = this.lagging.get(url) ?? now;
+ this.lagging.set(url, since);
+ if (now - since > LAG_FOR) {
+ this.lagging.delete(url);
+ this.codecs?.demote(url, `its frames ran ${Number.isFinite(lag) ? `${lag.toFixed(2)} s` : "a while"} behind the sound`);
+ }
+ }
+
+ /**
+ * A frame drawn while playing, against the second the clock wanted (after a
+ * restart has settled), in frames of the clip's own rate: the frame due is
+ * the latest at or before the clock, so on time is under one frame.
+ */
+ private measure(id: string, at: number, want: number, frame: number) {
+ if (performance.now() - this.restartedAt < 400) return;
+ const off = (want - at) / Math.max(1e-3, frame);
+ this.measured.drawn += 1;
+ if (off >= 1.5 || off < -0.5) {
+ this.measured.off += 1;
+ this.measured.late = [...this.measured.late, { id, want: Math.round(want * 1000) / 1000, at: Math.round(at * 1000) / 1000 }].slice(-12);
+ }
+ this.measured.worst = Math.max(this.measured.worst, Math.abs(off));
+ }
+
+ private reportInfo() {
+ // WebCodecs with every clip it was asked for; "mixed" once one was refused and plays on an element.
+ const refused = !!this.codecs && this.plan.items.some((_, i) => {
+ const u = this.hasVideo(i) ? this.mediaUrl(i) : null;
+ const st = u ? this.codecs!.status(u) : null;
+ return st === "unsupported" || st === "failed";
+ });
+ const picture: EngineInfo["picture"] = !this.codecs ? "element" : refused ? "mixed" : "webcodecs";
+ const info: EngineInfo = { sound: this.sound, picture, silent: this.silent };
+ const key = JSON.stringify(info);
+ if (key !== this.lastInfo) {
+ this.lastInfo = key;
+ this.o.onInfo(info);
+ }
+ }
+
+ private draw(t: number, layers: { i: number; alpha: number; source: CanvasImageSource | null; w: number; h: number }[]) {
+ const el = this.canvas;
+ if (!el) return;
+ const items = this.plan.items;
+ const out: FootageLayer[] = [];
+ let missing = false;
+ for (const l of layers) {
+ if (!l.source || !(l.w > 0)) {
+ missing = true;
+ continue;
+ }
+ const it = items[l.i];
+ const e = this.entries.get(it.id);
+ const src = sourceAt(it, t);
+ const b = e?.blur && this.blurRendered ? e.blur : null;
+ const blur = b && src !== null && (b.from ?? -Infinity) <= src && src <= (b.to ?? Infinity)
+ ? { strength: b.strength ?? BLUR_STRENGTH.default, caption: b.caption ?? BLUR_CAPTION_DEFAULT }
+ : null;
+ out.push({ source: l.source, width: l.w, height: l.h, alpha: l.alpha, blur });
+ }
+ // A frame not decoded yet (a seek, a join whose bytes are still coming): the last picture stays rather than a black flash.
+ if (missing && !out.length && this.shown) return;
+ const key = `${items[this.cur]?.id}|${out.map((l) => `${l.alpha.toFixed(3)}:${l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp}:${l.blur ? 1 : 0}`).join(",")}|${this.bg}|${el.width}x${el.height}`;
+ if (key === this.lastDraw && out.every((l) => !(l.source instanceof HTMLVideoElement) || l.source.paused)) return;
+ this.lastDraw = key;
+ el.dataset.playBlur = out.some((l) => l.blur) ? "on" : "off";
+ el.dataset.playLayers = String(out.length);
+ drawFootageLayers(el, out, this.bg);
+ this.shown = out.length > 0;
+ }
+
+ private publish() {
+ const t = this.now();
+ const ui: EngineUi = { t: Math.round(Math.min(t, this.plan.total) * 1000) / 1000, cur: this.cur, playing: this.playing, ended: this.ended, waiting: this.waiting };
+ const u = this.lastUi;
+ if (Math.abs(u.t - ui.t) > 1 / 30 || u.cur !== ui.cur || u.playing !== ui.playing || u.ended !== ui.ended || u.waiting !== ui.waiting) {
+ this.lastUi = ui;
+ this.o.onUi(ui);
+ }
+ }
+
+ /** How many clips' sound is decoded now, and the decoders open (read by the e2e through a data attribute). */
+ get stats() {
+ return {
+ decoded: this.bank.size, bytes: this.bank.bytes, decoders: this.codecs?.open ?? 0, nodes: this.nodes.length,
+ scheduled: this.measured.nodes, framesDrawn: this.measured.drawn, framesOff: this.measured.off, worstFrames: this.measured.worst, offFrames: this.measured.late,
+ contextTime: this.ctx?.currentTime ?? null, sound: this.sound,
+ };
+ }
+}
diff --git a/umtool/components/projects/review/playEngine/usePlayEngine.ts b/umtool/components/projects/review/playEngine/usePlayEngine.ts
@@ -0,0 +1,104 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { PlayEngine, type EngineEntry, type EngineInfo, type EngineUi, type Plan } from "./engine";
+
+// The Play view's engine (engine.ts) as a hook: PlayCut.tsx hands it the plan
+// and the entries, and gets back what it renders from (`ui`, `failed`,
+// `info`), the transport (seekTo, setPlaying, the speed) and the refs the
+// footage canvas and the two <video> slots attach to. `now()` reads the
+// engine's state at the moment it is called -- the keys and the note
+// composer act on the playhead as it is, not as it was at the last render.
+
+type Args = {
+ plan: Plan;
+ entries: Map<string, EngineEntry>;
+ srcOf: (id: string, file: string) => string;
+ audioOf: (id: string, file: string, from: number, to: number) => string;
+ blurRendered: boolean;
+ bg: string;
+ /** render.transitionStyle: how a crossfade is drawn (a dissolve, or a dip through the ground). */
+ style: string;
+};
+
+export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style }: Args) {
+ const [ui, setUi] = useState<EngineUi>({ t: 0, cur: 0, playing: false, ended: false, waiting: false });
+ const [failed, setFailed] = useState<Record<string, string>>({});
+ const [info, setInfo] = useState<EngineInfo | null>(null);
+ const [rate, setRate] = useState(1);
+ const eng = useRef<PlayEngine | null>(null);
+ const fns = useRef({ srcOf, audioOf });
+ fns.current = { srcOf, audioOf };
+ const latest = useRef({ plan, entries });
+ latest.current = { plan, entries };
+ // Elements attach before the engine exists (refs before effects): held here and handed over.
+ const els = useRef<{ canvas: HTMLCanvasElement | null; slots: (HTMLVideoElement | null)[] }>({ canvas: null, slots: [null, null] });
+
+ useEffect(() => {
+ const pick: "auto" | "element" | "webcodecs" = (() => {
+ try {
+ const p = new URLSearchParams(window.location.search).get("picture");
+ return p === "element" || p === "webcodecs" ? p : "auto";
+ } catch {
+ return "auto";
+ }
+ })();
+ const e = new PlayEngine({
+ srcOf: (id, file) => fns.current.srcOf(id, file),
+ audioOf: (id, file, from, to) => fns.current.audioOf(id, file, from, to),
+ onUi: setUi,
+ onFailed: (id, why) => setFailed((f) => ({ ...f, [id]: why })),
+ onInfo: setInfo,
+ picture: pick,
+ });
+ e.attachCanvas(els.current.canvas);
+ els.current.slots.forEach((el, k) => e.attachSlot(k, el));
+ e.setPlan(latest.current.plan, latest.current.entries);
+ eng.current = e;
+ // A handle for a console and the e2e (play-engine.spec.ts): the engine's own clock and its measurements.
+ (window as Window & { __umtoolPlayEngine?: PlayEngine }).__umtoolPlayEngine = e;
+ return () => {
+ e.destroy();
+ if (eng.current === e) eng.current = null;
+ const w = window as Window & { __umtoolPlayEngine?: PlayEngine };
+ if (w.__umtoolPlayEngine === e) delete w.__umtoolPlayEngine;
+ };
+ }, []);
+
+ useEffect(() => {
+ eng.current?.setPlan(plan, entries);
+ }, [plan, entries]);
+ useEffect(() => {
+ eng.current?.setRate(rate);
+ }, [rate]);
+ useEffect(() => {
+ const e = eng.current;
+ if (!e) return;
+ e.blurRendered = blurRendered;
+ e.bg = bg;
+ e.style = style;
+ }, [blurRendered, bg, style, ui.cur]);
+
+ const canvasRef = useCallback((el: HTMLCanvasElement | null) => {
+ els.current.canvas = el;
+ eng.current?.attachCanvas(el);
+ }, []);
+ const slotRef0 = useCallback((el: HTMLVideoElement | null) => {
+ els.current.slots[0] = el;
+ eng.current?.attachSlot(0, el);
+ }, []);
+ const slotRef1 = useCallback((el: HTMLVideoElement | null) => {
+ els.current.slots[1] = el;
+ eng.current?.attachSlot(1, el);
+ }, []);
+ const onMediaError = useCallback((k: number) => eng.current?.slotFailed(k), []);
+ const seekTo = useCallback((t: number) => eng.current?.seek(t), []);
+ const setPlaying = useCallback((on: boolean) => eng.current?.setPlaying(on), []);
+ const now = useCallback(() => {
+ const e = eng.current;
+ return e ? { t: e.now(), cur: e.cur, playing: e.playing, rate: e.rate } : { t: 0, cur: 0, playing: false, rate: 1 };
+ }, []);
+ const stats = useCallback(() => eng.current?.stats ?? null, []);
+
+ return { ui, failed, info, rate, setRate, seekTo, setPlaying, now, stats, canvasRef, slotRef0, slotRef1, onMediaError };
+}
diff --git a/umtool/components/projects/review/playEngine/useRenderCuts.ts b/umtool/components/projects/review/playEngine/useRenderCuts.ts
@@ -0,0 +1,54 @@
+"use client";
+
+import { useEffect, 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;
+};
+
+const MEASURING: RenderCuts = { state: "measuring", cuts: null, style: "fade", montage: false, why: null };
+
+export function useRenderCuts(project: string, take: string | null, key: string): RenderCuts {
+ // Each answer says which cut it is for: another cut's (a take switched to, before its own
+ // answer) is never returned -- not even for the render between the switch and its effect.
+ const which = `${project}|${take ?? ""}`;
+ const [got, setGot] = useState<RenderCuts & { for: string }>({ ...MEASURING, for: which });
+ useEffect(() => {
+ let live = true;
+ 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}`, for: which });
+ 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, for: which });
+ })
+ .catch((e: unknown) => {
+ if (live) setGot({ state: "estimate", cuts: null, style: "fade", montage: false, why: e instanceof Error ? e.message : String(e), for: which });
+ });
+ return () => {
+ live = false;
+ };
+ }, [project, take, key, which]);
+ // The same cut with an edge moved: its edges stand until the new ones are measured (only what moved is).
+ return got.for === which ? got : MEASURING;
+}
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -212,8 +212,7 @@ browser. **Render this clip** is the pixel-true check of all of that but the joi
(`/projects/<p>/play?take=<id>`) — plays the WHOLE cut in this browser in its final look, for iterating without a
render: every entry in timeline order, each clip from its cached source window (the bench's media route, an
excerpt of a long recording), the live preview's chrome over it on ONE cut clock — the rail's pip, the tally, the
-stamps, the markers and the finale advance as in the render — and the next clip loaded behind the playing one so
-the cut is near-seamless. A take plays the project's manifest **as it is now** with the take's style patch and its
+stamps, the markers and the finale advance as in the render — at the render's own edges (below). A take plays the project's manifest **as it is now** with the take's style patch and its
own patch (a take's own `timeline` included), from `takes/<id>/take.json` or — not rendered yet — a recipe that
names it; its pages are composed under `takes/<id>/out/`, never over the project's. `render.blur: "off"` on the
take plays its blurred clips as recorded.
@@ -227,12 +226,38 @@ take plays its blurred clips as recorded.
| the assistant on a note (its reply lands on the note, its edits wait for **Apply all**), or on every open note at once | a note's **Send to the assistant**; **Send N open notes to the assistant** | — |
| every key | **?** | ? |
-What it does not do (the line under the picture says so): each crossfade is a **hard cut at its middle** (where
-the deck hands its title over); cards, teasers and images are **placeholders** with their heading for their
-seconds; the edges are not snapped to silence; the sound is the source's (no room, no Audio knobs); the clock is the
-estimate's (a carrying clip's posts hold included when the cut has a deck). A clip whose source window is not on
-disk is a named placeholder that plays on — fetch it from the Cut tab. **Reload the cut** reads an edit made
-elsewhere.
+**It plays the render's cut, edges first.** The build snaps every clip edge to the nearest silence within
+`render.snapWindow` (on the Huck cut, starts up to 1.0 s earlier and ends up to 1.0 s later than the manifest's), so
+Play asks where it will cut — `GET /api/report/cut-points?project=<p>[&take=<t>]`, the build's own source resolution,
+silencedetect and snap (`report-to-video/cut-points.mjs`, `snap.mjs`; room at the edges and `render.loudness` too),
+measured once per clip and cached under the umtool cache's `cut-points/` — and plays each clip from the render's
+first source second to its last, every later entry moved by what the clips before it gained or lost. The clip bench
+draws the same edges over its waveform as faint ghosts with their offset (**render: +0.52 s**), snapped live from
+the measured silences as an edge is dragged.
+
+**The sound is on one Web Audio clock.** Each clip's sound is decoded (ffmpeg's decode of the cached window, the
+bench's `/api/report/audio`; only the clips around the playhead are held) and scheduled back to back on one
+AudioContext, sample-exact at the render's edges: a crossfade is the build's two linear ramps over the overlap, the
+loudness gain, room's muted edges, the clip's own `audio` knobs and the mute mark are gain automation, and a speed
+time-stretches at the voice's pitch as the bench does. The clock of the whole view — the rail, the tally, the
+stamps, the finale, a note's anchor — is that context's time mapped through the plan; the chrome (composed on the
+estimate's clock) is seeked by the source second playing, so a stamp lands on its word. A clip whose sound is not
+decoded yet holds the clock at its first second (**loading…**), nothing skipped.
+
+**The picture follows the clock**: by WebCodecs where the browser has it — each clip decoded from its window a few
+frames ahead, the frame due at the audio clock drawn, a crossfade a real dissolve (a `fadeblack` join dips through
+the ground) — else on two `<video>` elements slaved to the clock (requestVideoFrameCallback, the speed nudged past a
+frame of drift, re-seeked past a quarter second). `?picture=element` forces the elements, to compare.
+
+What it still does not do (the line under the picture says so, with which sound and picture paths are playing):
+cards, teasers and images are **placeholders** with their heading for their seconds; a push, a wipe or a whip is
+drawn as a dissolve; the limiter after the loudness gain is not applied; a montage's phrase cuts are snapped as plain
+cuts. A clip whose source window is not on disk is a named placeholder that plays on (silent) — fetch it from the
+Cut tab. **Reload the cut** reads an edit made elsewhere, and the edges are measured again for what moved. **Edit this clip** (E) and the bench's **Back to the cut** come back
+to the same clip by its id and then by the SOURCE second you left (`?clip=&at=`, the offset turned into a source
+second once the render's edges are in), so an edit that moves the clip's start does not move you off the word. The
+bench draws the render's cut over its waveform and, on a phone, on the edge strip (a faint line, and its offset under
+each edge).
The notes are the project's `notes.json` ([notes.md](notes.md)): `umtool notes <p>` prints each with its cut second,
its clip and source, and — for a take — that its patch is the file to edit. **Send to the assistant** is the video
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1861,7 +1861,7 @@ makeLivePreviewFixture({ reports, deckManifest, cachedWindow: path.join(REPORT,
makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// The same cut for Play → Edit this clip → Back (phone-walk.spec.ts), which WRITES
// an edge: its own copy, so play-cut.spec's clock is never moved.
-makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-edit-fixture", title: "The Play Edit Fixture" });
+makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-edit-fixture", title: "The Play Edit Fixture", video: "vid1" });
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs
@@ -1,13 +1,16 @@
// What play-cut.spec.ts plays (umtool/docs/knobs.md, "Play the cut"): a short deck cut on
-// vid1 (the fixture corpus's synthetic source, its 0-9 s window cached in
-// out/clips-raw), never built -- the Play view plays it from the cached
+// playvid (the fixture's synthetic vid1 window -- tone, and silences at 2.9-3.1
+// and 5.9-6.1 -- cached in out/clips-raw under a recording id of its own: the
+// corpus's vid1 gains wider windows as other specs fetch, and the render's
+// edges, and so Play's clock, must not depend on which spec ran first), never built -- the Play view plays it from the cached
// 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)
+// c01 playvid 1.0-3.0 c02 playvid 3.5-5.5 (k1 at 4.5) k01 card 1.5 s
+// c03 nofetch 2-4 (no window on disk) c04 playvid 6.0-8.0 (k2, counts 2)
// sections 0 (c01, c02) and 1 (c03, c04); one counter, "Seizures"
//
// Synthetic, like every fixture.
@@ -15,22 +18,23 @@ import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
/**
- * @param {{ reports: string, deckManifest: Function, cachedWindow: string, name?: string, title?: string }} o
+ * @param {{ reports: string, deckManifest: Function, cachedWindow: string, name?: string, title?: string, video?: string }} o
* `name`: a second copy under another name (play-edit-fixture, which a spec writes to).
+ * `video`: the recording id its clips cut (playvid; play-edit-fixture's walk needs vid1's cues).
*/
-export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = "play-cut-fixture", title = "The Play Cut Fixture" }) {
+export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = "play-cut-fixture", title = "The Play Cut Fixture", video = "playvid" }) {
const dir = path.join(reports, name);
mkdirSync(dir, { recursive: true });
const timeline = [
- { type: "clip", id: "c01", video: "vid1", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } },
+ { type: "clip", id: "c01", video, start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } },
{
- type: "clip", id: "c02", video: "vid1", start: 3.5, end: 5.5, cite: 4, section: 0, lock: true, quote: "And this one runs on", onscreen: { title: "2 Dec 2024" },
+ type: "clip", id: "c02", video, start: 3.5, end: 5.5, cite: 4, section: 0, lock: true, quote: "And this one runs on", onscreen: { title: "2 Dec 2024" },
claim: { id: "k1", verdict: "CORROBORATED", at: 4.5 },
},
{ type: "card", id: "k01", style: "chapter", seconds: 1.5, heading: "Between the clips" },
{ type: "clip", id: "c03", video: "nofetch", start: 2.0, end: 4.0, cite: 2, section: 1, lock: true, quote: "never fetched" },
{
- type: "clip", id: "c04", video: "vid1", start: 6.0, end: 8.0, cite: 6, section: 1, lock: true, quote: "of that it finishes here.", onscreen: { title: "27 Feb 2025" },
+ type: "clip", id: "c04", video, start: 6.0, end: 8.0, cite: 6, section: 1, lock: true, quote: "of that it finishes here.", onscreen: { title: "27 Feb 2025" },
claim: { id: "k2", verdict: "CORROBORATED", count: 2 },
},
];
@@ -40,7 +44,7 @@ export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name =
m.render.chrome = { ...m.render.chrome, factcheck: { verdicts: { CORROBORATED: { label: "Seizures", color: "#6fa8dc" } }, stamp: { seconds: 1 } } };
writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
- copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", `${video}_0.00-9.00.mp4`));
// A made take with its own timeline (a JSON merge patch replaces the list).
mkdirSync(path.join(dir, "takes", "short"), { recursive: true });
writeFileSync(
@@ -56,6 +60,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", `${video}_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,14 @@ 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), in the encode's whole frames (15 fps here). On the fixture's window (playvid)
+// (silences 2.90-3.11 and 5.92-6.11) c01 plays 1.000-3.082 (2.133 s), c02
+// 3.011-6.101 (3.133 s), c04 6.007-8.000 (2 s), so with the 0.2 s
+// crossfades: c01 0-2.133 (shown to 2.033), c02 1.933-5.067 (shown 2.033-
+// 4.967), k01 4.867-6.367 (shown to 6.267), c03 6.167-8.167 (shown to
+// 8.067), c04 7.967-9.967. play-engine.spec.ts covers the engine itself.
// Screenshots at 1280 and 390 px land in test-results. Fixture:
// e2e/fixtures/play-cut-fixture.mjs.
// ---------------------------------------------------------------------------
@@ -23,6 +31,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 +44,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 +66,12 @@ 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 2.033 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);
+ // c02's picture is drawn (whichever path the browser plays it on).
+ await expect(page.locator("[data-play-footage]")).toHaveAttribute("data-play-layers", /^[12]$/, { timeout: 15_000 });
+ await expect.poll(() => tNow(page)).toBeGreaterThan(2.033);
// 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.967, 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.967, 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.967-6.267).
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(2.033, 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.967)).toBeLessThan(0.15);
// ? lists the keys; Esc closes it.
await page.keyboard.press("?");
@@ -114,19 +127,21 @@ 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"); // 2.033 + 5 = 7.033: c03 (shown to 8.067)
+ await page.keyboard.press("n"); // 8.067: 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");
- // Paused, the clip's frame is in the picture (the fixture's window is dark green), not a black box.
+ await expect(page.locator("[data-play-note-add]")).toHaveText("Note at 00:08.0");
+ // Paused, the clip's frame is in the picture (the fixture's window is dark green), not a black box --
+ // half of it: c04's first shown second is the middle of its crossfade from c03 (no media: the ground).
await expect
.poll(
() =>
page.locator("[data-play-footage]").evaluate((c: HTMLCanvasElement) => {
const [r, g, b] = c.getContext("2d")!.getImageData(Math.floor(c.width / 2), Math.floor(c.height / 2), 1, 1).data;
- return g > 60 && r < 40 && b < 40;
+ return g > 35 && g > r + 20 && g > b + 20;
}),
{ timeout: 15_000 },
)
@@ -134,7 +149,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", "8.07");
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,27 +157,29 @@ 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:08.0");
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.967 at
+ // source 6.007, so 8.067 is 6.107, stored to the hundredth), 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: 8.07, entry: "c04", sourceT: 6.11, ask: "trim" });
expect(n.author).toBe("operator");
// Elsewhere, then ] (the next note) and the note's timecode: back where it was taken.
await page.locator('[data-play-row="c01"]').press("Enter");
await expect(root(page)).toHaveAttribute("data-play-item", "c01");
+ // (A note seeks by its clip and source second: 6.11 in c04 is 8.070 on this clock.)
await page.keyboard.press("]");
await expect(root(page)).toHaveAttribute("data-play-item", "c04");
- expect(await tNow(page)).toBeCloseTo(6.9, 1);
+ expect(Math.abs((await tNow(page)) - 8.07)).toBeLessThan(0.011);
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(Math.abs((await tNow(page)) - 8.07)).toBeLessThan(0.011);
// 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 +203,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 segment ends (2.133 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.133, 2);
});
diff --git a/umtool/e2e/play-engine.spec.ts b/umtool/e2e/play-engine.spec.ts
@@ -0,0 +1,148 @@
+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's engine (components/projects/review/playEngine/): the cut
+// plays like the finished video, 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
+// - the CLOCK is the sound's: one AudioContext, every clip a node started
+// ahead of its time (so on the sample); suspend the context and the
+// whole view stops with it
+// - the PICTURE follows the clock: WebCodecs where the browser has it (a
+// dissolve is two layers), <video> elements otherwise (?picture=element)
+//
+// Fixture: e2e/fixtures/play-cut-fixture.mjs's play-engine-fixture (the
+// play-cut cut, which this spec WRITES). On the fixture's window (playvid; 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; in whole frames at 15 fps c01 lasts 2.133 s, so c02's
+// segment starts at 1.933 (the 0.2 s crossfade before c01's end).
+// ---------------------------------------------------------------------------
+
+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; run: number; from: number; to: 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 clock is the sound's: one AudioContext, nodes started ahead of their time; suspend it and the view stops", async ({ page }) => {
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ await page.locator("[data-play-toggle]").click();
+ await expect(root(page)).toHaveAttribute("data-play-sound", "webaudio", { timeout: 15_000 });
+ await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(0.4);
+ // Through the c01 → c02 join (shown to 2.033, crossfading 1.933-2.133).
+ await expect(root(page)).toHaveAttribute("data-play-item", "c02", { timeout: 20_000 });
+ await expect.poll(() => tNow(page), { timeout: 10_000 }).toBeGreaterThan(2.4);
+ // The context stops: so does the clock, and everything that reads it.
+ await page.evaluate(() => (window as unknown as { __umtoolPlayEngine: { ctx: AudioContext } }).__umtoolPlayEngine.ctx.suspend());
+ await page.waitForTimeout(150);
+ const held = await tNow(page);
+ await page.waitForTimeout(600);
+ expect(await tNow(page)).toBe(held);
+ await page.evaluate(() => (window as unknown as { __umtoolPlayEngine: { ctx: AudioContext } }).__umtoolPlayEngine.ctx.resume());
+ await expect.poll(() => tNow(page), { timeout: 5_000 }).toBeGreaterThan(held + 0.2);
+ const s = await stats(page);
+ // Every node was started AHEAD of its time (Web Audio then starts it on the sample), and the two
+ // clips meet as the build joins them, on one clock: c02 sounds from its segment's first second
+ // (1.933), c01 to its source's last (2.082: the rest of its last frame is the encode's silence).
+ // (One run of the clock: a restart -- the chrome composing, a seek -- schedules again.)
+ const c02 = s.scheduled.find((n) => n.id === "c02")!;
+ const c01 = s.scheduled.find((n) => n.id === "c01" && n.run === c02?.run)!;
+ expect(c01 && c02).toBeTruthy();
+ expect(Math.max(...s.scheduled.map((n) => n.late))).toBeLessThanOrEqual(0);
+ expect(c02.from).toBeCloseTo(1.933, 3);
+ expect(c01.to).toBeCloseTo(2.082, 3);
+ expect(Math.abs(c02.at - c01.at - (c02.from - c01.from))).toBeLessThan(1e-6);
+ expect(Math.abs(c01.stop - c01.at - (c01.to - c01.from))).toBeLessThan(1e-6);
+ console.log(`play-engine: joins ${JSON.stringify(s.scheduled)}; frames drawn ${s.framesDrawn}, more than 1.5 frames off ${s.framesOff}, worst ${s.worstFrames.toFixed(2)} frames`);
+ await page.keyboard.press("k");
+});
+
+test("the picture: WebCodecs in this browser, a dissolve is two layers; the <video> path does the same", async ({ page }) => {
+ for (const [q, want] of [["", "webcodecs"], ["?picture=element", "element"]] as const) {
+ await page.goto(urls.playHref(PROJECT) + q);
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ await page.locator('[data-play-row="c02"]').press("Enter");
+ await expect(root(page)).toHaveAttribute("data-play-picture", want, { timeout: 15_000 });
+ await expect(page.locator("[data-play-approximate]")).toContainText(want === "webcodecs" ? "picture: WebCodecs" : "picture: <video>");
+ // c02's first shown second (2.033) is inside the crossfade from c01 (1.933-2.133): both clips are drawn.
+ await expect(page.locator("[data-play-footage]")).toHaveAttribute("data-play-layers", "2", { timeout: 15_000 });
+ // Played on past it: one layer, and the frames drawn are the clock's.
+ await page.locator("[data-play-toggle]").click();
+ await expect.poll(() => tNow(page), { timeout: 15_000 }).toBeGreaterThan(2.6);
+ await expect(page.locator("[data-play-footage]")).toHaveAttribute("data-play-layers", "1");
+ await expect.poll(async () => (await stats(page)).framesDrawn, { timeout: 10_000 }).toBeGreaterThan(10);
+ const s = await stats(page);
+ console.log(`play-engine ${want}: frames drawn ${s.framesDrawn}, more than 1.5 frames off ${s.framesOff}, worst ${s.worstFrames.toFixed(2)}; decoders open ${s.decoders}`);
+ // Bounded: never more decoders than the clips on screen and the next.
+ expect(s.decoders).toBeLessThanOrEqual(3);
+ await page.keyboard.press("k");
+ }
+});
+
+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");
+ // (The manifest's play window, what the bench edits, beside it.)
+ await expect(root(page)).toHaveAttribute("data-play-source", "1.2-3");
+
+ // On a phone the edge strip carries the same: a faint line on its waveform, the offset under each edge.
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.goto(urls.clipBenchHref(PROJECT, "c01"));
+ await expect(page.locator('[data-edge-row="end"] [data-strip-render-offset]')).toHaveText("render: +0.08 s", { timeout: 30_000 });
+ await expect(page.locator('[data-edge-row="start"] [data-strip-render-offset]')).toHaveText("render: here");
+ await expect(page.locator('[data-strip-render-edge="end"]')).toHaveCount(1);
+});
diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs
@@ -0,0 +1,260 @@
+// WHERE THE RENDER WILL CUT EACH CLIP, before it renders (umtool/docs/knobs.md,
+// "Play the cut"): the edges the Play view plays and the clip bench draws as
+// ghost markers. The build snaps every clip edge to the nearest silence
+// within `render.snapWindow` (measured on the Huck cut: starts up to 1.0 s
+// earlier, ends up to 1.0 s later than the manifest's), and a preview that
+// plays the manifest's edges plays a different cut -- the join is where it
+// differs most, and the join is what a preview is for.
+//
+// ONE IMPLEMENTATION. Everything that decides an edge is the build's own code:
+// the same file over the same span (build-video.mjs onDiskClipSource and
+// alignedClipSource -- the build's resolution, never the bench's widest
+// window: the silence threshold is relative to what is measured), the same
+// silencedetect (cut-points.mjs detectSilence), the same snap (snap.mjs
+// renderCut), room at the edges (cut-points.mjs roomOfCut) and the loudness
+// gain (render.loudness). cutPoints.test.mjs renders a fixture and checks the
+// cut records against this, edge for edge.
+//
+// CACHED ON DISK, per measurement, under UMTOOL_CACHE_DIR/cut-points/: the
+// silences by (file, its mtime and size, the span measured, silenceMinDur,
+// silenceRelDb); a file's clock offset by (file, mtime, size); a loudness by
+// (file, mtime, size, span). The snap itself is arithmetic on the cached
+// silences, so moving a clip's cut (the bench's edge drag) costs nothing, and
+// only a change of its extent -- a different span to measure -- runs ffmpeg
+// again. Nothing here fetches: a clip with no source on disk is `missing`.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ DEFAULT_VARIANT, FFMPEG_BIN, alignedClipSource, localSources, onDiskClipSource, probeMedia, selectVariant,
+} from "umtool-report-to-video/build-video";
+import { detectRoomSilences, detectSilence, lookWords, measureLoudnessWith, readLookSources, roomOfCut } from "umtool-report-to-video/cut-points";
+import { playWindow, transitionOf } from "umtool-report-to-video/deck";
+import { clipAudioOf } from "umtool-report-to-video/clip-audio";
+import { createLocalMedia, hasLocalMedia } from "umtool-report-to-video/local-media";
+import { loudnessGain, montageOn, parseIntegratedLoudness } from "umtool-report-to-video/montage";
+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";
+
+/** Bump when what is cached changes shape. */
+const CACHE_VERSION = 1;
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r3 = (v) => Number(v.toFixed(3));
+
+/** The cache directory (a function: the env is read when the route runs, as the e2e fixture sets it). */
+const cacheDir = () => path.join(/* turbopackIgnore: true */ CACHE_DIR, "cut-points");
+
+/** A file's identity for a cache key: the path, its mtime and size. null when it is gone. */
+async function fileKey(file) {
+ const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);
+ return st ? `${file}|${Math.round(st.mtimeMs)}|${st.size}` : null;
+}
+
+/**
+ * A value computed once per key and kept on disk (tmp + rename), and in this
+ * process while it lives. A failed computation is not cached.
+ *
+ * @template T
+ * @param {string} kind
+ * @param {string} key
+ * @param {() => Promise<T>} make
+ * @returns {Promise<T>}
+ */
+const memo = new Map();
+async function cached(kind, key, make) {
+ const h = createHash("sha1").update(`${CACHE_VERSION}|${kind}|${key}`).digest("hex");
+ if (memo.has(h)) return memo.get(h);
+ const file = path.join(/* turbopackIgnore: true */ cacheDir(), `${kind}-${h}.json`);
+ const p = (async () => {
+ const have = await readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null);
+ if (have && have.key === key) return have.value;
+ const value = await make();
+ try {
+ await mkdir(/* turbopackIgnore: true */ cacheDir(), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify({ key, value }));
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch {
+ // A cache that cannot be written is a slower route, not a broken one.
+ }
+ return value;
+ })();
+ memo.set(h, p);
+ p.catch(() => memo.delete(h));
+ if (memo.size > 2000) memo.delete(memo.keys().next().value);
+ return p;
+}
+
+/**
+ * The manifest Play plays (the project's, or a take's, the default cut) and
+ * where the build would look for each clip's source.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string | null} take
+ */
+async function cutContext(project, take) {
+ let manifest = await readManifest(project.dir);
+ if (!manifest) throw new Error("this project has no video.manifest.json");
+ let outRoot = path.join(/* turbopackIgnore: true */ project.dir, "out");
+ if (take) {
+ const { resolveTakeManifest, takePlayDir } = await import("./takeManifest.mjs");
+ manifest = (await resolveTakeManifest(project.dir, take)).manifest;
+ outRoot = path.join(/* turbopackIgnore: true */ takePlayDir(project.dir, take), "out");
+ }
+ const selected = selectVariant(manifest, DEFAULT_VARIANT);
+ const render = selected.render ?? {};
+ const provenance = selected.provenance ?? {};
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ // A take renders into its own out/ (its clips-raw empty, as a rule: its
+ // sources are the corpus's windows or the project's cache); the project's
+ // raw cache is looked in after it, as the bench does.
+ const locals = [...new Set([outRoot, path.join(/* turbopackIgnore: true */ project.dir, "out")])].map((root) =>
+ localSources({ rawDir: path.join(/* turbopackIgnore: true */ root, "clips-raw"), channelsDir, channelSlug: provenance.channelSlug ?? null }),
+ );
+ const localMedia = createLocalMedia({ baseDir: project.dir, allowAbsolute: render.allowAbsoluteSrc === true });
+ return { selected, render, provenance, channelsDir, locals, localMedia };
+}
+
+/**
+ * Each clip's render cut, in SOURCE seconds:
+ *
+ * cutStart / cutEnd where its segment starts and ends (`<id>.cut.json`'s
+ * `start`/`end`): the picture's span, room included
+ * footage the segment's length in the cut: that span in whole
+ * frames, as the encode makes it
+ * snapped { start, end }: which edge moved to a silence
+ * sound [from, to] the sound is heard over, when room mutes
+ * an edge (else the whole segment)
+ * gainDb render.loudness's gain for the cut (none: absent)
+ * audio the clip's own audio knobs (clip-audio.mjs), absent when none
+ * playFrom / playTo the play window it was snapped from (deck.mjs playWindow)
+ * silences, fetchStart, window what was measured, so a client (the
+ * bench, dragging an edge) can snap a new cut itself
+ * with snap.mjs, on the same numbers
+ * montage true when render.montage cuts it (a phrase cut this
+ * does not model: its edges are snapped as a plain cut)
+ * missing no source on disk (nothing else is said)
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ take?: string | null, clips?: string[] | null, concurrency?: number }} [opts]
+ */
+export async function cutPointsFor(project, { take = null, clips = null, concurrency = 2 } = {}) {
+ const ctx = await cutContext(project, take);
+ const { selected, render } = ctx;
+ const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string");
+ const want = clips ? new Set(clips) : null;
+ const montage = montageOn(render);
+ const D = transitionOf(render);
+ const first = timeline[0]?.id ?? null;
+ const targets = timeline.filter((e) => e.type === "clip" && (hasLocalMedia(e) || (fin(e.start) && fin(e.end))) && (!want || want.has(e.id)));
+ const look = { promise: null };
+ const out = new Array(targets.length);
+ let next = 0;
+ const work = async () => {
+ for (;;) {
+ const i = next++;
+ if (i >= targets.length) return;
+ const e = targets[i];
+ try {
+ out[i] = await clipCutPoints(e, { ...ctx, montage, D, first: first === e.id, look, projectDir: project.dir });
+ } catch (err) {
+ out[i] = { id: e.id, error: err instanceof Error ? err.message : String(err) };
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, targets.length)) }, work));
+ 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). */
+async function clipCutPoints(entry, ctx) {
+ const { render, locals, localMedia, montage, D } = ctx;
+ let src = null;
+ for (const local of locals) {
+ src = await onDiskClipSource(entry, null, render, local, { localMedia });
+ if (src) break;
+ }
+ if (!src) return { id: entry.id, missing: true };
+ const fk = await fileKey(src.path);
+ if (!fk) return { id: entry.id, missing: true };
+ const { log: _log, ...disk } = src;
+ // The file's clock (a late-starting picture moves fetchStart), once per file.
+ const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0);
+ const fetchStart = disk.fetchStart + offset;
+ const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null;
+ const k = snapKnobs(render);
+ const sil = await cached(
+ "silences",
+ `${fk}|${scan ? `${scan.from}-${scan.to}` : "whole"}|${k.silenceMinDur}|${k.silenceRelDb}`,
+ () => detectSilence(src.path, render, scan, { ffmpeg: FFMPEG_BIN }),
+ );
+ const pw = playWindow(entry, render);
+ const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render });
+ const { cutA, cutB } = cut.file;
+ let segA = cutA;
+ let segB = cutB;
+ /** @type {[number, number] | null} */
+ let sound = null;
+ // Room at the edges: only with a join to make room for, never in a montage.
+ if (D > 0 && !montage && clipRoom(entry, render)) {
+ if (!ctx.look.promise) ctx.look.promise = readLookSources(ctx.projectDir);
+ const lookSrc = await ctx.look.promise;
+ const provenance = ctx.provenance;
+ const room = await roomOfCut({
+ entry, render, D, first: ctx.first, fetchStart, cutA, cutB, file: src.path,
+ duration: await cached("duration", fk, async () => (await probeMedia(src.path)).duration ?? null),
+ words: (from, to) => lookWords(entry, provenance, lookSrc, from, to, {
+ channelsDir: ctx.channelsDir,
+ cues: async (e) => (await cuesForSource(ctx.projectDir, { video: e.video, channel: e.channel ?? provenance.channelSlug ?? null }, -Infinity, Infinity))?.cues ?? [],
+ }),
+ silences: (from, to) => detectRoomSilences(src.path, from, to, { ffmpeg: FFMPEG_BIN }),
+ });
+ if (room) {
+ segA = room.plan.picA;
+ segB = room.plan.picB;
+ sound = room.record.sound;
+ }
+ }
+ // The segment's length as its encode makes it: whole frames, the last one
+ // begun counted (the build's cutOffsets sums the probed frames; measured on
+ // the Huck walk, 34 of 51 segments exactly this, the rest one frame more).
+ const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30;
+ const row = {
+ id: entry.id,
+ window: path.basename(src.path),
+ footage: Number((Math.ceil((segB - segA) * fps - 1e-6) / fps).toFixed(6)),
+ fetchStart: r3(fetchStart),
+ silences: sil,
+ playFrom: pw.from,
+ playTo: pw.to,
+ cutStart: r3(fetchStart + segA),
+ cutEnd: r3(fetchStart + segB),
+ snapped: cut.snapped,
+ ...(sound ? { sound } : {}),
+ ...(montage ? { montage: true } : {}),
+ };
+ const target = loudnessTargetOf(render);
+ if (!montage && target != null) {
+ const from = cutA;
+ const to = sound ? sound[1] - fetchStart : cutB;
+ const measured = await cached("loudness", `${fk}|${from.toFixed(3)}-${to.toFixed(3)}`, () =>
+ measureLoudnessWith(src.path, from, to, parseIntegratedLoudness, { ffmpeg: FFMPEG_BIN }),
+ );
+ row.gainDb = loudnessGain(measured, target);
+ }
+ 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;
+}
+
+/** Room's fade (seconds) at a muted edge, for the player: the build's afade length. */
+export const ROOM_FADE = ROOM.fade;
diff --git a/umtool/lib/report/cutPoints.test.mjs b/umtool/lib/report/cutPoints.test.mjs
@@ -0,0 +1,161 @@
+// The render's cut, from the render's code: a fixture RENDERED (build-video.mjs
+// buildVideo) and read back through the cut-points route's function
+// (cutPoints.mjs cutPointsFor) -- every clip's start, end, which edge
+// snapped, room's audible span and the loudness gain must be the cut
+// records', to the millisecond. And the route measures once: a second read is
+// the cache, and a moved cut (the bench's edge drag) re-snaps on the cached
+// silences without ffmpeg.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { readdir, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+// The corpus and the cache: set before the build (cues.mjs) and paths.mjs are loaded.
+const CORPUS = mkdtempSync(path.join(os.tmpdir(), "cutpoints-corpus-"));
+const CACHE = mkdtempSync(path.join(os.tmpdir(), "cutpoints-cache-"));
+process.env.CHANNELS_DIR = CORPUS;
+process.env.UMTOOL_CACHE_DIR = CACHE;
+
+const { buildVideo, setProgressMode } = await import("umtool-report-to-video/build-video");
+const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("umtool-report-to-video/brand");
+const { renderCut } = await import("umtool-report-to-video/snap");
+const { cutPointsFor } = await import("./cutPoints.mjs");
+
+test.after(async () => {
+ await rm(CORPUS, { recursive: true, force: true });
+ await rm(CACHE, { recursive: true, force: true });
+});
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const CHANNEL = "synth";
+const PALETTE = { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a", amber: "#ffc860" };
+const RENDER = {
+ width: 320, height: 180, fps: 30, audioRate: 48000, audioChannels: 2, preset: "ultrafast",
+ headerHeight: 0, footerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ fetchPad: 1, snapWindow: 0.8, silenceMinDur: 0.15, snapLead: 0.3, snapTail: 0.4,
+};
+
+const dir = path.join(CORPUS, CHANNEL, "data", "vid1");
+mkdirSync(dir, { recursive: true });
+writeFileSync(path.join(CORPUS, CHANNEL, "config.json"), JSON.stringify({ name: "Synth" }));
+writeFileSync(path.join(dir, "transcript.cues.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 20, uploadDate: "20240102", cues: [] }));
+writeFileSync(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid1", title: "Synthetic", duration: 20 }));
+
+/**
+ * A project cut from one 20 s window in out/clips-raw: a 440 Hz tone with
+ * gaps (pauses between "words") at 2.6-2.9, 5.4-5.9, 8.1-8.4, 11.2-11.6,
+ * 14.5-15.2 -- so every edge below has a pause within the snap window, and
+ * one (c3's start) has none.
+ */
+async function project(render = {}) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "cutpoints-"));
+ mkdirSync(path.join(root, "out", "clips-raw"), { recursive: true });
+ const raw = path.join(root, "out", "clips-raw", "vid1_0.00-20.00.mp4");
+ const gaps = [[2.6, 2.9], [5.4, 5.9], [8.1, 8.4], [11.2, 11.6], [14.5, 15.2]];
+ const vol = gaps.map(([a, b]) => `volume=enable='between(t,${a},${b})':volume=0`).join(",");
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=gray:s=320x180:r=30:d=20",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=20",
+ "-filter_complex", `[1:a]${vol},volume=0.5[a]`,
+ "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "cutpoints", title: "Cut points",
+ provenance: { channelSlug: CHANNEL, channelsDir: CORPUS },
+ render: { ...RENDER, ...render },
+ timeline: [
+ // A cut inside the extent (the lead-in before it): both edges snap.
+ { type: "clip", id: "c1", channel: CHANNEL, video: "vid1", start: 2, end: 6, cutStart: 3.3, cutEnd: 5.2, cite: 3, quote: "q" },
+ // The extent alone: the start snaps back to 8.4 - lead, the end to 11.2 + tail.
+ { type: "clip", id: "c2", channel: CHANNEL, video: "vid1", start: 8.2, end: 11.0, cite: 9, quote: "q" },
+ // No pause near its start (12.6): it stays; the end snaps into the long pause.
+ { type: "clip", id: "c3", channel: CHANNEL, video: "vid1", start: 12.6, end: 14.4, cite: 13, quote: "q" },
+ ],
+ }));
+ return { root, manifestPath };
+}
+
+const quiet = () => setProgressMode(() => {});
+const record = async (root, id) => JSON.parse(await readFile(path.join(root, "out", "sourced", "segments", `${id}.cut.json`), "utf8"));
+
+async function agree(p, render) {
+ await buildVideo({ manifestPath: p.manifestPath, opts: { noNetwork: true, noXfade: render.transition === 0 } });
+ const got = await cutPointsFor({ id: "fixture", dir: p.root });
+ assert.equal(got.clips.length, 3);
+ for (const c of got.clips) {
+ const rec = await record(p.root, c.id);
+ assert.equal(c.cutStart, rec.start, `${c.id} start`);
+ assert.equal(c.cutEnd, rec.end, `${c.id} end`);
+ assert.deepEqual(c.snapped, rec.snapped, `${c.id} snapped`);
+ if (rec.room) assert.deepEqual(c.sound, rec.room.sound, `${c.id} room's sound`);
+ else assert.equal(c.sound, undefined, `${c.id} has no room`);
+ if (rec.loudness) assert.equal(c.gainDb, rec.loudness.gain, `${c.id} loudness gain`);
+ else assert.equal(c.gainDb, undefined);
+ }
+ return got;
+}
+
+test("cut points: the route's edges are the render's cut records, edge for edge", { skip: !have && "needs ffmpeg" }, async () => {
+ quiet();
+ const p = await project({ transition: 0 });
+ try {
+ const got = await agree(p, { transition: 0 });
+ const byId = Object.fromEntries(got.clips.map((c) => [c.id, c]));
+ // Something actually moved, both ways: c1's start earlier than its play window, c2's end later.
+ assert.ok(byId.c1.cutStart < byId.c1.playFrom - 0.05, "c1's start snaps earlier");
+ assert.ok(byId.c2.cutEnd > byId.c2.playTo + 0.05, "c2's end snaps later");
+ assert.deepEqual(byId.c3.snapped, { start: false, end: true });
+ // The client's snap (the bench's ghost marker) from the silences the route returned: the same edges.
+ for (const c of got.clips) {
+ const again = renderCut({ sil: c.silences, fetchStart: c.fetchStart, playFrom: c.playFrom, playTo: c.playTo, render: { ...RENDER, transition: 0 } });
+ assert.equal(again.start, c.cutStart);
+ assert.equal(again.end, c.cutEnd);
+ }
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("cut points: with room at the edges and even loudness, the sound's span and the gain are the render's too", { skip: !have && "needs ffmpeg" }, async () => {
+ quiet();
+ const render = { transition: 0.4, room: { tail: true, head: true }, loudness: { target: -16 } };
+ const p = await project(render);
+ try {
+ const got = await agree(p, render);
+ assert.ok(got.clips.some((c) => c.sound), "room widened at least one clip");
+ assert.ok(got.clips.every((c) => typeof c.gainDb === "number"), "each clip has its gain");
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("cut points: measured once -- a second read and a moved cut reuse the cached silences", { skip: !have && "needs ffmpeg" }, async () => {
+ quiet();
+ const p = await project({ transition: 0 });
+ try {
+ const t0 = performance.now();
+ const first = await cutPointsFor({ id: "fixture", dir: p.root });
+ const cold = performance.now() - t0;
+ const files = (await readdir(path.join(CACHE, "cut-points"))).filter((f) => f.startsWith("silences-"));
+ assert.ok(files.length >= 1, "the silences are on disk");
+ // The cut moved (an edge edit): no new measurement, the edge follows.
+ const m = JSON.parse(await readFile(p.manifestPath, "utf8"));
+ m.timeline[0].cutEnd = 4.9;
+ await writeFile(p.manifestPath, JSON.stringify(m));
+ const t1 = performance.now();
+ const moved = await cutPointsFor({ id: "fixture", dir: p.root });
+ const warm = performance.now() - t1;
+ assert.deepEqual((await readdir(path.join(CACHE, "cut-points"))).filter((f) => f.startsWith("silences-")).sort(), files.sort());
+ assert.notEqual(moved.clips[0].playTo, first.clips[0].playTo);
+ assert.ok(warm < cold, `warm ${warm.toFixed(0)} ms < cold ${cold.toFixed(0)} ms`);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/frameQueue.mjs b/umtool/lib/report/frameQueue.mjs
@@ -0,0 +1,73 @@
+// THE DECODED FRAMES OF ONE CLIP, waiting to be drawn (the Play view's
+// WebCodecs picture, components/projects/review/playEngine/codecPicture.ts):
+// a small queue in presentation order, bounded, and every frame that leaves
+// it -- drawn past, dropped for room, cleared on a seek -- CLOSED. A
+// VideoFrame holds decoder memory (often on the GPU) until it is closed, and a
+// decoder with too many open frames stalls; so nothing here ever forgets one.
+//
+// `frameAt(t)` is the frame due at time t: the latest at or before it. It
+// stays in the queue (a paused picture, a held last frame are drawn again
+// every tick) and everything older is closed. Pure: any object with a
+// `timestamp` (microseconds, as WebCodecs has it) and `close()`, so it is
+// unit-tested with fakes (frameQueue.test.mjs).
+
+export class FrameQueue {
+ /** @param {{ max?: number }} [opts] */
+ constructor({ max = 12 } = {}) {
+ this.max = max;
+ /** @type {Array<{ timestamp: number, close: () => void }>} */
+ this.frames = [];
+ }
+
+ get size() {
+ return this.frames.length;
+ }
+
+ /** The newest frame's time (µs), or -Infinity: how far ahead the queue reaches. */
+ get head() {
+ return this.frames.length ? this.frames[this.frames.length - 1].timestamp : -Infinity;
+ }
+
+ /** Is there room for another decoded frame? */
+ get room() {
+ return this.frames.length < this.max;
+ }
+
+ /**
+ * A decoded frame, in its place. Over the bound, the OLDEST goes (it is
+ * behind the clock), closed. A frame for a time already held replaces it.
+ */
+ push(frame) {
+ const i = this.frames.findIndex((f) => f.timestamp >= frame.timestamp);
+ if (i < 0) this.frames.push(frame);
+ else if (this.frames[i].timestamp === frame.timestamp) {
+ this.frames[i].close();
+ this.frames[i] = frame;
+ } else this.frames.splice(i, 0, frame);
+ while (this.frames.length > this.max) this.frames.shift()?.close();
+ }
+
+ /** The frame due at t (µs): the latest at or before it, kept; every older one closed. null when none is due yet. */
+ frameAt(t) {
+ let k = -1;
+ for (let i = 0; i < this.frames.length; i += 1) {
+ if (this.frames[i].timestamp <= t) k = i;
+ else break;
+ }
+ if (k < 0) return null;
+ for (let i = 0; i < k; i += 1) this.frames[i].close();
+ this.frames.splice(0, k);
+ return this.frames[0];
+ }
+
+ /** Close and drop every frame before t (µs) -- a decode that ran from a keyframe toward a seek. */
+ dropBefore(t) {
+ while (this.frames.length > 1 && this.frames[1].timestamp <= t) this.frames.shift()?.close();
+ }
+
+ /** Close every frame (a seek, a clip let go). */
+ clear() {
+ for (const f of this.frames) f.close();
+ this.frames = [];
+ }
+}
diff --git a/umtool/lib/report/frameQueue.test.mjs b/umtool/lib/report/frameQueue.test.mjs
@@ -0,0 +1,60 @@
+// The Play view's frame queue (frameQueue.mjs): bounded, in presentation
+// order, the frame due at a time, and every frame closed when it leaves.
+//
+// Run with: node --test lib/report/frameQueue.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { FrameQueue } from "./frameQueue.mjs";
+
+const made = [];
+const frame = (ms) => {
+ const f = { timestamp: ms * 1000, closed: false, close() { if (this.closed) throw new Error(`closed twice: ${ms}`); this.closed = true; } };
+ made.push(f);
+ return f;
+};
+const open = () => made.filter((f) => !f.closed).length;
+
+test("bounded: past `max` the oldest frame goes, closed", () => {
+ made.length = 0;
+ const q = new FrameQueue({ max: 4 });
+ for (let i = 0; i < 10; i += 1) q.push(frame(i * 33));
+ assert.equal(q.size, 4);
+ assert.equal(open(), 4);
+ assert.deepEqual(q.frames.map((f) => f.timestamp / 1000), [198, 231, 264, 297]);
+ assert.equal(q.room, false);
+ q.clear();
+ assert.equal(open(), 0);
+});
+
+test("in presentation order whatever the decode order; a repeat replaces (and closes) the old one", () => {
+ made.length = 0;
+ const q = new FrameQueue({ max: 8 });
+ for (const ms of [0, 100, 33, 66, 133]) q.push(frame(ms));
+ assert.deepEqual(q.frames.map((f) => f.timestamp / 1000), [0, 33, 66, 100, 133]);
+ q.push(frame(66));
+ assert.equal(q.size, 5);
+ assert.equal(open(), 5);
+ q.clear();
+});
+
+test("the frame due: the latest at or before the time, kept; older ones closed; none before the first", () => {
+ made.length = 0;
+ const q = new FrameQueue({ max: 8 });
+ for (const ms of [100, 133, 166, 200]) q.push(frame(ms));
+ assert.equal(q.frameAt(90_000), null);
+ assert.equal(open(), 4);
+ assert.equal(q.frameAt(150_000).timestamp, 133_000);
+ assert.equal(open(), 3);
+ // Paused: the same frame again, nothing closed.
+ assert.equal(q.frameAt(150_000).timestamp, 133_000);
+ assert.equal(open(), 3);
+ // Past the last: the last frame (a held clip's last frame), kept.
+ assert.equal(q.frameAt(10_000_000).timestamp, 200_000);
+ assert.equal(q.size, 1);
+ assert.equal(open(), 1);
+ q.dropBefore(1e12);
+ assert.equal(q.size, 1, "dropBefore keeps the newest it has");
+ q.clear();
+ assert.equal(open(), 0);
+});
diff --git a/umtool/lib/report/mp4Index.mjs b/umtool/lib/report/mp4Index.mjs
@@ -0,0 +1,291 @@
+// AN MP4's VIDEO SAMPLES, from its `moov` (the Play view's WebCodecs picture,
+// components/projects/review/playEngine/codecPicture.ts): where each coded
+// frame is in the file (byte offset, size), when it is presented, whether it
+// is a keyframe, and the decoder's configuration (codec string, the avcC /
+// hvcC / vpcC / av1C record). Enough to feed a VideoDecoder from byte-range
+// reads of the bench's own media route, so a clip's frames are decoded ahead
+// and the one due at the audio clock is drawn -- no <video> element, no seek
+// latency at a join.
+//
+// The files are the cut's cached windows: ffmpeg's (an excerpt, a raw-cache
+// window, an editor-fetched corpus window), progressive mp4 with one video
+// track. A fragmented file (its samples in `moof`s, the `moov` empty) or a
+// codec this does not know returns null, and the caller plays that clip on a
+// <video> instead. Pure: an ArrayBuffer in, plain objects out; no DOM, so it
+// is unit-tested against ffprobe (mp4Index.test.mjs).
+
+const FOURCC = (dv, at) => String.fromCharCode(dv.getUint8(at), dv.getUint8(at + 1), dv.getUint8(at + 2), dv.getUint8(at + 3));
+
+/**
+ * The top-level boxes of a file's first bytes: each one's type, offset and
+ * size (a size of 0 runs to the end). Stops at the first box that does not fit
+ * in `buf` (its header read, its size known): what a caller needs to find
+ * `moov` behind an `mdat`.
+ *
+ * @param {ArrayBuffer} buf
+ * @param {number} [base] the file offset buf starts at
+ * @returns {Array<{ type: string, offset: number, size: number }>}
+ */
+export function topBoxes(buf, base = 0) {
+ const dv = new DataView(buf);
+ const out = [];
+ let at = 0;
+ while (at + 8 <= dv.byteLength) {
+ let size = dv.getUint32(at);
+ const type = FOURCC(dv, at + 4);
+ if (size === 1) {
+ if (at + 16 > dv.byteLength) break;
+ size = Number(dv.getBigUint64(at + 8));
+ }
+ out.push({ type, offset: base + at, size });
+ if (size === 0) break;
+ if (size < 8) break;
+ at += size;
+ }
+ return out;
+}
+
+/** Each child box of [start, end) of a DataView: { type, start (its content), end }. */
+function children(dv, start, end) {
+ const out = [];
+ let at = start;
+ while (at + 8 <= end) {
+ let size = dv.getUint32(at);
+ let head = 8;
+ const type = FOURCC(dv, at + 4);
+ if (size === 1) {
+ size = Number(dv.getBigUint64(at + 8));
+ head = 16;
+ } else if (size === 0) size = end - at;
+ if (size < head || at + size > end) break;
+ out.push({ type, start: at + head, end: at + size, box: at });
+ at += size;
+ }
+ return out;
+}
+
+const find = (dv, start, end, type) => children(dv, start, end).find((c) => c.type === type) ?? null;
+const path = (dv, box, ...types) => {
+ let cur = box;
+ for (const t of types) {
+ cur = cur && find(dv, cur.start, cur.end, t);
+ if (!cur) return null;
+ }
+ return cur;
+};
+
+/** The codec string WebCodecs wants, from a sample entry and its config box. */
+function codecOf(dv, entryType, cfg) {
+ const hex = (n) => n.toString(16).padStart(2, "0");
+ if ((entryType === "avc1" || entryType === "avc3") && cfg?.type === "avcC") {
+ // avc1.PPCCLL: profile, constraint flags, level -- bytes 1..3 of the record.
+ return `${entryType}.${hex(dv.getUint8(cfg.start + 1))}${hex(dv.getUint8(cfg.start + 2))}${hex(dv.getUint8(cfg.start + 3))}`;
+ }
+ if ((entryType === "hvc1" || entryType === "hev1") && cfg?.type === "hvcC") {
+ const b1 = dv.getUint8(cfg.start + 1);
+ const space = ["", "A", "B", "C"][b1 >> 6];
+ const tier = (b1 >> 5) & 1 ? "H" : "L";
+ const profile = b1 & 0x1f;
+ let compat = dv.getUint32(cfg.start + 2);
+ // The compatibility flags, bit-reversed, in hex without leading zeros.
+ let rev = 0;
+ for (let i = 0; i < 32; i += 1) {
+ rev = (rev << 1) | (compat & 1);
+ compat >>>= 1;
+ }
+ const level = dv.getUint8(cfg.start + 12);
+ const cons = [];
+ for (let i = 0; i < 6; i += 1) cons.push(dv.getUint8(cfg.start + 6 + i));
+ while (cons.length && cons[cons.length - 1] === 0) cons.pop();
+ return [`${entryType}`, `${space}${profile}`, (rev >>> 0).toString(16), `${tier}${level}`, ...cons.map((c) => c.toString(16))].join(".");
+ }
+ if (entryType === "vp09" && cfg?.type === "vpcC") {
+ // vpcC v1: version(1) flags(3) profile level bitDepth|chroma...
+ const p = cfg.start + 4;
+ const profile = dv.getUint8(p);
+ const level = dv.getUint8(p + 1);
+ const depth = dv.getUint8(p + 2) >> 4;
+ return `vp09.${String(profile).padStart(2, "0")}.${String(level).padStart(2, "0")}.${String(depth).padStart(2, "0")}`;
+ }
+ if (entryType === "av01" && cfg?.type === "av1C") {
+ const b1 = dv.getUint8(cfg.start + 1);
+ const b2 = dv.getUint8(cfg.start + 2);
+ const profile = b1 >> 5;
+ const level = b1 & 0x1f;
+ const tier = b2 >> 7 ? "H" : "M";
+ const high = (b2 >> 6) & 1;
+ const twelve = (b2 >> 5) & 1;
+ const depth = profile === 2 && high ? (twelve ? 12 : 10) : high ? 10 : 8;
+ return `av01.${profile}.${String(level).padStart(2, "0")}${tier}.${String(depth).padStart(2, "0")}`;
+ }
+ return null;
+}
+
+/**
+ * The video track of a `moov` box.
+ *
+ * @param {ArrayBuffer} moov the bytes of the whole `moov` box (its header included)
+ * @param {{ fileSize?: number }} [opts]
+ * @returns {null | {
+ * codec: string, description: Uint8Array | null, width: number, height: number, timescale: number,
+ * samples: Array<{ offset: number, size: number, pts: number, dts: number, duration: number, key: boolean }>,
+ * duration: number,
+ * }} times in SECONDS on the file's presentation clock (the edit list applied)
+ */
+export function videoTrackOf(moov) {
+ const dv = new DataView(moov);
+ const top = children(dv, 0, dv.byteLength).find((c) => c.type === "moov");
+ if (!top) return null;
+ for (const trak of children(dv, top.start, top.end).filter((c) => c.type === "trak")) {
+ const hdlr = path(dv, trak, "mdia", "hdlr");
+ if (!hdlr || FOURCC(dv, hdlr.start + 8) !== "vide") continue;
+ const mdhd = path(dv, trak, "mdia", "mdhd");
+ if (!mdhd) return null;
+ const v = dv.getUint8(mdhd.start);
+ const timescale = v === 1 ? dv.getUint32(mdhd.start + 20) : dv.getUint32(mdhd.start + 12);
+ const stbl = path(dv, trak, "mdia", "minf", "stbl");
+ if (!stbl || !timescale) return null;
+ const stsd = find(dv, stbl.start, stbl.end, "stsd");
+ if (!stsd) return null;
+ // stsd: version/flags(4) count(4), then the sample entries; a visual one's
+ // fixed part is 78 bytes after its 8-byte header, then its boxes.
+ const entry = children(dv, stsd.start + 8, stsd.end)[0];
+ if (!entry) return null;
+ const width = dv.getUint16(entry.start + 24);
+ const height = dv.getUint16(entry.start + 26);
+ const cfg = children(dv, entry.start + 78, entry.end).find((c) => ["avcC", "hvcC", "vpcC", "av1C"].includes(c.type)) ?? null;
+ const codec = codecOf(dv, entry.type, cfg);
+ if (!codec) return null;
+ const description = cfg && (cfg.type === "avcC" || cfg.type === "hvcC" || cfg.type === "av1C")
+ ? new Uint8Array(moov.slice(cfg.start, cfg.end))
+ : null;
+
+ // The sample tables.
+ const u32s = (box, at, n) => {
+ const out = new Array(n);
+ for (let i = 0; i < n; i += 1) out[i] = dv.getUint32(at + 4 * i);
+ return out;
+ };
+ const stsz = find(dv, stbl.start, stbl.end, "stsz");
+ const stts = find(dv, stbl.start, stbl.end, "stts");
+ const stsc = find(dv, stbl.start, stbl.end, "stsc");
+ const stco = find(dv, stbl.start, stbl.end, "stco");
+ const co64 = find(dv, stbl.start, stbl.end, "co64");
+ const ctts = find(dv, stbl.start, stbl.end, "ctts");
+ const stss = find(dv, stbl.start, stbl.end, "stss");
+ if (!stsz || !stts || !stsc || !(stco || co64)) return null;
+ const fixed = dv.getUint32(stsz.start + 4);
+ const count = dv.getUint32(stsz.start + 8);
+ if (!count) return null; // fragmented: the samples are elsewhere
+ const sizes = fixed ? new Array(count).fill(fixed) : u32s(stsz, stsz.start + 12, count);
+ const chunkOffsets = stco
+ ? u32s(stco, stco.start + 8, dv.getUint32(stco.start + 4))
+ : Array.from({ length: dv.getUint32(co64.start + 4) }, (_, i) => Number(dv.getBigUint64(co64.start + 8 + 8 * i)));
+ // stsc: runs of chunks sharing a samples-per-chunk count.
+ const runs = [];
+ const nRuns = dv.getUint32(stsc.start + 4);
+ for (let i = 0; i < nRuns; i += 1) {
+ const at = stsc.start + 8 + 12 * i;
+ runs.push({ first: dv.getUint32(at) - 1, per: dv.getUint32(at + 4) });
+ }
+ const offsets = new Array(count);
+ let s = 0;
+ for (let r = 0; r < runs.length && s < count; r += 1) {
+ const end = r + 1 < runs.length ? runs[r + 1].first : chunkOffsets.length;
+ for (let ch = runs[r].first; ch < end && s < count; ch += 1) {
+ let at = chunkOffsets[ch];
+ for (let k = 0; k < runs[r].per && s < count; k += 1) {
+ offsets[s] = at;
+ at += sizes[s];
+ s += 1;
+ }
+ }
+ }
+ // Decode times (stts), composition offsets (ctts, signed in version 1).
+ const dts = new Array(count);
+ const durs = new Array(count);
+ {
+ let t = 0;
+ let i = 0;
+ const n = dv.getUint32(stts.start + 4);
+ for (let e = 0; e < n && i < count; e += 1) {
+ const c = dv.getUint32(stts.start + 8 + 8 * e);
+ const d = dv.getUint32(stts.start + 12 + 8 * e);
+ for (let k = 0; k < c && i < count; k += 1) {
+ dts[i] = t;
+ durs[i] = d;
+ t += d;
+ i += 1;
+ }
+ }
+ }
+ const cto = new Array(count).fill(0);
+ if (ctts) {
+ const ver = dv.getUint8(ctts.start);
+ const n = dv.getUint32(ctts.start + 4);
+ let i = 0;
+ for (let e = 0; e < n && i < count; e += 1) {
+ const c = dv.getUint32(ctts.start + 8 + 8 * e);
+ const o = ver === 1 ? dv.getInt32(ctts.start + 12 + 8 * e) : dv.getUint32(ctts.start + 12 + 8 * e);
+ for (let k = 0; k < c && i < count; k += 1) cto[i++] = o;
+ }
+ }
+ const keys = stss ? new Set(u32s(stss, stss.start + 8, dv.getUint32(stss.start + 4)).map((n) => n - 1)) : null;
+ // The edit list: where the presentation starts in the media's time (ffmpeg
+ // shifts by the B-frame delay this way). One edit with a media time is
+ // all a cached window carries; anything else plays from the media's zero.
+ let shift = 0;
+ const elst = path(dv, trak, "edts", "elst");
+ if (elst) {
+ const ver = dv.getUint8(elst.start);
+ const n = dv.getUint32(elst.start + 4);
+ for (let e = 0; e < n; e += 1) {
+ const at = elst.start + 8 + (ver === 1 ? 20 : 12) * e;
+ const mt = ver === 1 ? Number(dv.getBigInt64(at + 8)) : dv.getInt32(at + 4);
+ if (mt >= 0) {
+ shift = mt;
+ break;
+ }
+ }
+ }
+ const samples = new Array(count);
+ for (let i = 0; i < count; i += 1) {
+ samples[i] = {
+ offset: offsets[i],
+ size: sizes[i],
+ dts: (dts[i] - shift) / timescale,
+ pts: (dts[i] + cto[i] - shift) / timescale,
+ duration: durs[i] / timescale,
+ key: keys ? keys.has(i) : true,
+ };
+ }
+ const last = samples.reduce((m, x) => Math.max(m, x.pts + x.duration), 0);
+ return { codec, description, width, height, timescale, samples, duration: last };
+ }
+ return null;
+}
+
+/**
+ * The sample to start decoding from to show presentation time `t`: the last
+ * keyframe whose pts is at or before it (in decode order), and the index of
+ * the frame that shows at t. -1s for an empty track.
+ *
+ * @param {Array<{ pts: number, duration: number, key: boolean }>} samples in decode order
+ * @param {number} t seconds
+ */
+export function seekPoint(samples, t) {
+ let at = -1;
+ let best = -Infinity;
+ for (let i = 0; i < samples.length; i += 1) {
+ const s = samples[i];
+ if (s.pts <= t + 1e-6 && s.pts > best) {
+ best = s.pts;
+ at = i;
+ }
+ }
+ if (at < 0) at = samples.length ? 0 : -1;
+ let key = at;
+ while (key > 0 && !samples[key].key) key -= 1;
+ // B-frames: a keyframe after `at` in decode order may still present before t -- never; start from the key.
+ return { key, frame: at };
+}
diff --git a/umtool/lib/report/mp4Index.test.mjs b/umtool/lib/report/mp4Index.test.mjs
@@ -0,0 +1,79 @@
+// The Play view's mp4 index (mp4Index.mjs) against ffprobe: every video
+// sample's byte offset, size, presentation and decode time and keyframe flag,
+// on an ffmpeg-made file with B-frames (an edit list), moov first and last.
+//
+// Run with: node --test lib/report/mp4Index.test.mjs
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { seekPoint, topBoxes, videoTrackOf } from "./mp4Index.mjs";
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const dir = mkdtempSync(path.join(os.tmpdir(), "mp4index-"));
+test.after(() => rmSync(dir, { recursive: true, force: true }));
+
+function make(name, extra) {
+ const f = path.join(dir, name);
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=320x180:rate=30:duration=4",
+ "-f", "lavfi", "-i", "sine=frequency=440:duration=4",
+ "-c:v", "libx264", "-preset", "ultrafast", "-bf", "2", "-g", "30", "-c:a", "aac", ...extra, f,
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ return f;
+}
+
+function probe(f) {
+ const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_packets", "-show_entries", "packet=pts_time,dts_time,pos,size,flags", "-of", "json", f]);
+ return JSON.parse(String(r.stdout)).packets;
+}
+
+function moovOf(f) {
+ const buf = readFileSync(f);
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ const boxes = topBoxes(ab);
+ const m = boxes.find((b) => b.type === "moov");
+ assert.ok(m, `moov in ${boxes.map((b) => b.type).join(",")}`);
+ return ab.slice(m.offset, m.offset + m.size);
+}
+
+for (const [name, extra] of [["faststart.mp4", ["-movflags", "+faststart"]], ["moov-last.mp4", []]]) {
+ test(`the video samples of ${name} are ffprobe's`, { skip: !have && "needs ffmpeg" }, () => {
+ const f = make(name, extra);
+ const track = videoTrackOf(moovOf(f));
+ assert.ok(track);
+ assert.match(track.codec, /^avc1\.[0-9a-f]{6}$/);
+ assert.ok(track.description && track.description.length > 8);
+ assert.deepEqual([track.width, track.height], [320, 180]);
+ const pk = probe(f);
+ assert.equal(track.samples.length, pk.length);
+ track.samples.forEach((s, i) => {
+ const p = pk[i];
+ assert.equal(s.offset, Number(p.pos), `offset ${i}`);
+ assert.equal(s.size, Number(p.size), `size ${i}`);
+ assert.ok(Math.abs(s.pts - Number(p.pts_time)) < 1e-4, `pts ${i}: ${s.pts} vs ${p.pts_time}`);
+ assert.ok(Math.abs(s.dts - Number(p.dts_time)) < 1e-4, `dts ${i}: ${s.dts} vs ${p.dts_time}`);
+ assert.equal(s.key, p.flags.startsWith("K"), `key ${i}`);
+ });
+ // The first presented frame is at 0; a seek to 1.5 s starts at the keyframe at 1.0 s.
+ assert.equal(Math.min(...track.samples.map((s) => s.pts)), 0);
+ const sp = seekPoint(track.samples, 1.5);
+ assert.ok(track.samples[sp.key].key);
+ assert.ok(Math.abs(track.samples[sp.key].pts - 1) < 1e-6);
+ assert.ok(Math.abs(track.samples[sp.frame].pts - 1.5) < 1 / 30);
+ });
+}
+
+test("a top-level walk stops where the bytes stop, naming the box it could not hold", () => {
+ const ab = new ArrayBuffer(24);
+ const dv = new DataView(ab);
+ dv.setUint32(0, 16);
+ [..."ftyp"].forEach((c, i) => dv.setUint8(4 + i, c.charCodeAt(0)));
+ dv.setUint32(16, 1000);
+ [..."mdat"].forEach((c, i) => dv.setUint8(20 + i, c.charCodeAt(0)));
+ assert.deepEqual(topBoxes(ab), [{ type: "ftyp", offset: 0, size: 16 }, { type: "mdat", offset: 16, size: 1000 }]);
+});
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,118 @@ const fin = (v) => typeof v === "number" && Number.isFinite(v);
const round = (v) => Math.round(v * 1000) / 1000;
/**
+ * @typedef {{ cutStart: number, cutEnd: number, footage?: 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 };
+ }
+ // Its length in the cut: the encode's whole frames when the route said (`footage`), else the span.
+ const foot = fin(c.footage) && /** @type {number} */ (c.footage) > 0 ? /** @type {number} */ (c.footage) : 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 +175,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;
diff --git a/umtool/lib/report/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs
@@ -0,0 +1,172 @@
+// THE PLAY VIEW'S SOUND, as arithmetic (umtool/docs/knobs.md, "Play the cut";
+// the engine is components/projects/review/playEngine/). Every clip's sound is
+// decoded (the bench's /api/report/audio: ffmpeg's decode of the window, so
+// the samples are the ones the build cuts) and scheduled back to back on ONE
+// AudioContext: each clip starts at its segment's first second on the cut's
+// clock and stops at its footage's last, sample-exact, and the whole view's
+// clock -- the rail, the tally, the stamps, the finale, a note's anchor -- is
+// that context's time mapped through the plan. These are the numbers: where
+// each clip's sound sits on the cut's clock, what its level does over it (the
+// crossfade's ramps, room's muted edges, the loudness gain, the clip's own
+// audio knobs, the mute mark), and, from a cut second and a speed, when each
+// node starts, at what offset into its buffer, for how long, with which
+// gain breakpoints. Pure: no Web Audio, so it is unit-tested
+// (playSchedule.test.mjs) and the engine only applies it.
+//
+// CLOCKS: `t` is the cut's (Play's) second; `src` a source second; a name
+// ending in `Wall` is the listener's seconds from the moment playback starts
+// (cut seconds divided by the speed).
+
+import { MUTE_FADE } from "umtool-report-to-video/mute";
+import { ROOM } from "yt-dlp-transcript-common/lib/report/look.mjs";
+
+/** Room's afade at a muted edge (the build's roomAudioFilter): the look's own number. */
+export const ROOM_FADE = ROOM.fade;
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r6 = (v) => Math.round(v * 1e6) / 1e6;
+
+/**
+ * A piecewise-linear level, as [[t, g], ...] sorted by t (cut seconds); flat
+ * before the first and after the last point. The product of several is
+ * sampled at the union of their points -- exact for one ramp at a time,
+ * within a few percent where two ramps overlap.
+ *
+ * @typedef {Array<[number, number]>} Envelope
+ */
+
+/** An envelope's level at t. */
+export function levelAt(env, t) {
+ if (!env.length) return 1;
+ if (t <= env[0][0]) return env[0][1];
+ for (let i = 1; i < env.length; i += 1) {
+ const [t1, g1] = env[i];
+ if (t <= t1) {
+ const [t0, g0] = env[i - 1];
+ return t1 > t0 ? g0 + ((g1 - g0) * (t - t0)) / (t1 - t0) : g1;
+ }
+ }
+ return env[env.length - 1][1];
+}
+
+/** The product of envelopes, sampled at every point of each (clamped to [from, to]). */
+export function multiply(envs, from, to) {
+ const ts = new Set([from, to]);
+ for (const e of envs) for (const [t] of e) if (t > from && t < to) ts.add(t);
+ return [...ts].sort((a, b) => a - b).map((t) => [r6(t), r6(envs.reduce((g, e) => g * levelAt(e, t), 1))]);
+}
+
+/** A rise from 0 at `a` to 1 at `b` (a fade in), or a fall when `down`. */
+const ramp = (a, b, down = false) => (b > a ? [[a, down ? 1 : 0], [b, down ? 0 : 1]] : [[a, down ? 0 : 1]]);
+
+/**
+ * Where each clip's sound sits on the cut's clock and what its level does.
+ *
+ * from / to the cut seconds it sounds over: its segment's start to its
+ * source's end (the encode's last part-frame and a carrying
+ * clip's hold are silent, as the build pads them)
+ * src the source second at `from` (an `audio.offset` reads the
+ * sound that much earlier: later against the picture)
+ * env its level: the crossfades (a linear ramp over each
+ * overlap, acrossfade's `tri`), room's muted head and
+ * tail, the clip's fadeIn / fadeOut, the mute mark
+ * gain a constant multiplier: the loudness gain and the clip's
+ * own `audio.gain`, in dB, as amplitude
+ *
+ * @param {{ items: Array<{ id: string, start: number, end: number, clip: null | {
+ * sourceFrom: number, sourceTo: number, playEnd: number, hold: number,
+ * sound?: [number, number], gainDb?: number, audio?: Record<string, number>, muteFrom?: number } }> }} plan
+ * @returns {Array<{ id: string, index: number, from: number, to: number, src: number, srcTo: number, env: Envelope, gain: number }>}
+ */
+export function audioSpans(plan) {
+ const items = plan?.items ?? [];
+ const out = [];
+ items.forEach((it, i) => {
+ const c = it.clip;
+ if (!c || !(c.playEnd > it.start)) return;
+ const from = it.start;
+ // Its source's length: the encode pads a segment to whole frames with SILENCE (apad), and a hold is silent too.
+ const to = Math.min(c.playEnd, it.start + Math.max(0, c.sourceTo - c.sourceFrom));
+ if (!(to > from)) return;
+ const prev = items[i - 1];
+ const next = items[i + 1];
+ const dIn = prev ? Math.max(0, prev.end - it.start) : 0;
+ const dOut = next ? Math.max(0, it.end - next.start) : 0;
+ const envs = [];
+ // The crossfades: up over the overlap with the clip before, down over the one after (on the segment, hold included).
+ if (dIn > 0) envs.push(ramp(from, from + dIn));
+ if (dOut > 0) envs.push(ramp(it.end - dOut, it.end, true));
+ const at = (src) => from + (src - c.sourceFrom);
+ // Room: heard over [sound[0], sound[1]] only -- a fade in ending at its start, a fade out from its end.
+ if (Array.isArray(c.sound) && fin(c.sound[0]) && fin(c.sound[1])) {
+ const [sa, sb] = c.sound;
+ if (sa > c.sourceFrom + 1e-6) envs.push(ramp(at(sa) - ROOM_FADE, at(sa)));
+ if (sb < c.sourceTo - 1e-6) envs.push(ramp(at(sb), at(sb) + ROOM_FADE, true));
+ }
+ // The clip's own fades, at its segment's edges (clip-audio.mjs).
+ const a = c.audio ?? {};
+ if (fin(a.fadeIn) && a.fadeIn > 0) envs.push(ramp(from, from + Math.min(a.fadeIn, to - from)));
+ if (fin(a.fadeOut) && a.fadeOut > 0) envs.push(ramp(to - Math.min(a.fadeOut, to - from), to, true));
+ // The mute mark: silent from it on, the fade ending AT it.
+ if (fin(c.muteFrom)) envs.push(ramp(at(/** @type {number} */ (c.muteFrom)) - MUTE_FADE, at(/** @type {number} */ (c.muteFrom)), true));
+ const db = (fin(c.gainDb) ? /** @type {number} */ (c.gainDb) : 0) + (fin(a.gain) ? a.gain : 0);
+ const shift = fin(a.offset) ? a.offset / 1000 : 0;
+ out.push({
+ id: it.id, index: i, from, to,
+ src: r6(c.sourceFrom - shift), srcTo: r6(c.sourceFrom - shift + (to - from)),
+ env: multiply(envs, from, to),
+ gain: r6(10 ** (db / 20)),
+ });
+ });
+ return out;
+}
+
+/**
+ * What to start, from cut second `t` at `rate`: for each span not yet over,
+ * its delay from the moment playback starts (`atWall`), the source second
+ * its buffer is read from, how long it plays (`durWall`), and its envelope
+ * on the same wall clock (the first point is the level AT its start, so a
+ * seek into a ramp starts mid-ramp). Hard cuts abut exactly: one span's
+ * `atWall + durWall` is the next one's `atWall`.
+ *
+ * @param {ReturnType<typeof audioSpans>} spans
+ * @param {number} t
+ * @param {number} [rate]
+ * @param {{ until?: number }} [opts] only spans starting before this cut second
+ */
+export function scheduleFrom(spans, t, rate = 1, { until = Infinity } = {}) {
+ const r = rate > 0 ? rate : 1;
+ const out = [];
+ for (const s of spans) {
+ if (s.to <= t + 1e-9 || s.from >= until) continue;
+ const begin = Math.max(t, s.from);
+ const env = multiply([s.env], begin, s.to).map(([x, g]) => [r6((x - t) / r), g]);
+ out.push({
+ id: s.id,
+ index: s.index,
+ atWall: r6((begin - t) / r),
+ durWall: r6((s.to - begin) / r),
+ src: r6(s.src + (begin - s.from)),
+ srcTo: s.srcTo,
+ env,
+ gain: s.gain,
+ });
+ }
+ return out;
+}
+
+/** The cut second at context time `now`, for a playback started at `ctxStart` from cut second `t0`. */
+export const cutTimeAtCtx = (t0, ctxStart, now, rate = 1) => t0 + Math.max(0, now - ctxStart) * (rate > 0 ? rate : 1);
+
+/**
+ * Which span of a clip's source to decode for Play: its whole sound
+ * (offset included) and a little either side, so a seek and a crossfade read
+ * inside one buffer. Bounded: a clip is seconds, never a recording.
+ *
+ * @param {{ src: number, srcTo: number }} span
+ * @param {{ pad?: number, max?: number }} [opts]
+ */
+export function decodeSpanOf(span, { pad = 0.25, max = 120 } = {}) {
+ const from = Math.max(0, span.src - pad);
+ return { from: Math.round(from * 1000) / 1000, to: Math.round(Math.min(span.srcTo + pad, from + max) * 1000) / 1000 };
+}
diff --git a/umtool/lib/report/playSchedule.test.mjs b/umtool/lib/report/playSchedule.test.mjs
@@ -0,0 +1,115 @@
+// The Play view's sound on one clock (playSchedule.mjs): clips abut sample
+// for sample at a hard cut, a crossfade is two linear ramps over the overlap,
+// room's muted edges, the gain, the mute mark, a seek into the middle of a
+// clip (and of a ramp), and a speed.
+//
+// Run with: node --test lib/report/playSchedule.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { estimateSchedule } from "umtool-report-to-video/deck";
+import { playPlan } from "./playCut.mjs";
+import { audioSpans, cutTimeAtCtx, decodeSpanOf, levelAt, multiply, scheduleFrom } from "./playSchedule.mjs";
+
+const manifest = (transition) => ({
+ slug: "t",
+ render: { width: 1920, height: 1080, fps: 30, transition },
+ timeline: [
+ { type: "clip", id: "a", video: "v1", start: 10, end: 14 },
+ { type: "clip", id: "b", video: "v2", start: 100, end: 103 },
+ { type: "card", id: "k", seconds: 2, heading: "card" },
+ { type: "clip", id: "c", video: "v3", start: 50, end: 52.5 },
+ ],
+});
+const planOf = (transition, cuts = null) => {
+ const m = manifest(transition);
+ return playPlan(estimateSchedule(m).segments, m.timeline, { cuts });
+};
+const near = (a, b, what, tol = 1e-6) => assert.ok(Math.abs(a - b) <= tol, `${what}: ${a} vs ${b}`);
+
+test("hard cuts: each clip's sound abuts the next to the sample, at its segment's start; a card is silence", () => {
+ const spans = audioSpans(planOf(0));
+ assert.deepEqual(spans.map((s) => [s.id, s.from, s.to, s.src]), [["a", 0, 4, 10], ["b", 4, 7, 100], ["c", 9, 11.5, 50]]);
+ const sch = scheduleFrom(spans, 0);
+ // a ends exactly where b starts, on the wall clock; at 48 kHz, the same sample.
+ assert.equal(sch[0].atWall + sch[0].durWall, sch[1].atWall);
+ assert.equal(Math.round((sch[0].atWall + sch[0].durWall) * 48000), Math.round(sch[1].atWall * 48000));
+ // The card's two seconds: nothing scheduled over them.
+ assert.equal(sch[2].atWall - (sch[1].atWall + sch[1].durWall), 2);
+ // No ramps: full level throughout.
+ assert.deepEqual(sch[0].env, [[0, 1], [4, 1]]);
+});
+
+test("a crossfade: the outgoing ramps down and the incoming up over the same overlap, summing to one", () => {
+ const spans = audioSpans(planOf(0.5));
+ const [a, b] = spans;
+ // b's segment starts 0.5 s before a's ends.
+ assert.equal(b.from, 3.5);
+ assert.equal(a.to, 4);
+ for (const t of [3.5, 3.6, 3.75, 3.9, 4]) near(levelAt(a.env, t) + levelAt(b.env, t), 1, `sum at ${t}`);
+ near(levelAt(a.env, 3.75), 0.5, "a mid-fade");
+ near(levelAt(b.env, 3.5), 0, "b silent at its start");
+ near(levelAt(b.env, 4), 1, "b full when a is out");
+});
+
+test("a seek mid-clip and mid-ramp: the node starts now, at the source second the cut shows, at the ramp's level", () => {
+ const spans = audioSpans(planOf(0.5));
+ const sch = scheduleFrom(spans, 3.7);
+ const [a, b] = sch;
+ assert.equal(a.atWall, 0);
+ near(a.src, 13.7, "a's offset");
+ near(a.durWall, 0.3, "a's rest");
+ near(a.env[0][1], 0.6, "a starts 0.2 s into its fade down");
+ assert.equal(b.atWall, 0);
+ near(b.src, 100.2, "b's offset");
+ near(b.env[0][1], 0.4, "b starts 0.2 s into its fade up");
+ // Nothing before the seek is scheduled.
+ assert.equal(scheduleFrom(spans, 5).length, 2);
+ assert.equal(scheduleFrom(spans, 5)[0].id, "b");
+});
+
+test("at a speed: wall times divide by the rate, source seconds do not", () => {
+ const spans = audioSpans(planOf(0));
+ const sch = scheduleFrom(spans, 1, 2);
+ near(sch[0].durWall, 1.5, "a's 3 s at 2x");
+ near(sch[0].src, 11, "a from source 11");
+ near(sch[1].atWall, 1.5, "b at 1.5 s of wall");
+ near(sch[1].durWall, 1.5, "b's 3 s at 2x");
+ assert.equal(sch[0].atWall + sch[0].durWall, sch[1].atWall);
+ near(cutTimeAtCtx(1, 10, 11.5, 2), 4, "the clock at 2x");
+});
+
+test("the render's edges, room, loudness, the clip's knobs and the mute mark shape the level", () => {
+ const cuts = {
+ a: { cutStart: 9.6, cutEnd: 14.4, gainDb: -6, sound: [10, 14] },
+ b: { cutStart: 100, cutEnd: 103, audio: { gain: 6, fadeIn: 0.5, offset: 200 }, muteFrom: 102 },
+ };
+ const spans = audioSpans(planOf(0, cuts));
+ const [a, b] = spans;
+ assert.deepEqual([a.from, a.to, a.src], [0, 4.8, 9.6]);
+ near(a.gain, 10 ** (-6 / 20), "a's gain");
+ // Room: silent before source 10 (cut 0.4), its fade in ending there; silent after 14 + fade.
+ near(levelAt(a.env, 0.2), 0, "a's muted head");
+ near(levelAt(a.env, 0.4), 1, "a heard from its sound's start");
+ near(levelAt(a.env, 4.4), 1, "a heard to its sound's end");
+ near(levelAt(a.env, 4.7), 0, "a's muted tail");
+ // b: +6 dB, fading in over 0.5 s, read 0.2 s earlier (its sound later), silent from source 102.
+ near(b.gain, 10 ** (6 / 20), "b's gain");
+ near(b.src, 99.8, "b read 0.2 s earlier");
+ near(levelAt(b.env, b.from), 0, "b fades in");
+ near(levelAt(b.env, b.from + 0.5), 1, "b in");
+ near(levelAt(b.env, b.from + 2), 0, "b silent from its mute mark");
+ near(levelAt(b.env, b.from + 2 - 0.04), 1, "b full until the mute fade");
+});
+
+test("a segment longer than its source (whole frames) is silent past the source's end", () => {
+ const spans = audioSpans(planOf(0, { a: { cutStart: 10, cutEnd: 13.99, footage: 4 } }));
+ assert.equal(spans[0].to, 3.99);
+ assert.equal(spans[1].from, 4);
+});
+
+test("envelopes multiply on the union of their points; a decode span is the sound and a pad", () => {
+ assert.deepEqual(multiply([[[0, 0], [1, 1]], [[0.5, 1], [1.5, 0]]], 0, 2), [[0, 0], [0.5, 0.5], [1, 0.5], [1.5, 0], [2, 0]]);
+ assert.deepEqual(decodeSpanOf({ src: 10, srcTo: 14 }), { from: 9.75, to: 14.25 });
+ assert.deepEqual(decodeSpanOf({ src: 0.1, srcTo: 400 }, { max: 120 }), { from: 0, to: 120 });
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -187,10 +187,17 @@ import {
} from "./look.mjs";
// Room at a clip's edges (release 36 lane E, render.room): the rule is pure,
// in room.mjs; the build finds the words or silences and cuts the segment.
+import { clipRoom, roomAudioFilter } from "./room.mjs";
+// Where a clip is cut (cut-points.mjs, snap.mjs): the silences, the snap, the
+// room and the loudness measure -- one implementation, which umtool's
+// cut-points route (the Play view, the bench's ghost edges) calls too.
import {
- ROOM, clipRoom, roomAudioFilter, roomPlan, speechStartFromSilences, speechStartFromWords, tailFromSilences,
- tailFromWords,
-} from "./room.mjs";
+ detectRoomSilences as detectRoomSilencesWith, detectSilence as detectSilenceWith, lookWords, measureLoudnessWith,
+ readLookSources, roomOfCut, snapCut,
+} from "./cut-points.mjs";
+// The snap itself (a montage's window snaps with it too), re-exported for the tests.
+import { snap } from "./snap.mjs";
+export { snap };
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
import { pruneChromeFrames } from "./prune-frames.mjs";
@@ -974,43 +981,38 @@ async function startOffset(file) {
/** fetchClip, with the window's clock aligned (startOffset): what every segment and tile cuts from. */
async function fetchClipAligned(entry, meta, render, local, opts) {
- const r = await fetchClip(entry, meta, render, local, opts);
- const off = await startOffset(r.path);
- if (!off) return r;
- EMIT("note", { message: `${entry.id}: ${path.basename(r.path)} starts ${off.toFixed(2)}s in — cut on its own clock` });
- return {
- ...r,
- fetchStart: r.fetchStart + off,
- ...(r.scan ? { scan: { from: Math.max(0, r.scan.from - off), to: r.scan.to - off } } : {}),
- startOffset: off,
- };
+ const r = await alignedClipSource(await fetchClip(entry, meta, render, local, opts));
+ if (r.startOffset) EMIT("note", { message: `${entry.id}: ${path.basename(r.path)} starts ${r.startOffset.toFixed(2)}s in — cut on its own clock` });
+ return r;
}
-async function fetchClip(entry, meta, render, local, opts) {
- const { rawDir } = local;
+/**
+ * A clip's source ON DISK, as the build cuts from it -- the file, the source
+ * second it starts at (`fetchStart`), the span silence detection measures
+ * (`scan`, none for a raw-cache window: measured whole) -- or null when only
+ * the network has it. `log` is the build's `fetch` event for it. The build's
+ * fetchClip asks this first; umtool's cut-points route asks only this (it
+ * never fetches), so both snap on the same file over the same span.
+ */
+export async function onDiskClipSource(entry, meta, render, local, opts = {}) {
const { from, to } = fetchSpan(entry, render, opts);
// A `src` clip IS its source: the whole file, [0, duration], beside the
// manifest. Nothing is looked up and nothing is fetched.
if (hasLocalMedia(entry)) {
- const file = LOCAL.file(entry);
+ const file = (opts.localMedia ?? LOCAL).file(entry);
const duration = entry.srcDuration ?? (await probeMedia(file)).duration;
- EMIT("fetch", {
- id: entry.id, video: clipLabel(entry), from, to: Number.isFinite(duration) ? Math.min(to, duration) : to,
- cached: true, source: "src",
- reuse: path.basename(file), local: file, window: [0, duration],
- });
return {
path: file, fetchStart: 0, cached: true, source: "src",
scan: { from: Math.max(0, from), to: Number.isFinite(duration) ? Math.min(to, duration) : to },
+ log: {
+ id: entry.id, video: clipLabel(entry), from, to: Number.isFinite(duration) ? Math.min(to, duration) : to,
+ cached: true, source: "src",
+ reuse: path.basename(file), local: file, window: [0, duration],
+ },
};
}
- // Shared across variants, and deliberately so: this is the only expensive
- // thing in a build, and the two cuts overlap almost entirely.
- const name = rawWindowName(entry.video, from, to);
- const dest = path.join(rawDir, name);
-
// ON DISK FIRST. The raw cache, then the editor's corpus windows, then a
// saved whole source (sources.mjs). `--no-reuse` takes only the raw file
// named for exactly this span. fetchStart is the SOURCE's start, not the
@@ -1019,28 +1021,60 @@ async function fetchClip(entry, meta, render, local, opts) {
// The audio tier only by audioUse's rule: before the network for a clip
// with no picture to fetch; for one that should have a picture, only when
// there is no network to ask AND --audio-fallback said so.
+ const name = rawWindowName(entry.video, from, to);
const use = audioUse({ entry, meta, render, network: networkOn(opts), fallback: !!opts.audioFallback });
const hit = await local.resolve(entry, { from, to }, { exact: !!opts.noReuse, audio: use !== null });
+ if (!hit) return null;
// What the log calls it: a fallback is not the same fact as an audio-only clip.
- const kind = hit?.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit?.kind;
- if (hit) {
- EMIT("fetch", {
+ const kind = hit.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit.kind;
+ return {
+ path: hit.path,
+ fetchStart: hit.windowStart,
+ cached: true,
+ source: kind,
+ // A whole container is hours long and silence detection decodes what it
+ // is given: give it the span a fetch would have produced, no more.
+ ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }),
+ log: {
id: entry.id, video: entry.video, from, to, cached: true, source: kind,
...(hit.kind !== "raw-cache" || hit.name !== name ? { reuse: hit.name } : {}),
local: hit.path,
window: [hit.windowStart, hit.windowEnd],
...(hit.height ? { height: hit.height } : {}),
- });
- return {
- path: hit.path,
- fetchStart: hit.windowStart,
- cached: true,
- source: kind,
- // A whole container is hours long and silence detection decodes what it
- // is given: give it the span a fetch would have produced, no more.
- ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }),
- };
+ },
+ };
+}
+
+/**
+ * A source's clock aligned (startOffset): a file whose picture starts late
+ * moves its `fetchStart` (and its `scan`) by the container's start_time.
+ * What fetchClipAligned does after a fetch; the cut-points route's too.
+ */
+export async function alignedClipSource(r) {
+ const off = await startOffset(r.path);
+ if (!off) return r;
+ return {
+ ...r,
+ fetchStart: r.fetchStart + off,
+ ...(r.scan ? { scan: { from: Math.max(0, r.scan.from - off), to: r.scan.to - off } } : {}),
+ startOffset: off,
+ };
+}
+
+async function fetchClip(entry, meta, render, local, opts) {
+ const { rawDir } = local;
+ const { from, to } = fetchSpan(entry, render, opts);
+ const disk = await onDiskClipSource(entry, meta, render, local, opts);
+ if (disk) {
+ const { log, ...r } = disk;
+ EMIT("fetch", log);
+ return r;
}
+
+ // Shared across variants, and deliberately so: this is the only expensive
+ // thing in a build, and the two cuts overlap almost entirely.
+ const name = rawWindowName(entry.video, from, to);
+ const dest = path.join(rawDir, name);
if (opts.noNetwork) throw new Error(`--no-network set and no local source covers ${name}`);
if (opts.skipFetch) throw new Error(`--skip-fetch set and no cached window covers ${name}`);
@@ -1096,84 +1130,10 @@ async function fetchClip(entry, meta, render, local, opts) {
return { path: dest, fetchStart: from, cached: false, source: "network" };
}
-// Parse ffmpeg's silencedetect output into [{s, e}] intervals, in seconds
-// relative to the start of the given file.
-async function detectSilence(file, render, scan = null) {
- const minDur = render.silenceMinDur ?? 0.09;
- // A source wider than the fetch would have been (a corpus window, a whole
- // saved container) is measured over just that span: seeked, audio only, and
- // the silences shifted back onto the file's clock. A raw-cache window is
- // measured whole, as it always was, so no cached cut moves.
- const input = scan
- ? ["-ss", scan.from.toFixed(3), "-to", scan.to.toFixed(3), "-i", file, "-vn"]
- : ["-i", file];
- const shift = scan ? scan.from : 0;
-
- // The threshold has to be RELATIVE to the clip, not absolute. These are game
- // streams: the gaps between words are full of game audio and music, so they
- // are quiet but nowhere near silent. A fixed -32 dB sits below the noise floor
- // of a typical clip here and finds literally zero silences (measured: mean
- // volume -21 dB, 0 hits at -32 dB, 25 hits at -26 dB). Measure the clip first
- // and cut a few dB under its own mean instead.
- const { stderr: volLog } = await execFileP(
- FFMPEG,
- ["-nostdin", ...input, "-af", "volumedetect", "-f", "null", "-"],
- { maxBuffer: 1 << 26 },
- ).catch((e) => ({ stderr: e.stderr ?? "" }));
- const meanMatch = (volLog ?? "").match(/mean_volume:\s*(-?[\d.]+) dB/);
- const mean = meanMatch ? Number(meanMatch[1]) : -24;
- const noise = Math.max(-45, Math.min(-18, mean - (render.silenceRelDb ?? 6)));
-
- // ffmpeg exits 0 here, so stderr comes back on the resolved result.
- const { stderr } = await execFileP(
- FFMPEG,
- ["-nostdin", ...input, "-af", `silencedetect=noise=${noise.toFixed(1)}dB:d=${minDur}`, "-f", "null", "-"],
- { maxBuffer: 1 << 26 },
- ).catch((e) => ({ stderr: e.stderr ?? "" }));
- const log = stderr ?? "";
-
- const out = [];
- let open = null;
- for (const line of log.split("\n")) {
- const s = line.match(/silence_start:\s*(-?[\d.]+)/);
- if (s) open = Number(s[1]) + shift;
- const e = line.match(/silence_end:\s*(-?[\d.]+)/);
- if (e && open !== null) {
- out.push({ s: open, e: Number(e[1]) + shift });
- open = null;
- }
- }
- return out;
-}
-
-// Snap a desired cut to the nearest silence, so the clip begins and ends between
-// words instead of through one. Returns the desired point unchanged when no
-// silence is close enough — better a tight cut than a cut in the wrong place.
-//
-// How much of the pause is kept: 0.10 s before speech resumes, 0.18 s after it
-// stops, unless the render says `snapLead` / `snapTail` -- and then never more
-// than the pause holds, so a long one keeps its breath (room for the
-// crossfade to fade over silence, not the last word) without reaching the
-// next word. Exported for the tests.
-export function snap(desired, intervals, kind, window, render = {}) {
- let best = null;
- for (const iv of intervals) {
- // Starting: we want to resume just before speech does -> the silence's END.
- // Ending: we want to stop just after speech does -> the silence's START.
- const point = kind === "start" ? iv.e : iv.s;
- const d = Math.abs(point - desired);
- if (d > window) continue;
- if (!best || d < best.d) best = { d, point, iv };
- }
- if (!best) return { at: desired, snapped: false };
- const set = kind === "start" ? render.snapLead : render.snapTail;
- let lead = kind === "start" ? -0.10 : 0.18;
- if (Number.isFinite(set) && set >= 0) {
- const room = best.iv.e - best.iv.s;
- lead = (kind === "start" ? -1 : 1) * Math.min(set, room);
- }
- return { at: Math.max(0, best.point + lead), snapped: true };
-}
+// The silences of a file, in its own seconds (cut-points.mjs detectSilence,
+// with this build's ffmpeg). The snap that reads them is snap.mjs's `snap`,
+// re-exported above for the tests.
+const detectSilence = (file, render, scan = null) => detectSilenceWith(file, render, scan, { ffmpeg: FFMPEG });
// Encoder quality is manifest-driven so a cut can trade size for fidelity without
// editing this file. Defaults reproduce the original hardcoded settings exactly.
@@ -1265,11 +1225,12 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes,
entry, mont, raw, fetchStart, M: dirs.montage, render, provenance, sil, wantA, wantB, win,
}));
}
- const a = mont ? mont.win.start : snap(wantA, sil, "start", win, render);
- const b = mont ? mont.win.end : snap(wantB, sil, "end", win, render);
- // Never let snapping invert or collapse the window.
- const cutA = mont ? mont.win.cutA : Math.min(a.at, wantB - 1);
- const cutB = mont ? mont.win.cutB : Math.max(b.at, cutA + 1);
+ // Snapped, and never inverted or collapsed (snap.mjs snapCut: the cut-points route's own).
+ const snapped = mont ? null : snapCut({ sil, wantA, wantB, render });
+ const a = mont ? mont.win.start : snapped.a;
+ const b = mont ? mont.win.end : snapped.b;
+ const cutA = mont ? mont.win.cutA : snapped.cutA;
+ const cutB = mont ? mont.win.cutB : snapped.cutB;
EMIT("snap", { id: entry.id, start: a.snapped, end: b.snapped, seconds: cutB - cutA });
// Room at the edges (render.room, room.mjs): the picture widened past the
// snapped cut -- to the first silence and a join's length beyond, muted --
@@ -1619,69 +1580,12 @@ async function probeDims(file) {
}
/**
- * What the captions read beside the manifest: reactions.json (the clip
- * finder's turns and roles, when it is version 1) and the words file it names
- * (`source.words`, else words.json), read once.
- */
-async function readLookSources(manifestDir) {
- let reactions = null;
- try {
- const doc = JSON.parse(await readFile(path.join(manifestDir, "reactions.json"), "utf8"));
- if (doc?.version === 1 && Array.isArray(doc.turns)) reactions = doc;
- } catch {
- reactions = null;
- }
- return { manifestDir, reactions, words: null, transcripts: new Map() };
-}
-
-/** Does reactions.json describe this clip's recording? */
-function lookMatches(entry, provenance, rx) {
- if (!rx?.source?.video || hasLocalMedia(entry) || entry.video !== rx.source.video) return false;
- const ch = entry.channel ?? provenance?.channelSlug ?? null;
- return !rx.source.channel || !ch || ch === rx.source.channel;
-}
-
-const wordOf = (w) => ({ text: String(w?.w ?? w?.word ?? w?.text ?? ""), start: Number(w?.start), end: Number(w?.end) });
-
-/**
- * A clip's words, turns and speakers in [from, to] (source seconds): the
- * project's words file for the recording reactions.json describes, else the
- * corpus's whisper words (transcript.json), else its cues spread by
- * character. Turns and speakers only from reactions.json.
+ * A clip's words, turns and speakers in [from, to] (source seconds):
+ * cut-points.mjs lookWords over this build's corpus and cue source (the
+ * captions and the room read the same words).
*/
-async function lookWordsFor(entry, provenance, look, from, to) {
- const inSpan = (w) => Number.isFinite(w.start) && Number.isFinite(w.end) && (w.start + w.end) / 2 >= from - 0.05 && (w.start + w.end) / 2 <= to + 0.05;
- const rx = lookMatches(entry, provenance, look.reactions) ? look.reactions : null;
- const turns = rx ? rx.turns.filter((t) => t.end > from && t.start < to) : [];
- const speakers = rx?.speakers ?? [];
- if (rx) {
- look.words ??= readFile(path.join(look.manifestDir, typeof rx.source.words === "string" ? rx.source.words : "words.json"), "utf8")
- .then((t) => {
- const doc = JSON.parse(t);
- return (Array.isArray(doc) ? doc : doc?.words ?? []).map(wordOf);
- })
- .catch(() => null);
- const ws = await look.words;
- if (ws?.length) {
- const got = ws.filter(inSpan);
- if (got.length) return { words: got, turns, speakers, wordsFrom: "words.json" };
- }
- }
- if (!hasLocalMedia(entry) && FX_CHANNELS_DIR && entry.video) {
- const slug = entry.channel ?? provenance?.channelSlug;
- const key = `${slug}/${entry.video}`;
- if (!look.transcripts.has(key)) {
- look.transcripts.set(key, resolveVideoDir(FX_CHANNELS_DIR, slug, entry.video)
- .then((dir) => readFile(path.join(dir, "transcript.json"), "utf8"))
- .then((t) => whisperWords(JSON.parse(t)))
- .catch(() => null));
- }
- const ws = await look.transcripts.get(key);
- const got = (ws ?? []).map(wordOf).filter(inSpan);
- if (got.length) return { words: got, turns, speakers, wordsFrom: "transcript.json" };
- }
- const cues = fxWordsOf(await montageCues(entry, provenance), from - 0.05, to + 0.05).map(wordOf);
- return { words: cues, turns, speakers, wordsFrom: "cues" };
+function lookWordsFor(entry, provenance, look, from, to) {
+ return lookWords(entry, provenance, look, from, to, { channelsDir: FX_CHANNELS_DIR, cues: (e) => montageCues(e, provenance) });
}
/**
@@ -1714,80 +1618,20 @@ async function segmentCaptions({ entry, provenance, look, render, outDir, from,
// edges, and the plan its segment is cut by.
/**
- * silencedetect at a fixed floor (ROOM.detectDb, ROOM.detectD) over [from, to]
- * of a file (its own seconds), for a clip with no words. A silence still open
- * when the span ends runs to its end.
- */
-async function detectRoomSilences(file, from, to) {
- const a = Math.max(0, from);
- const { stderr } = await execFileP(
- FFMPEG,
- ["-nostdin", "-ss", a.toFixed(3), "-to", to.toFixed(3), "-i", file, "-vn", "-af", `silencedetect=noise=${ROOM.detectDb}dB:d=${ROOM.detectD}`, "-f", "null", "-"],
- { maxBuffer: 1 << 26 },
- ).catch((e) => ({ stderr: e.stderr ?? "" }));
- const out = [];
- let open = null;
- for (const line of String(stderr ?? "").split("\n")) {
- const s = line.match(/silence_start:\s*(-?[\d.]+)/);
- if (s) open = Number(s[1]) + a;
- const e = line.match(/silence_end:\s*(-?[\d.]+)/);
- if (e && open !== null) {
- out.push({ s: open, e: Number(e[1]) + a });
- open = null;
- }
- }
- if (open !== null) out.push({ s: open, e: to });
- return out;
-}
-
-/**
- * One clip's room (room.mjs's rule): where its sound stops and whether its
- * head is muted, from its words -- the project's words.json, the corpus
- * transcript, the cues (lookWordsFor) -- else silencedetect; the plan, in
- * the file's seconds; and what its cut record says. Null when the clip has
- * no room (or nothing moves). `first`: nothing comes before it, so no head.
+ * One clip's room (cut-points.mjs roomOfCut, room.mjs's rule): its words
+ * (lookWordsFor) else its silences, the plan its segment is cut by, and what
+ * its cut record says; its notes said here. Null when the clip has no room.
*/
async function segmentRoom({ entry, raw, render, provenance, look, D, first, fetchStart, cutA, cutB }) {
- const room = clipRoom(entry, render);
- if (!room) return null;
- const head = room.head && !first;
- if (!room.tail && !head) return null;
+ if (!clipRoom(entry, render)) return null;
const media = await probeMedia(raw);
- const got = look
- ? await lookWordsFor(entry, provenance, look, fetchStart + cutA - 1, fetchStart + cutB + room.maxS + 1).catch(() => null)
- : null;
- const words = (got?.words ?? []).map((w) => ({ start: w.start - fetchStart, end: w.end - fetchStart }));
- let via = words.length ? got.wordsFrom : "silence";
- let tail = room.tail && words.length ? tailFromWords(words, cutB, room) : null;
- let speech = head && words.length ? speechStartFromWords(words, cutA) : null;
- // Cues abut: a run of them that reaches the cap says nothing about where
- // anybody stops, so the sound decides that edge instead.
- const detectTail = room.tail && (!words.length || (via === "cues" && tail?.capped));
- if (detectTail || (head && !words.length)) {
- const end = Math.min(media.duration ?? Infinity, cutB + room.maxS + 0.5);
- const sil = await detectRoomSilences(raw, Math.min(cutA, cutB) - 0.5, end);
- if (detectTail) {
- tail = tailFromSilences(sil, cutB, room);
- via = words.length ? `${via}+silence` : "silence";
- if (!tail.found) EMIT("note", { message: `${entry.id}: no silence within ${room.maxS} s of its end — its sound stops at the cut` });
- }
- if (head && !words.length) speech = speechStartFromSilences(sil, cutA);
- }
- const plan = roomPlan({ cutA, cutB, D, soundEnd: tail ? tail.at : null, speechStart: head ? speech : null, duration: media.duration });
- if (plan.picA === cutA && plan.picB === cutB) return null;
- if (tail?.capped) EMIT("note", { message: `${entry.id}: still talking ${room.maxS} s past its end — its sound fades there (render.room.maxS)` });
- for (const edge of plan.clamped) {
- EMIT("note", { message: `${entry.id}: its ${edge === "tail" ? "tail" : "head"} room is clamped to ${path.basename(raw)}'s ${edge === "tail" ? "end" : "start"} (a fetched window; widen the extent or fetch it whole)` });
- }
- const s3 = (t) => Number((fetchStart + t).toFixed(3));
- return {
- plan,
- record: {
- sound: [s3(plan.soundA), s3(plan.soundB)], head: plan.head, tail: plan.tail, via,
- ...(tail?.capped ? { capped: true } : {}),
- ...(plan.clamped.length ? { clamped: plan.clamped } : {}),
- },
- };
+ const room = await roomOfCut({
+ entry, render, D, first, fetchStart, cutA, cutB, duration: media.duration, file: raw,
+ words: (from, to) => (look ? lookWordsFor(entry, provenance, look, from, to) : Promise.resolve(null)),
+ silences: (from, to) => detectRoomSilencesWith(raw, from, to, { ffmpeg: FFMPEG }),
+ });
+ for (const message of room?.notes ?? []) EMIT("note", { message });
+ return room;
}
/**
@@ -2001,11 +1845,7 @@ async function montageCheckSound({ entry, mont, raw, fetchStart, M, render, prov
* null when it cannot be measured.
*/
export async function measureLoudness(raw, from, to) {
- const { stderr } = await execFileP(FFMPEG, [
- "-nostdin", "-hide_banner", "-ss", Math.max(0, from).toFixed(3), "-to", to.toFixed(3), "-i", raw,
- "-vn", "-af", "ebur128", "-f", "null", "-",
- ], { maxBuffer: 1 << 26 }).catch((e) => ({ stderr: e.stderr ?? "" }));
- return parseIntegratedLoudness(stderr);
+ return measureLoudnessWith(raw, from, to, parseIntegratedLoudness, { ffmpeg: FFMPEG });
}
/** The gain that brings a stretch of a source to the montage's loudness target: `{ measured, gain, target }`. */
diff --git a/umtool/report-to-video/cut-points.mjs b/umtool/report-to-video/cut-points.mjs
@@ -0,0 +1,246 @@
+// WHERE THE RENDER CUTS A CLIP, measured: the build's snap path as one module
+// the build (build-video.mjs buildClipSegment) and umtool's cut-points route
+// (lib/report/cutPoints.mjs, the Play view and the clip bench's ghost
+// markers) both call -- so what Play plays at a join is where the render cuts
+// it, from the render's code, never a second reading of it.
+//
+// detectSilence the silences of the file a clip is cut from (silencedetect
+// a few dB under the clip's own mean, `render.silenceMinDur`,
+// `render.silenceRelDb`) -- the input of snap.mjs's arithmetic
+// room* room at the edges (render.room, room.mjs): the words around
+// a clip's edges, else the silences, and the plan its sound
+// and picture are cut by
+// measureLoudness the cut's integrated loudness (render.loudness's gain)
+//
+// No imports from build-video.mjs: it imports this file.
+import { execFile } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { fxWordsOf } from "./fx.mjs";
+import { hasLocalMedia } from "./local-media.mjs";
+import { whisperWords } from "./montage.mjs";
+import {
+ ROOM, clipRoom, roomPlan, speechStartFromSilences, speechStartFromWords, tailFromSilences, tailFromWords,
+} from "./room.mjs";
+
+export { snap, snapCut, renderCut, recordSecond, snapKnobs, SNAP_DEFAULTS } from "./snap.mjs";
+
+const execFileP = promisify(execFile);
+const FFMPEG_DEFAULT = process.env.FFMPEG_BIN ?? "ffmpeg";
+
+/** silencedetect's lines as [{s, e}], shifted by `shift`; a silence still open at the end runs to `openTo` when given. */
+function parseSilences(log, shift, openTo = null) {
+ const out = [];
+ let open = null;
+ for (const line of String(log ?? "").split("\n")) {
+ const s = line.match(/silence_start:\s*(-?[\d.]+)/);
+ if (s) open = Number(s[1]) + shift;
+ const e = line.match(/silence_end:\s*(-?[\d.]+)/);
+ if (e && open !== null) {
+ out.push({ s: open, e: Number(e[1]) + shift });
+ open = null;
+ }
+ }
+ if (open !== null && openTo !== null) out.push({ s: open, e: openTo });
+ return out;
+}
+
+/**
+ * The silences of a file as [{s, e}], in seconds relative to its start.
+ *
+ * @param {string} file
+ * @param {{ silenceMinDur?: number, silenceRelDb?: number }} render
+ * @param {{ from: number, to: number } | null} [scan] measure only this span
+ * @param {{ ffmpeg?: string }} [opts]
+ */
+export async function detectSilence(file, render, scan = null, { ffmpeg = FFMPEG_DEFAULT } = {}) {
+ const minDur = render.silenceMinDur ?? 0.09;
+ // A source wider than the fetch would have been (a corpus window, a whole
+ // saved container) is measured over just that span: seeked, audio only, and
+ // the silences shifted back onto the file's clock. A raw-cache window is
+ // measured whole, as it always was, so no cached cut moves.
+ const input = scan
+ ? ["-ss", scan.from.toFixed(3), "-to", scan.to.toFixed(3), "-i", file, "-vn"]
+ : ["-i", file];
+ const shift = scan ? scan.from : 0;
+
+ // The threshold has to be RELATIVE to the clip, not absolute. These are game
+ // streams: the gaps between words are full of game audio and music, so they
+ // are quiet but nowhere near silent. A fixed -32 dB sits below the noise floor
+ // of a typical clip here and finds literally zero silences (measured: mean
+ // volume -21 dB, 0 hits at -32 dB, 25 hits at -26 dB). Measure the clip first
+ // and cut a few dB under its own mean instead.
+ const { stderr: volLog } = await execFileP(
+ ffmpeg,
+ ["-nostdin", ...input, "-af", "volumedetect", "-f", "null", "-"],
+ { maxBuffer: 1 << 26 },
+ ).catch((e) => ({ stderr: e.stderr ?? "" }));
+ const meanMatch = (volLog ?? "").match(/mean_volume:\s*(-?[\d.]+) dB/);
+ const mean = meanMatch ? Number(meanMatch[1]) : -24;
+ const noise = Math.max(-45, Math.min(-18, mean - (render.silenceRelDb ?? 6)));
+
+ // ffmpeg exits 0 here, so stderr comes back on the resolved result.
+ const { stderr } = await execFileP(
+ ffmpeg,
+ ["-nostdin", ...input, "-af", `silencedetect=noise=${noise.toFixed(1)}dB:d=${minDur}`, "-f", "null", "-"],
+ { maxBuffer: 1 << 26 },
+ ).catch((e) => ({ stderr: e.stderr ?? "" }));
+ return parseSilences(stderr ?? "", shift);
+}
+
+/**
+ * A stretch of a source's integrated loudness (LUFS, ffmpeg's ebur128), or
+ * null when it cannot be measured.
+ *
+ * @param {(log: string) => number | null} parse montage.mjs parseIntegratedLoudness
+ */
+export async function measureLoudnessWith(raw, from, to, parse, { ffmpeg = FFMPEG_DEFAULT } = {}) {
+ const { stderr } = await execFileP(ffmpeg, [
+ "-nostdin", "-hide_banner", "-ss", Math.max(0, from).toFixed(3), "-to", to.toFixed(3), "-i", raw,
+ "-vn", "-af", "ebur128", "-f", "null", "-",
+ ], { maxBuffer: 1 << 26 }).catch((e) => ({ stderr: e.stderr ?? "" }));
+ return parse(stderr);
+}
+
+// ---- room at the edges (render.room; release 36 lane E) --------------------
+
+/**
+ * silencedetect at a fixed floor (ROOM.detectDb, ROOM.detectD) over [from, to]
+ * of a file (its own seconds), for a clip with no words. A silence still open
+ * when the span ends runs to its end.
+ */
+export async function detectRoomSilences(file, from, to, { ffmpeg = FFMPEG_DEFAULT } = {}) {
+ const a = Math.max(0, from);
+ const { stderr } = await execFileP(
+ ffmpeg,
+ ["-nostdin", "-ss", a.toFixed(3), "-to", to.toFixed(3), "-i", file, "-vn", "-af", `silencedetect=noise=${ROOM.detectDb}dB:d=${ROOM.detectD}`, "-f", "null", "-"],
+ { maxBuffer: 1 << 26 },
+ ).catch((e) => ({ stderr: e.stderr ?? "" }));
+ return parseSilences(stderr ?? "", a, to);
+}
+
+/**
+ * What the captions and the room read beside the manifest: reactions.json
+ * (the clip finder's turns and roles, when it is version 1) and the words file
+ * it names (`source.words`, else words.json), read once.
+ */
+export async function readLookSources(manifestDir) {
+ let reactions = null;
+ try {
+ const doc = JSON.parse(await readFile(path.join(manifestDir, "reactions.json"), "utf8"));
+ if (doc?.version === 1 && Array.isArray(doc.turns)) reactions = doc;
+ } catch {
+ reactions = null;
+ }
+ return { manifestDir, reactions, words: null, transcripts: new Map() };
+}
+
+/** Does reactions.json describe this clip's recording? */
+function lookMatches(entry, provenance, rx) {
+ if (!rx?.source?.video || hasLocalMedia(entry) || entry.video !== rx.source.video) return false;
+ const ch = entry.channel ?? provenance?.channelSlug ?? null;
+ return !rx.source.channel || !ch || ch === rx.source.channel;
+}
+
+const wordOf = (w) => ({ text: String(w?.w ?? w?.word ?? w?.text ?? ""), start: Number(w?.start), end: Number(w?.end) });
+
+/**
+ * A clip's words, turns and speakers in [from, to] (source seconds): the
+ * project's words file for the recording reactions.json describes, else the
+ * corpus's whisper words (transcript.json), else its cues spread by
+ * character. Turns and speakers only from reactions.json.
+ *
+ * @param {{ channelsDir: string | null, cues: (entry: any) => Promise<Array<{ start: number, end: number, text: string }>> }} src
+ * where the corpus is, and the clip's cues (the build's cue source, or umtool's)
+ */
+export async function lookWords(entry, provenance, look, from, to, { channelsDir, cues }) {
+ const inSpan = (w) => Number.isFinite(w.start) && Number.isFinite(w.end) && (w.start + w.end) / 2 >= from - 0.05 && (w.start + w.end) / 2 <= to + 0.05;
+ const rx = lookMatches(entry, provenance, look.reactions) ? look.reactions : null;
+ const turns = rx ? rx.turns.filter((t) => t.end > from && t.start < to) : [];
+ const speakers = rx?.speakers ?? [];
+ if (rx) {
+ look.words ??= readFile(path.join(look.manifestDir, typeof rx.source.words === "string" ? rx.source.words : "words.json"), "utf8")
+ .then((t) => {
+ const doc = JSON.parse(t);
+ return (Array.isArray(doc) ? doc : doc?.words ?? []).map(wordOf);
+ })
+ .catch(() => null);
+ const ws = await look.words;
+ if (ws?.length) {
+ const got = ws.filter(inSpan);
+ if (got.length) return { words: got, turns, speakers, wordsFrom: "words.json" };
+ }
+ }
+ if (!hasLocalMedia(entry) && channelsDir && entry.video) {
+ const slug = entry.channel ?? provenance?.channelSlug;
+ const key = `${slug}/${entry.video}`;
+ if (!look.transcripts.has(key)) {
+ look.transcripts.set(key, resolveVideoDir(channelsDir, slug, entry.video)
+ .then((dir) => readFile(path.join(dir, "transcript.json"), "utf8"))
+ .then((t) => whisperWords(JSON.parse(t)))
+ .catch(() => null));
+ }
+ const ws = await look.transcripts.get(key);
+ const got = (ws ?? []).map(wordOf).filter(inSpan);
+ if (got.length) return { words: got, turns, speakers, wordsFrom: "transcript.json" };
+ }
+ const cs = fxWordsOf(await cues(entry), from - 0.05, to + 0.05).map(wordOf);
+ return { words: cs, turns, speakers, wordsFrom: "cues" };
+}
+
+/**
+ * One clip's room (room.mjs's rule): where its sound stops and whether its
+ * head is muted, from its words -- `words(from, to)`, the build's lookWords
+ * -- else the silences (`silences(from, to)`, detectRoomSilences); the plan,
+ * in the file's seconds; and what its cut record says. Null when the clip has
+ * no room (or nothing moves). `first`: nothing comes before it, so no head.
+ * `notes` are the build's log lines, said by the caller.
+ *
+ * @param {{ entry: any, render: any, D: number, first: boolean, fetchStart: number, cutA: number, cutB: number,
+ * duration: number | null, file: string,
+ * words: (from: number, to: number) => Promise<{ words: Array<{ start: number, end: number }>, wordsFrom: string } | null>,
+ * silences: (from: number, to: number) => Promise<Array<{ s: number, e: number }>> }} o
+ */
+export async function roomOfCut({ entry, render, D, first, fetchStart, cutA, cutB, duration, file, words, silences }) {
+ const room = clipRoom(entry, render);
+ if (!room) return null;
+ const head = room.head && !first;
+ if (!room.tail && !head) return null;
+ const notes = [];
+ const got = await words(fetchStart + cutA - 1, fetchStart + cutB + room.maxS + 1).catch(() => null);
+ const ws = (got?.words ?? []).map((w) => ({ start: w.start - fetchStart, end: w.end - fetchStart }));
+ let via = ws.length ? got.wordsFrom : "silence";
+ let tail = room.tail && ws.length ? tailFromWords(ws, cutB, room) : null;
+ let speech = head && ws.length ? speechStartFromWords(ws, cutA) : null;
+ // Cues abut: a run of them that reaches the cap says nothing about where
+ // anybody stops, so the sound decides that edge instead.
+ const detectTail = room.tail && (!ws.length || (via === "cues" && tail?.capped));
+ if (detectTail || (head && !ws.length)) {
+ const end = Math.min(duration ?? Infinity, cutB + room.maxS + 0.5);
+ const sil = await silences(Math.min(cutA, cutB) - 0.5, end);
+ if (detectTail) {
+ tail = tailFromSilences(sil, cutB, room);
+ via = ws.length ? `${via}+silence` : "silence";
+ if (!tail.found) notes.push(`${entry.id}: no silence within ${room.maxS} s of its end — its sound stops at the cut`);
+ }
+ if (head && !ws.length) speech = speechStartFromSilences(sil, cutA);
+ }
+ const plan = roomPlan({ cutA, cutB, D, soundEnd: tail ? tail.at : null, speechStart: head ? speech : null, duration });
+ if (plan.picA === cutA && plan.picB === cutB) return null;
+ if (tail?.capped) notes.push(`${entry.id}: still talking ${room.maxS} s past its end — its sound fades there (render.room.maxS)`);
+ for (const edge of plan.clamped) {
+ notes.push(`${entry.id}: its ${edge === "tail" ? "tail" : "head"} room is clamped to ${path.basename(file)}'s ${edge === "tail" ? "end" : "start"} (a fetched window; widen the extent or fetch it whole)`);
+ }
+ const s3 = (t) => Number((fetchStart + t).toFixed(3));
+ return {
+ plan,
+ notes,
+ record: {
+ sound: [s3(plan.soundA), s3(plan.soundB)], head: plan.head, tail: plan.tail, via,
+ ...(tail?.capped ? { capped: true } : {}),
+ ...(plan.clamped.length ? { clamped: plan.clamped } : {}),
+ },
+ };
+}
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -27,6 +27,7 @@
"./clip-blur": "./clip-blur.mjs",
"./compose-chrome": "./compose-chrome.mjs",
"./cues": "./cues.mjs",
+ "./cut-points": "./cut-points.mjs",
"./deck": "./deck.mjs",
"./drafts-review": "./drafts-review.mjs",
"./factcheck": "./factcheck.mjs",
@@ -52,6 +53,7 @@
"./resolve-windows": "./resolve-windows.mjs",
"./room": "./room.mjs",
"./shoot-page": "./shoot-page.mjs",
+ "./snap": "./snap.mjs",
"./social": "./social.mjs",
"./sources": "./sources.mjs",
"./sync-report": "./sync-report.mjs",
diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs
@@ -0,0 +1,116 @@
+// WHERE THE RENDER CUTS A CLIP, as arithmetic: a desired edge moved to the
+// nearest silence (`snap`), and the two edges of a clip kept from inverting
+// or collapsing (`snapCut`). Pure -- no ffmpeg, no fs -- so the build
+// (build-video.mjs buildClipSegment), umtool's cut-points route (the Play view
+// plays these edges) and the clip bench's ghost markers (drawn live while an
+// edge is dragged, from the silences the route measured once) run ONE
+// implementation, in the browser as on the server. The silences themselves are
+// measured by cut-points.mjs `detectSilence`, the build's own.
+//
+// EVERYTHING HERE IS IN THE SOURCE FILE'S SECONDS (0 = the window's first
+// sample, `fetchStart` in the recording) unless a name says `source`: that is
+// the clock the build snaps on, and the same float arithmetic on the same
+// clock is what makes the route's edges the build's to the millisecond.
+
+/** The render's defaults for the snap knobs (render.snapWindow, snapLead, snapTail, silence*). */
+export const SNAP_DEFAULTS = Object.freeze({
+ snapWindow: 1.6,
+ silenceMinDur: 0.09,
+ silenceRelDb: 6,
+ lead: 0.10,
+ tail: 0.18,
+});
+
+/**
+ * Snap a desired cut to the nearest silence, so the clip begins and ends
+ * between words instead of through one. Returns the desired point unchanged
+ * when no silence is close enough -- better a tight cut than a cut in the
+ * wrong place.
+ *
+ * How much of the pause is kept: 0.10 s before speech resumes, 0.18 s after it
+ * stops, unless the render says `snapLead` / `snapTail` -- and then never more
+ * than the pause holds, so a long one keeps its breath (room for the
+ * crossfade to fade over silence, not the last word) without reaching the
+ * next word.
+ *
+ * @param {number} desired
+ * @param {Array<{ s: number, e: number }>} intervals the silences, file seconds
+ * @param {"start" | "end"} kind
+ * @param {number} window how far a silence may be (render.snapWindow)
+ * @param {{ snapLead?: number, snapTail?: number }} [render]
+ * @returns {{ at: number, snapped: boolean }}
+ */
+export function snap(desired, intervals, kind, window, render = {}) {
+ let best = null;
+ for (const iv of intervals) {
+ // Starting: we want to resume just before speech does -> the silence's END.
+ // Ending: we want to stop just after speech does -> the silence's START.
+ const point = kind === "start" ? iv.e : iv.s;
+ const d = Math.abs(point - desired);
+ if (d > window) continue;
+ if (!best || d < best.d) best = { d, point, iv };
+ }
+ if (!best) return { at: desired, snapped: false };
+ const set = kind === "start" ? render.snapLead : render.snapTail;
+ let lead = kind === "start" ? -SNAP_DEFAULTS.lead : SNAP_DEFAULTS.tail;
+ if (Number.isFinite(set) && set >= 0) {
+ const room = best.iv.e - best.iv.s;
+ lead = (kind === "start" ? -1 : 1) * Math.min(set, room);
+ }
+ return { at: Math.max(0, best.point + lead), snapped: true };
+}
+
+/**
+ * A clip's two edges as the render cuts them: each snapped (`snap`), then
+ * never inverted or collapsed -- the start at least a second before the
+ * desired end, the end at least a second after the start.
+ *
+ * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any> }} o
+ * `wantA`/`wantB`: the play window's edges in the file's seconds
+ */
+export function snapCut({ sil, wantA, wantB, render = {} }) {
+ const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow;
+ const a = snap(wantA, sil, "start", win, render);
+ const b = snap(wantB, sil, "end", win, render);
+ const cutA = Math.min(a.at, wantB - 1);
+ const cutB = Math.max(b.at, cutA + 1);
+ return { win, a, b, cutA, cutB };
+}
+
+/** A source second as the cut record writes it (`<id>.cut.json`, three decimals). */
+export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3));
+
+/**
+ * The render's cut of one clip in SOURCE seconds, from the silences of the
+ * file it is cut from: what `<id>.cut.json` records (`start`, `end`,
+ * `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are
+ * the play window (deck.mjs playWindow); `fetchStart` the file's first
+ * second in the recording.
+ *
+ * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any> }} o
+ */
+export function renderCut({ sil, fetchStart, playFrom, playTo, render = {} }) {
+ const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render });
+ return {
+ start: recordSecond(fetchStart, c.cutA),
+ end: recordSecond(fetchStart, c.cutB),
+ snapped: { start: c.a.snapped, end: c.b.snapped },
+ file: { cutA: c.cutA, cutB: c.cutB },
+ };
+}
+
+/**
+ * The render knobs that move a snapped edge, and nothing else: what a cache of
+ * cut points is keyed by, so a change of any other knob reuses it.
+ *
+ * @param {Record<string, any>} render
+ */
+export function snapKnobs(render = {}) {
+ return {
+ snapWindow: render.snapWindow ?? SNAP_DEFAULTS.snapWindow,
+ silenceMinDur: render.silenceMinDur ?? SNAP_DEFAULTS.silenceMinDur,
+ silenceRelDb: render.silenceRelDb ?? SNAP_DEFAULTS.silenceRelDb,
+ snapLead: Number.isFinite(render.snapLead) ? render.snapLead : null,
+ snapTail: Number.isFinite(render.snapTail) ? render.snapTail : null,
+ };
+}