commit 30075252e153cb99395b3023238ab9c82e79f43d
parent e14ce9384e941070590c5d7cf0919fea20aa4290
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 24 Oct 2026 02:55:11 -0400
Play the cut: the sound on one Web Audio clock, the picture slaved to it
A new engine (components/projects/review/playEngine/) behind usePlayEngine,
replacing PlayCut.tsx's two-slot tick with the same outward transport
(seekTo, next/prev/skip, rate, the ui state, the data-play-* attributes):
- every clip's sound decoded once (the bench's /api/report/audio, now with
`take`; audioBank.ts holds the clips around the playhead within a byte
budget) and scheduled back to back on ONE AudioContext (playSchedule.mjs):
sample-exact starts and stops at the render's edges, the crossfade as the
build's two linear ramps, the loudness gain, room's muted edges, the
clip's audio knobs and the mute mark as gain automation, a speed time-
stretched at its pitch as the bench does. A clip not decoded when due
holds the clock (`waiting`); no Web Audio, the element's own sound.
- the clock of the whole view is that context's time mapped through the
plan; the picture follows it: the <video> slots slaved by
requestVideoFrameCallback (nudged past a frame of drift, re-seeked past a
quarter second), a crossfade drawn as a dissolve of the two
(footageCanvas.ts drawFootageLayers). WebCodecs (codecPicture.ts, its mp4
index and frame queue) is in, asked for by name: ?picture=webcodecs.
Unit tests: the schedule (gapless joins to the sample, crossfade ramps, a
seek mid-clip and mid-ramp, speed, room/gain/knobs/mute), the mp4 index
against ffprobe, the frame queue (bounded, every frame closed).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
16 files changed, 2374 insertions(+), 269 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/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -12,15 +12,15 @@ import { cn } from "@/lib/utils";
import { footageAt } from "@/lib/report/footage-move.mjs";
import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
import {
- chromeTime, counterSteps, cutAtSource, cutNotesRequest, itemIndexAt, playPlan, playTimeOfChrome, 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 ReelStrip, { type StripCounter } from "./ReelStrip";
+import { usePlayEngine } from "./playEngine/usePlayEngine";
import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
+import type { EngineInfo } from "./playEngine/engine";
+import ReelStrip, { type StripCounter } from "./ReelStrip";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -32,18 +32,18 @@ import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
// the estimate's segments (the live preview's schedule when the cut has a
// deck: posts' holds included), re-timed by the RENDER'S EDGES -- each clip
// snapped to its silences exactly as the build snaps it (the cut-points
-// route, lib/report/cutPoints.mjs) -- each clip played from its cached source
-// window -- the bench's own media route, /api/report/raw, `take` for a take's
-// clip -- and the crossfades played as HARD CUTS at the middle of each one.
-// The chrome, composed on the estimate's clock, is seeked by the source
-// second playing (chromeTime), so a stamp lands on its word.
-// While a clip plays the clock IS its <video>'s position mapped through the
-// play window (liveClock.mjs's rule), so the deck's rail pip, the tally, the
-// stamps and the finale advance exactly as the live preview places them; a
-// card, a hold or a clip with no media on disk advance it by the wall clock.
+// 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,
@@ -161,8 +161,13 @@ const KEYS: { keys: string; what: string }[] = [
{ keys: "?", what: "these keys" },
];
-/** What Play does not do as the render does: the line under the picture. */
-function approximateLine(edges: RenderCuts) {
+/**
+ * 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
@@ -171,7 +176,19 @@ function approximateLine(edges: RenderCuts) {
: edges.state === "measuring"
? "edges are the manifest's until the render's are measured"
: `edges are the manifest's (the render's could not be measured: ${edges.why ?? "no answer"})`;
- return `Approximate: crossfades are hard cuts at their middle, cards and teasers are placeholders, the sound is the recording's own, the chrome is composed on the estimate's clock; ${edge}.`;
+ 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). */
@@ -241,144 +258,21 @@ export default function PlayCut({
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],
);
-
- // 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]);
+ 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;
// `?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
@@ -403,97 +297,10 @@ export default function PlayCut({
if (composeState !== "composing" && edges.state !== "measuring") anchor.current = null;
}, [plan, composeState, edges.state, 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]);
-
// ---- 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 });
@@ -504,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 });
@@ -535,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;
@@ -545,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) {
@@ -555,12 +362,12 @@ export default function PlayCut({
}, [setPlaying]);
const stepNote = useCallback(
(d: 1 | -1) => {
- const t = eng.current.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, noteT],
+ [mine, seekTo, now, noteT],
);
// `?note=<id>` (the Inbox's link): seek to it once the notes are read.
@@ -575,11 +382,11 @@ export default function PlayCut({
// ---- 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;
@@ -598,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();
@@ -625,7 +432,7 @@ 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;
@@ -731,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");
@@ -748,6 +555,8 @@ export default function PlayCut({
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))]"
@@ -806,8 +615,8 @@ 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 ? (
@@ -931,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>
- {approximateLine(edges)}
+ {approximateLine(edges, engine.info)}
{!view.blurRendered ? " Blurred clips play unblurred (render.blur off)." : ""}
{view.note ? ` ${view.note}.` : ""}
</span>
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,163 @@
+// 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;
+ rvfc: number;
+};
+
+export class ElementPicture {
+ private slots: Slot[] = [0, 1].map(() => ({ el: null, index: -1, url: "", presented: null, presentedAt: 0, rvfc: 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;
+ }
+
+ /** 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;
+ 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;
+ 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,666 @@
+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: on two <video> elements slaved to it
+// (elementPicture.ts), a crossfade drawn as a dissolve of the two; by
+// WebCodecs (codecPicture.ts) when the URL asks for it, `?picture=webcodecs`.
+// 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 }[],
+ 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);
+ // WebCodecs is asked for by name here (`?picture=webcodecs`); the elements are the picture.
+ this.codecs = o.picture === "webcodecs" && 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();
+ // 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);
+ this.measured.nodes = [...this.measured.nodes, { id: p.id, at: this.c0 + p.atWall, stop, late }].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, el.currentTime, this.mediaTimeOf(v.i, t), 1 / 30);
+ 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/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts
@@ -17,7 +17,7 @@ import * as urls from "./urls";
// 1.000-3.082, c02 3.011-6.101, c04 6.007-8.000, so with the 0.2 s
// crossfades: c01 0-2.082 (shown to 1.982), c02 1.882-4.972 (shown 1.982-
// 4.872), k01 4.772-6.272 (shown to 6.172), c03 6.072-8.072 (shown to
-// 7.972), c04 7.872-9.865. play-engine.spec.ts covers the edges themselves.
+// 7.972), c04 7.872-9.865. 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.
// ---------------------------------------------------------------------------
@@ -68,9 +68,8 @@ test("the cut plays clip after clip on one clock; prev / next / keys; the strip
// ...and carries on into clip 2 (c01 is shown to 1.982 s on the render's clock).
await expect(root(page)).toHaveAttribute("data-play-item", "c02", { timeout: 20_000 });
await expect(page.locator('[data-play-row="c02"]')).toHaveAttribute("aria-current", "true");
- await expect
- .poll(() => page.locator('video[data-play-slot-item="c02"]').evaluate((v: HTMLVideoElement) => !v.paused && v.readyState >= 2), { timeout: 15_000 })
- .toBe(true);
+ // 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(1.982);
// NOW: c02 on the reader, the next entry named.
await expect(page.locator('[data-play-now="c02"]')).toBeVisible();
diff --git a/umtool/e2e/play-engine.spec.ts b/umtool/e2e/play-engine.spec.ts
@@ -5,12 +5,18 @@ import { fileURLToPath } from "node:url";
import * as urls from "./urls";
// ---------------------------------------------------------------------------
-// The Play view plays the render's cut, edges first:
+// 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: <video> elements slaved to it (a
+// dissolve is two layers)
//
// Fixture: e2e/fixtures/play-cut-fixture.mjs's play-engine-fixture (the
// play-cut cut, which this spec WRITES). On vid1's window (silences
@@ -56,6 +62,57 @@ test("the render's edges: Play schedules each clip as the build cuts it, and say
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 1.982, crossfading 1.882-2.082).
+ 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: c02 starts 0.2 s (the crossfade) before c01 stops.
+ const c01 = s.scheduled.find((n) => n.id === "c01")!;
+ const c02 = s.scheduled.find((n) => n.id === "c02")!;
+ expect(c01 && c02).toBeTruthy();
+ expect(Math.max(...s.scheduled.map((n) => n.late))).toBeLessThanOrEqual(0);
+ expect(Math.abs(c01.stop - c02.at - 0.2)).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: the <video> elements follow the clock, a dissolve is two layers", async ({ page }) => {
+ for (const [q, want] of [["?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 (1.982) is inside the crossfade from c01 (1.882-2.082): 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"]');
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/playSchedule.mjs b/umtool/lib/report/playSchedule.mjs
@@ -0,0 +1,170 @@
+// 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
+ * footage's end (a carrying clip's hold is silent, as the
+ * build pads it)
+ * 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;
+ const to = c.playEnd;
+ 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,109 @@
+// 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("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 });
+});