commit 88fbd65cb1db50e88f42719ea6e0d31343bedae1
parent e9fcb3c52c0d6b21aba1011bca1c08b8f7164eea
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 16:53:15 -0500
umtool: Play fetches the post items ahead and never cuts one short for loading (operator, 4 Nov: "The rapid sections on play the cut don't load fast enough such that most of it is cut out. Can we maybe preload?") -- while one item plays, the post items starting within ~20 s after it (at least 3, at most 24: a fast burst has many ahead) are fetched nearest first, 4 at a time (playEngine/postPreload.ts): the card's page with its faces, avatars and a parent's shot written into it as blob URLs (drawn as srcdoc), the picked take, every attachment the plan shows, held as blobs and let go behind the playhead; the player takes them as it mounts (a src never swapped under a playing element). THE GATE (engine.ts): a post item not ready holds the clock like a buffer stall -- on the item before's last frame while it is still fetching, then at its first second until its card is drawn and its voice and first attachment can play (at most 15 s), "loading…" over the picture -- then plays in full; every hold counted (stats.waits) and logged ("[play] held …")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 519 insertions(+), 26 deletions(-)
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -18,7 +18,8 @@ import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from ".
import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
import { usePlayEngine } from "./playEngine/usePlayEngine";
import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
-import type { EngineInfo, MediaRef } from "./playEngine/engine";
+import type { EngineInfo, ItemGate, MediaRef } from "./playEngine/engine";
+import { postPreload } from "./playEngine/postPreload";
import ReelStrip, { type StripCounter, type StripEdit } from "./ReelStrip";
import { useWaveZoom, ZoomControls } from "../bench/GapsZoom";
import { followVis, itemSections } from "@/lib/report/stripDrag.mjs";
@@ -27,7 +28,7 @@ import WhatPlays, { type WorkingCut } from "./WhatPlays";
import { useCutApp } from "../cutApp/CutApp";
import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport";
import AddPost from "./AddPost";
-import PostItemPlayer, { type PostPlan } from "./PostItemPlayer";
+import PostItemPlayer, { postItemAssets, type PostPlan } from "./PostItemPlayer";
import ComboBadge, { type ComboInfo } from "./ComboBadge";
// ---------------------------------------------------------------------------
@@ -240,6 +241,19 @@ function approximateLine(edges: RenderCuts, info: EngineInfo | null) {
].filter(Boolean).join(" ");
}
+/**
+ * POST ITEMS FETCHED AHEAD (postPreload.ts; operator, 4 Nov: "the rapid sections ... don't load fast enough"):
+ * the post items whose start is within this many cut seconds after the one on screen -- at least PRELOAD_MIN of
+ * them, at most PRELOAD_MAX -- so a burst of short items has many ahead, a slow stretch a few.
+ */
+const PRELOAD_AHEAD_S = 20;
+const PRELOAD_MIN = 3;
+const PRELOAD_MAX = 24;
+/** An item fetched ahead plays once its player says it is ready, or this long after it is first on screen. */
+const GATE_GRACE_MS = 400;
+/** The clock never waits longer than this on one item (a page that never says it is ready). */
+const GATE_MAX_MS = 15_000;
+
/** The pinned player as a strip, once the transport is under it (a phone). */
const STRIP_H = 120;
@@ -395,8 +409,32 @@ export default function PlayCut({
}).toString()}`,
[project, take],
);
+ // THE GATE (engine.ts): a post item plays once its player is ready -- its card drawn, its voice and its first
+ // attachment able to play -- and the clock waits on it, never cutting it short (a buffer stall's wait). Fetched
+ // ahead (postPreload.ts), it is ready as it comes on screen; the clock holds on the item before while it is
+ // still fetching. `postReady`: the item whose player said so (one is mounted at a time).
+ const entryOfRef = useRef(entryOf);
+ entryOfRef.current = entryOf;
+ const postReady = useRef<string | null>(null);
+ const gateAsked = useRef(new Map<string, number>());
+ const gate = useCallback<ItemGate>((id, next) => {
+ const e = entryOfRef.current.get(id);
+ if (!(e?.type === "post" && e.post && e.postPlan)) return "ready";
+ const now = performance.now();
+ const key = `${next ? "next" : "on"}:${id}`;
+ let since = gateAsked.current.get(key);
+ if (since === undefined) gateAsked.current.set(key, (since = now));
+ if (now - since > GATE_MAX_MS) return "ready";
+ const st = postPreload.itemState(id);
+ if (next) return st === "loading" ? "fetching" : "ready";
+ if (postReady.current === id) return "ready";
+ return st === "ready" && now - since > GATE_GRACE_MS ? "ready" : "wait";
+ }, []);
+ const onPostReady = useCallback((id: string) => {
+ postReady.current = id;
+ }, []);
const engine = usePlayEngine({
- plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring",
+ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", gate,
});
const { ui, rate, failed, now } = engine;
const setRate = engine.setRate;
@@ -831,6 +869,38 @@ export default function PlayCut({
const placeholder = item && !postNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
const pct = (n: number, of: number) => `${(n / of) * 100}%`;
+ // ---- post items fetched ahead (postPreload.ts): from the one on screen, ~20 s on --------------------------
+ const postBox = box ? { width: box.width, height: box.height } : { width: 1920, height: 1080 };
+ const postBoxKey = `${Math.round(postBox.width)}x${Math.round(postBox.height)}`;
+ useEffect(() => {
+ // A new item on screen: its gate is asked afresh (a revisit waits as the first visit did).
+ gateAsked.current.clear();
+ if (postReady.current !== (plan.items[ui.cur]?.id ?? null)) postReady.current = null;
+ }, [ui.cur, plan]);
+ useEffect(() => {
+ const items = plan.items;
+ const i = ui.cur;
+ const [w, h] = postBoxKey.split("x").map(Number);
+ const assetsOf = (k: number) => {
+ const it = items[k];
+ const e = it ? entryOf.get(it.id) : null;
+ if (!e || e.type !== "post" || !e.post || !e.postPlan) return null;
+ const before = k > 0 ? entryOf.get(items[k - 1]?.id ?? "") : null;
+ const joinFrom = e.postPlan.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null;
+ return postItemAssets({ project, take, entry: e.post, plan: e.postPlan, box: { width: w, height: h }, published: asPublished, uncensored, joinFrom });
+ };
+ const keep = [i - 1, i].map(assetsOf).filter((x): x is NonNullable<typeof x> => !!x);
+ const ahead: NonNullable<ReturnType<typeof assetsOf>>[] = [];
+ const from = items[i]?.to ?? 0;
+ for (let k = i + 1, n = 0; k < items.length && ahead.length < PRELOAD_MAX; k += 1, n += 1) {
+ if (items[k].from - from > PRELOAD_AHEAD_S && n >= PRELOAD_MIN) break;
+ const a = assetsOf(k);
+ if (a) ahead.push(a);
+ }
+ postPreload.want(ahead, keep);
+ }, [ui.cur, plan, entryOf, project, take, asPublished, uncensored, postBoxKey]);
+ useEffect(() => () => postPreload.clear(), []);
+
// The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's.
const counters = useMemo<StripCounter[]>(() => {
const stamps = (schedule?.factcheck?.stamps as { landed: number; verdict: string; count?: number }[] | undefined) ?? view.counter.stamps;
@@ -860,6 +930,7 @@ export default function PlayCut({
uncensored={uncensored}
scene={postNow.entry.postScene ?? null}
clock={postNow.entry.postClock ?? null}
+ onReady={onPostReady}
joinFrom={(() => {
// THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended.
const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null;
@@ -1053,6 +1124,12 @@ export default function PlayCut({
{placeholderCard}
</div>
)}
+ {ui.playing && ui.waiting && (
+ // The clock held (engine.ts): a clip's sound decoding, a post item loading -- it plays in full once here.
+ <span data-play-loading="" className="pointer-events-none absolute right-2 top-2 z-40 rounded-full bg-black/70 px-2 py-0.5 text-[11px] text-white">
+ loading…
+ </span>
+ )}
</div>
{/* The strip's right side (a phone): where you are. */}
{compact && (
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -13,6 +13,7 @@ import {
CAPTION_SLIDE, captionCss, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, measureCaptionWords, mountCaptions, paletteOfDoc, placeCaption, setCaptionState, slideDir,
} from "umtool-report-to-video/post-caption";
import { clockCss, clockFace, clockHtml, clockStateAt, measureClockPlace, mountClock, setClockState } from "umtool-report-to-video/post-clock";
+import { postPreload, type PostAssets } from "./playEngine/postPreload";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
@@ -167,6 +168,70 @@ export function takeFileUrl(project: string, rel: string) {
return `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`;
}
+type PageOpts = { project: string; id: string; box: Box; phase: "read" | "media"; take?: string | null; cardKey?: string | null; published?: boolean; uncensored?: boolean };
+
+/** A post item's card page (the post-item route), as the player draws it and Play fetches it ahead (postPreload.ts). */
+export function postPageUrl({ project, id, box, phase, take = null, cardKey = null, published = false, uncensored = false }: PageOpts) {
+ return `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""}`;
+}
+
+/**
+ * EVERYTHING A POST ITEM'S PLAYER WILL ASK FOR (Play fetches it ahead, postPreload.ts): its card's pages -- the
+ * read, the media phase of a stacked one, the join's (the item before's page) -- and its files: the picked take,
+ * every attachment its plan shows (and a video's words), the panel's, what the join opens on. The same URLs the
+ * player builds, so what was fetched is what it draws.
+ */
+export function postItemAssets({ project, take = null, entry, plan, box, published = false, uncensored = false, joinFrom = null }: {
+ project: string; take?: string | null; entry: Record<string, unknown> & { id: string }; plan: PostPlan; box: Box; published?: boolean; uncensored?: boolean;
+ joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null;
+}): PostAssets {
+ const page = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored });
+ const docs = [page(entry.id, "read")];
+ if (postLayout(entry, box).mode === "stack") docs.push(page(entry.id, "media"));
+ if (joinFrom && (plan.follow?.join?.seconds ?? 0) > 0) docs.push(page(joinFrom.entry.id, "read"));
+ const files: string[] = [];
+ const voice = plan.narration ? (pickedTake(entry) as { file?: string } | null) : null;
+ if (voice?.file) files.push(takeFileUrl(project, voice.file));
+ for (const st of plan.steps) {
+ for (const m of st.items) {
+ files.push(postFileUrl(project, String(m.src)));
+ if (st.kind === "video" && typeof m.words === "string") files.push(postFileUrl(project, m.words));
+ }
+ }
+ for (const sh of plan.panel?.shows ?? []) for (const m of sh.media) files.push(postFileUrl(project, m.src));
+ if (joinFrom) for (const x of endMediaOf(joinFrom.plan as never, { stepAt, mediaTimeAt }) as Array<{ m: { src?: unknown } }>) if (x.m.src) files.push(postFileUrl(project, String(x.m.src)));
+ return { id: entry.id, docs: [...new Set(docs)], files: [...new Set(files)] };
+}
+
+/**
+ * What an element draws from, decided when it is first drawn (postPreload.ts): the bytes Play fetched ahead when
+ * they are here, else the URL -- and never changed under it after (a src swapped mid-play would load it again).
+ */
+function useFirstSrc() {
+ const seen = useRef(new Map<string, string>());
+ return useCallback((url: string) => {
+ let v = seen.current.get(url);
+ if (v === undefined) {
+ v = postPreload.urlOf(url);
+ seen.current.set(url, v);
+ }
+ return v;
+ }, []);
+}
+
+/** A card page's frame: its srcdoc when Play fetched it ahead (decided when it is first drawn), else its src. */
+function useFirstDoc() {
+ const seen = useRef(new Map<string, string | null>());
+ return useCallback((url: string): { src?: string; srcDoc?: string } => {
+ let v = seen.current.get(url);
+ if (v === undefined) {
+ v = postPreload.docOf(url);
+ seen.current.set(url, v);
+ }
+ return v === null ? { src: url } : { srcDoc: v };
+ }, []);
+}
+
// ---------------------------------------------------------------------------
// THE MUFFLE, LIVE (post-narration.mjs; the render's mix in WebAudio): a
// sound-bearing attachment under a narration goes through two branches --
@@ -274,6 +339,7 @@ function MediaEl({
}) {
const ref = useRef<HTMLVideoElement | null>(null);
const img = useRef<HTMLImageElement | null>(null);
+ const srcOf = useFirstSrc();
// The muffle follows the clock: the gains set from the item's second, as the render's expressions are.
const muffled = !!mix && mix.duck && step.sound;
useEffect(() => {
@@ -328,7 +394,7 @@ function MediaEl({
{timed ? (
<video
ref={ref}
- src={postFileUrl(project, String(m.src))}
+ src={srcOf(postFileUrl(project, String(m.src)))}
data-post-video={m.i}
data-post-video-playing={run ? "1" : "0"}
data-post-video-rate={String(speed)}
@@ -342,7 +408,7 @@ function MediaEl({
// eslint-disable-next-line @next/next/no-img-element
<img
ref={img}
- src={postFileUrl(project, String(m.src))}
+ src={srcOf(postFileUrl(project, String(m.src)))}
alt=""
data-post-image={m.i}
style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center", filter: wholeBlur }}
@@ -375,6 +441,7 @@ function MediaEl({
/** The panel's shows over the slot, as the build lays them: each crossfaded, a tall picture read through scrolled. */
function PanelShows({ project, shows, fade, slot, box, s }: { project: string; shows: PanelShow[]; fade: number; slot: Rect; box: Box; s: number }) {
+ const srcOf = useFirstSrc();
return (
<>
{shows.map((sh, i) => {
@@ -395,9 +462,9 @@ function PanelShows({ project, shows, fade, slot, box, s }: { project: string; s
<div key={`${sh.scope}:${i}`} data-post-panel={sh.scope} className="absolute z-10 overflow-hidden" style={{ left: pct(left, box.width), top: pct(top, box.height), width: pct(bw, box.width), height: pct(bh, box.height), opacity: op }}>
{m.kind === "image" ? (
// eslint-disable-next-line @next/next/no-img-element
- <img alt="" src={postFileUrl(project, m.src)} style={{ position: "absolute", left: 0, top: `${(y / bh) * 100}%`, width: "100%", height: scroll ? `${(full / bh) * 100}%` : "100%", display: "block" }} />
+ <img alt="" src={srcOf(postFileUrl(project, m.src))} style={{ position: "absolute", left: 0, top: `${(y / bh) * 100}%`, width: "100%", height: scroll ? `${(full / bh) * 100}%` : "100%", display: "block" }} />
) : (
- <video src={postFileUrl(project, m.src)} muted loop autoPlay playsInline style={{ width: "100%", height: "100%" }} />
+ <video src={srcOf(postFileUrl(project, m.src))} muted loop autoPlay playsInline style={{ width: "100%", height: "100%" }} />
)}
</div>
);
@@ -408,13 +475,14 @@ function PanelShows({ project, shows, fade, slot, box, s }: { project: string; s
/** THE JOIN's outgoing attachments (post-join.mjs endMediaOf): the item before's last frame at its slot, fading out. */
function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: Array<{ m: Record<string, unknown> & { src?: string; kind?: string }; t: number }>; layout: { slot: Rect | null }; box: Box; op: number }) {
+ const srcOf = useFirstSrc();
if (!layout.slot || !ends.length || op <= 0) return null;
const boxes = stepBoxes({ items: ends.map((x, j) => ({ ...x.m, i: j })) } as never, layout.slot) as Rect[];
return (
<>
{ends.map((x, j) => {
const b = boxes[j];
- const src = postFileUrl(project, String(x.m.src ?? ""));
+ const src = srcOf(postFileUrl(project, String(x.m.src ?? "")));
const style = { left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height), opacity: op, zIndex: 3 };
return x.m.kind === "image" ? (
// eslint-disable-next-line @next/next/no-img-element
@@ -428,8 +496,13 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A
}
export default function PostItemPlayer({
- project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null,
+ project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, onReady,
}: {
+ /**
+ * Called once the item can play from its first frame (Play's clock waits for it, engine.ts `gate`): its card
+ * drawn and measured, its voice and the attachment it opens on able to play (or failed: nothing to wait for).
+ */
+ onReady?: (id: string) => void;
project: string;
take?: string | null;
entry: Record<string, unknown> & { id: string };
@@ -488,10 +561,11 @@ export default function PostItemPlayer({
return () => ro.disconnect();
}, [box.width]);
const layout = useMemo(() => postLayout(entry, box), [entry, box]);
- const pageUrlOf = (id: string, phase: "read" | "media") =>
- `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""}`;
- const pageUrl = (phase: "read" | "media") =>
- `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""}`;
+ const pageUrlOf = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored });
+ const pageUrl = (phase: "read" | "media") => postPageUrl({ project, id: entry.id, box, phase, take, cardKey, published, uncensored });
+ // Fetched ahead by Play (postPreload.ts): drawn from those bytes, decided as each is first drawn.
+ const docOf = useFirstDoc();
+ const fileOf = useFirstSrc();
const reading = s < plan.reading || !plan.steps.length;
const current = stepAt(plan, s);
// Beside the card, the first attachment is up (its first frame) while the words are read.
@@ -504,7 +578,7 @@ export default function PostItemPlayer({
useEffect(() => {
if (!wordsRel || cues[wordsRel]) return;
let gone = false;
- fetch(postFileUrl(project, wordsRel))
+ fetch(fileOf(postFileUrl(project, wordsRel)))
.then((r) => (r.ok ? r.json() : null))
.then((doc) => {
if (gone || !doc) return;
@@ -515,7 +589,7 @@ export default function PostItemPlayer({
return () => {
gone = true;
};
- }, [wordsRel, project, cues]);
+ }, [wordsRel, project, cues, fileOf]);
// ---- the word zooms, live: measured in the card page once it is drawn, applied on the item's clock ----
const readFrame = useRef<HTMLIFrameElement | null>(null);
// ---- THE JOIN, live (post-join.mjs): the item before's page in a frame of its own, at its last frame's state ----
@@ -763,6 +837,27 @@ export default function PostItemPlayer({
const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity;
setClockState(clockSt && clockAt && s < until ? { ...clockAt, st: clockSt } : null, doc);
}, [clockSt, clockAt, s, layout.mode, plan.steps]);
+ // ---- READY (Play's clock waits for it): the card measured, the voice and the first attachment able to play ----
+ const readyFor = useRef<string | null>(null);
+ const onReadyRef = useRef(onReady);
+ onReadyRef.current = onReady;
+ useEffect(() => {
+ if (!onReadyRef.current || readyFor.current === entry.id) return;
+ const id = setInterval(() => {
+ const node = wrap.current;
+ const doc = readFrame.current?.contentDocument;
+ if (!node || doc?.body?.getAttribute("data-post-ready") !== "1") return;
+ const a = voice.current;
+ // HAVE_FUTURE_DATA: it can play on from here; an error is nothing to wait for.
+ if (a && a.readyState < 3 && !a.error) return;
+ for (const v of Array.from(node.querySelectorAll<HTMLVideoElement>("video[data-post-video]"))) if (v.readyState < 2 && !v.error) return;
+ for (const im of Array.from(node.querySelectorAll<HTMLImageElement>("img[data-post-image]"))) if (!im.complete) return;
+ clearInterval(id);
+ readyFor.current = entry.id;
+ onReadyRef.current?.(entry.id);
+ }, 40);
+ return () => clearInterval(id);
+ }, [entry.id]);
const src = shown && inStep ? mediaTimeAt(shown, s) : null;
const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null;
return (
@@ -800,7 +895,7 @@ export default function PostItemPlayer({
>
{mix && voiceTake && (
// eslint-disable-next-line jsx-a11y/media-has-caption
- <audio ref={voice} src={takeFileUrl(project, voiceTake.file)} preload="auto" data-post-narration-audio={voiceTake.file} data-post-narration-rate={String(speed * readRate)} />
+ <audio ref={voice} src={fileOf(takeFileUrl(project, voiceTake.file))} preload="auto" data-post-narration-audio={voiceTake.file} data-post-narration-rate={String(speed * readRate)} />
)}
{scale > 0 && (
<div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}>
@@ -808,7 +903,7 @@ export default function PostItemPlayer({
title={`post ${entry.id}`}
ref={readFrame}
onLoad={onFrameLoad}
- src={pageUrl("read")}
+ {...docOf(pageUrl("read"))}
data-post-card-frame="read"
className="absolute inset-0 border-0"
style={{ width: box.width, height: box.height, visibility: mediaPhase ? "hidden" : "visible" }}
@@ -819,7 +914,7 @@ export default function PostItemPlayer({
title={`post ${joinFrom!.entry.id} (as it ended)`}
ref={joinFrame}
onLoad={onJoinLoad}
- src={pageUrlOf(joinFrom!.entry.id, "read")}
+ {...docOf(pageUrlOf(joinFrom!.entry.id, "read"))}
data-post-join-frame={joinFrom!.entry.id}
className="absolute left-0 top-0 border-0"
style={{
@@ -833,7 +928,7 @@ export default function PostItemPlayer({
{layout.mode === "stack" && (
<iframe
title={`post ${entry.id} (media)`}
- src={pageUrl("media")}
+ {...docOf(pageUrl("media"))}
data-post-card-frame="media"
className="absolute inset-0 border-0"
style={{ width: box.width, height: box.height, visibility: mediaPhase ? "visible" : "hidden" }}
diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts
@@ -23,6 +23,13 @@ import { ElementPicture } from "./elementPicture";
// 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 GATE (`gate`, Play's post items: PlayCut.tsx, postPreload.ts): an item
+// whose own player is not ready holds the clock the same way -- on the item
+// before's last frame while its bytes are still being fetched ahead, then at
+// its first second until its card is drawn and its voice can play -- so a
+// short item is never cut short by its loading. Every hold is counted
+// (`stats.waits`), and logged when it ends.
+//
// THE PICTURE FOLLOWS THE CLOCK: by WebCodecs where the browser has it
// (codecPicture.ts: the frame due at the clock, decoded ahead; a real
// dissolve), else on two <video> elements slaved to it (elementPicture.ts).
@@ -49,6 +56,11 @@ export type EngineEntry = {
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 };
+/**
+ * May the clock run into / in item `id`? "ready" yes; "fetching" (asked of the NEXT item, as the clock reaches it)
+ * holds on the item before's last frame; "wait" (the item on screen) holds at the second it is at.
+ */
+export type ItemGate = (id: string, next: boolean) => "ready" | "fetching" | "wait";
export type EngineInfo = {
/** Where the sound comes from: decoded and scheduled on one context, or the playing element. */
sound: "webaudio" | "element";
@@ -108,6 +120,10 @@ export class PlayEngine {
playing = false;
ended = false;
waiting = false;
+ /** Play's post items (PlayCut.tsx): an item not ready yet holds the clock (THE GATE above). */
+ gate: ItemGate | null = null;
+ /** The hold in force: why, for which item, since when (performance.now). */
+ private held: { why: "sound" | "fetching" | "wait"; id: string; since: number } | null = null;
rate = 1;
blurRendered = true;
bg = "#000";
@@ -145,6 +161,8 @@ export class PlayEngine {
run: 0,
drawn: 0, off: 0, worst: 0,
late: [] as { id: string; want: number; at: number }[],
+ /** Every hold while playing: how many, how long in all, the last few (why, the item, ms). */
+ waits: { count: 0, ms: 0, last: [] as { id: string; why: string; ms: number }[] },
};
private restartedAt = 0;
/** WebCodecs windows behind the clock, and since when (performance.now). */
@@ -265,6 +283,7 @@ export class PlayEngine {
this.t = this.now();
this.playing = false;
this.waiting = false;
+ this.endHold();
this.stopNodes();
this.elements.pauseAll();
}
@@ -318,6 +337,7 @@ export class PlayEngine {
/** (Re)start the clock at cut second t, and the sound from there. */
private restart(t: number) {
this.stopNodes();
+ this.endHold();
this.t = t;
this.waiting = false;
this.c0 = this.clockNow() + (this.sound === "webaudio" && this.ctx ? START_LEAD : 0);
@@ -344,12 +364,45 @@ export class PlayEngine {
this.nodes = [];
}
- /** Hold the clock at cut second t until the sound due there is decoded. */
- private hold(t: number) {
+ /** Hold the clock at cut second t until the sound due there is decoded (or the item gated there is ready). */
+ private hold(t: number, why: "sound" | "fetching" | "wait" = "sound", id = this.plan.items[this.cur]?.id ?? "") {
this.stopNodes();
this.t = t;
this.waiting = true;
this.elements.pauseAll();
+ if (!this.held) {
+ this.held = { why, id, since: performance.now() };
+ this.measured.waits.count += 1;
+ }
+ }
+
+ /** A hold ended (the clock runs again, a seek, a pause): counted, and said in the console. */
+ private endHold() {
+ const h = this.held;
+ if (!h) return;
+ this.held = null;
+ const ms = Math.round(performance.now() - h.since);
+ this.measured.waits.ms += ms;
+ this.measured.waits.last = [...this.measured.waits.last, { id: h.id, why: h.why, ms }].slice(-20);
+ console.info(`[play] held ${ms} ms on ${h.id} (${h.why === "sound" ? "its sound decoding" : h.why === "fetching" ? "the next post item still fetching" : "its card, voice or attachment loading"}) -- ${this.measured.waits.count} hold(s), ${(this.measured.waits.ms / 1000).toFixed(1)} s in all`);
+ }
+
+ /**
+ * THE GATE at cut second t: the item on screen not ready ("wait"), or the next one still fetching as the clock
+ * reaches it ("fetching": held just short of it, on this one's last frame).
+ */
+ private gated(t: number): { why: "fetching" | "wait"; at: number; id: string } | null {
+ if (!this.gate) return null;
+ const items = this.plan.items;
+ const i = Math.max(0, itemIndexAt(this.plan, Math.min(t, this.plan.total - 0.001)));
+ const it = items[i];
+ if (!it) return null;
+ if (this.gate(it.id, false) !== "ready") return { why: "wait", at: t, id: it.id };
+ const nx = items[i + 1];
+ if (nx && nx.from - t <= DUE * Math.max(1, this.rate) && this.gate(nx.id, true) === "fetching") {
+ return { why: "fetching", at: Math.max(it.from, Math.min(t, nx.from - 0.001)), id: nx.id };
+ }
+ return null;
}
// ---- the sound ------------------------------------------------------------------
@@ -520,11 +573,18 @@ export class PlayEngine {
const ss = p ? this.spanSound(p.id, p.piece) : null;
// Asked for here too: a hold far from where the prefetch looks (a seek) must not wait on nothing.
const got = p && ss ? this.bank.peek(this.bank.resolve(p.id, ss.media, ss.need, ss.ask).key) : 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);
+ const soundOk = !p || !ss || got === "failed" || (got && got !== "loading" && this.bank.hasRate(got as ClipSound, this.rate));
+ if (soundOk && !this.gated(this.t)) this.restart(this.t);
+ else if (!soundOk && got && got !== "loading") this.bank.atRate(got as ClipSound, this.rate);
}
let t = this.now();
+ if (this.playing && !this.waiting) {
+ const g = this.gated(t);
+ if (g) {
+ this.hold(g.at, g.why, g.id);
+ t = this.t;
+ }
+ }
if (this.playing && !this.waiting && t >= this.plan.total - 0.001) {
t = this.plan.total;
this.t = t;
@@ -771,6 +831,7 @@ export class PlayEngine {
decoded: this.bank.size, bytes: this.bank.bytes, decodedSeconds: this.bank.seconds, held: this.bank.held, 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,
+ waits: { ...this.measured.waits, holding: this.held ? { ...this.held, ms: Math.round(performance.now() - this.held.since) } : null },
};
}
}
diff --git a/umtool/components/projects/review/playEngine/postPreload.ts b/umtool/components/projects/review/playEngine/postPreload.ts
@@ -0,0 +1,243 @@
+// ---------------------------------------------------------------------------
+// POST ITEMS FETCHED AHEAD (operator, 4 Nov: "The rapid sections on play the
+// cut don't load fast enough such that most of it is cut out. Can we maybe
+// preload?"). A post item's player (PostItemPlayer.tsx) is mounted only while
+// its item is on screen, and everything it draws was asked for then: the card's
+// page (and its faces and avatars), the narration take, the attachments. A
+// `pace: fast` burst is items of 1-4 s back to back, so each was mostly over
+// before it had loaded.
+//
+// So Play hands this the items AHEAD of the playhead (PlayCut.tsx: ~20 s of
+// them, more when they are short) and each one's bytes are fetched here, the
+// nearest first, a few at a time:
+//
+// - the card's PAGE as text, its own requests (the cut's faces, the avatars,
+// a parent's screenshot: the route's `file=` / `font=` URLs) fetched too and
+// written into it as blob URLs -- the player draws it as `srcdoc`, so the
+// frame needs nothing from the network;
+// - every FILE (the take, the attachments, a video's words) as a Blob, handed
+// to the element as a blob URL (in memory: a seek never waits on a range).
+//
+// The player asks `docOf` / `urlOf` once per element, when it mounts (a src
+// never changes under a playing element); anything not here yet is fetched by
+// the element itself, as before. What is behind the playhead is let go (its
+// blob URLs revoked), and a file over MAX_FILE, or past the budget, is left to
+// the element. `itemState` is what Play's clock asks before it crosses into an
+// item (engine.ts `gate`): still fetching, it holds on the item before.
+// ---------------------------------------------------------------------------
+
+/** What one post item needs: its card pages (read, media, the join's) and its files. */
+export type PostAssets = { id: string; docs: string[]; files: string[] };
+export type PreloadState = "ready" | "loading" | "partial" | "none";
+
+type Asset = {
+ url: string;
+ kind: "doc" | "file";
+ state: "queued" | "loading" | "ready" | "failed" | "skipped";
+ /** The doc's html (its requests in it as blob URLs), or the file's blob URL. */
+ out: string | null;
+ bytes: number;
+ users: Set<string>;
+ prio: number;
+ ctrl: AbortController | null;
+ /** A doc's own requests (files), settled before the doc is. */
+ subs: string[];
+ settled: Promise<void>;
+ settle: () => void;
+};
+
+/** A file bigger than this is left to its element (a long screen recording): not held in memory. */
+const MAX_FILE = 64 * 1024 * 1024;
+/** Everything held at once. */
+const BUDGET = 384 * 1024 * 1024;
+/** Requests in flight at once: the rest of the page (the engine's clips, the chrome) keeps the other connections. */
+const CONCURRENCY = 4;
+/** The card page's own requests: the route's files and faces (post-item.mjs: avatars, a parent's shot, @font-face). */
+const SUB_RE = /\/api\/report\/post-item\?[^"'()\s<>\\]+/g;
+
+class PostPreloader {
+ private assets = new Map<string, Asset>();
+ private items = new Map<string, PostAssets>();
+ private active = 0;
+ private bytes = 0;
+ /** For a console and the e2e (play-preload.spec.ts): what was fetched ahead, and how it went. */
+ stats = { asked: 0, ready: 0, failed: 0, skipped: 0, released: 0 };
+
+ /**
+ * The items wanted now, nearest first; everything else is let go. `keep`:
+ * items whose bytes are kept but never fetched now (the one on screen, which
+ * its player is already loading, and the one before it, whose last frame a
+ * join opens on).
+ */
+ want(list: PostAssets[], keep: PostAssets[] = []) {
+ const ids = new Set([...list, ...keep].map((x) => x.id));
+ for (const id of [...this.items.keys()]) if (!ids.has(id)) this.release(id);
+ for (const a of this.assets.values()) a.prio = Infinity;
+ for (const it of keep) {
+ this.items.set(it.id, it);
+ for (const url of [...it.docs, ...it.files]) {
+ const a = this.assets.get(url);
+ if (a) {
+ a.users.add(it.id);
+ a.prio = -1;
+ for (const s of a.subs) this.assets.get(s)?.users.add(it.id);
+ }
+ }
+ }
+ list.forEach((it, k) => {
+ this.items.set(it.id, it);
+ for (const url of it.docs) this.ask(url, "doc", it.id, k);
+ for (const url of it.files) this.ask(url, "file", it.id, k);
+ });
+ this.pump();
+ }
+
+ /** The card page at `url`, ready to draw as srcdoc, or null. */
+ docOf(url: string): string | null {
+ const a = this.assets.get(url);
+ return a?.kind === "doc" && a.state === "ready" ? a.out : null;
+ }
+
+ /** The file at `url` as a blob URL when it is here, else `url` itself. */
+ urlOf(url: string): string {
+ const a = this.assets.get(url);
+ return a?.kind === "file" && a.state === "ready" && a.out ? a.out : url;
+ }
+
+ /** An item's bytes: all here, still coming, here but for some (failed, too big), or not asked for. */
+ itemState(id: string): PreloadState {
+ const it = this.items.get(id);
+ if (!it) return "none";
+ let partial = false;
+ const look = (url: string): boolean => {
+ const a = this.assets.get(url);
+ if (!a) {
+ partial = true;
+ return true;
+ }
+ if (a.state === "queued" || a.state === "loading") return false;
+ if (a.state !== "ready") partial = true;
+ return a.subs.every(look);
+ };
+ for (const url of [...it.docs, ...it.files]) if (!look(url)) return "loading";
+ return partial ? "partial" : "ready";
+ }
+
+ clear() {
+ for (const id of [...this.items.keys()]) this.release(id);
+ }
+
+ private ask(url: string, kind: Asset["kind"], user: string, prio: number) {
+ let a = this.assets.get(url);
+ if (!a) {
+ let settle = () => {};
+ const settled = new Promise<void>((r) => (settle = r));
+ a = { url, kind, state: "queued", out: null, bytes: 0, users: new Set(), prio, ctrl: null, subs: [], settled, settle };
+ this.assets.set(url, a);
+ this.stats.asked += 1;
+ }
+ a.users.add(user);
+ a.prio = Math.min(a.prio, prio);
+ for (const s of a.subs) {
+ const sub = this.assets.get(s);
+ if (sub) {
+ sub.users.add(user);
+ sub.prio = Math.min(sub.prio, prio);
+ }
+ }
+ }
+
+ private release(id: string) {
+ this.items.delete(id);
+ for (const a of [...this.assets.values()]) {
+ if (!a.users.delete(id) || a.users.size) continue;
+ a.ctrl?.abort();
+ if (a.kind === "file" && a.out) URL.revokeObjectURL(a.out);
+ this.bytes -= a.bytes;
+ this.assets.delete(a.url);
+ if (a.state === "queued" || a.state === "loading") a.settle();
+ this.stats.released += 1;
+ }
+ }
+
+ private pump() {
+ while (this.active < CONCURRENCY) {
+ let next: Asset | null = null;
+ for (const a of this.assets.values()) if (a.state === "queued" && a.prio !== Infinity && (!next || a.prio < next.prio)) next = a;
+ if (!next) return;
+ next.state = "loading";
+ this.active += 1;
+ const a = next;
+ void (a.kind === "doc" ? this.loadDoc(a) : this.loadFile(a)).finally(() => {
+ this.active -= 1;
+ this.pump();
+ });
+ }
+ }
+
+ private done(a: Asset, state: "ready" | "failed" | "skipped") {
+ if (this.assets.get(a.url) !== a) return;
+ a.state = state;
+ this.stats[state] += 1;
+ a.settle();
+ }
+
+ private async loadFile(a: Asset) {
+ a.ctrl = new AbortController();
+ try {
+ const r = await fetch(a.url, { signal: a.ctrl.signal });
+ const len = Number(r.headers.get("content-length") ?? 0);
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ if (len > MAX_FILE || this.bytes + len > BUDGET) {
+ a.ctrl.abort();
+ this.done(a, "skipped");
+ return;
+ }
+ const blob = await r.blob();
+ if (this.assets.get(a.url) !== a) return;
+ a.bytes = blob.size;
+ this.bytes += blob.size;
+ a.out = URL.createObjectURL(blob);
+ this.done(a, "ready");
+ } catch {
+ this.done(a, "failed");
+ } finally {
+ a.ctrl = null;
+ }
+ }
+
+ private async loadDoc(a: Asset) {
+ a.ctrl = new AbortController();
+ let html: string;
+ try {
+ const r = await fetch(a.url, { signal: a.ctrl.signal });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ html = await r.text();
+ } catch {
+ a.ctrl = null;
+ this.done(a, "failed");
+ return;
+ }
+ a.ctrl = null;
+ if (this.assets.get(a.url) !== a) return;
+ // Its own requests, as written in it (an attribute's `&`, a style's raw `&`), each fetched as a file.
+ const found = [...new Set(html.match(SUB_RE) ?? [])].filter((m) => /[?&](amp;)?(file|font)=/.test(m));
+ const real = new Map(found.map((m) => [m, m.replace(/&/g, "&")]));
+ a.subs = [...new Set(real.values())];
+ for (const s of a.subs) for (const u of a.users) this.ask(s, "file", u, a.prio);
+ // The doc's slot is free while its requests come (they queue at its priority, ahead of farther items).
+ void Promise.all(a.subs.map((s) => this.assets.get(s)?.settled)).then(() => {
+ if (this.assets.get(a.url) !== a) return;
+ let out = html;
+ for (const [m, u] of real) {
+ const b = this.urlOf(u);
+ if (b !== u) out = out.split(m).join(b);
+ }
+ a.out = out;
+ this.done(a, "ready");
+ });
+ }
+}
+
+/** One for the page: Play fills it, and every post item's player reads it (the bench's, which nothing fills, too). */
+export const postPreload = new PostPreloader();
diff --git a/umtool/components/projects/review/playEngine/usePlayEngine.ts b/umtool/components/projects/review/playEngine/usePlayEngine.ts
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
-import { PlayEngine, type EngineEntry, type EngineInfo, type EngineUi, type MediaRef, type Plan } from "./engine";
+import { PlayEngine, type EngineEntry, type EngineInfo, type EngineUi, type ItemGate, type MediaRef, 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`,
@@ -21,9 +21,11 @@ type Args = {
style: string;
/** The plan's edges are the manifest's until the render's are measured (useRenderCuts `measuring`). */
edgesPending?: boolean;
+ /** THE GATE (engine.ts): an item not ready yet holds the clock -- Play's post items. */
+ gate?: ItemGate | null;
};
-export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style, edgesPending = false }: Args) {
+export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg, style, edgesPending = false, gate = null }: 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);
@@ -31,6 +33,8 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg,
const eng = useRef<PlayEngine | null>(null);
const fns = useRef({ srcOf, audioOf });
fns.current = { srcOf, audioOf };
+ const gateRef = useRef(gate);
+ gateRef.current = gate;
const latest = useRef({ plan, entries, edgesPending });
latest.current = { plan, entries, edgesPending };
// Elements attach before the engine exists (refs before effects): held here and handed over.
@@ -53,6 +57,7 @@ export function usePlayEngine({ plan, entries, srcOf, audioOf, blurRendered, bg,
onInfo: setInfo,
picture: pick,
});
+ e.gate = (id, next) => gateRef.current?.(id, next) ?? "ready";
e.attachCanvas(els.current.canvas);
els.current.slots.forEach((el, k) => e.attachSlot(k, el));
e.setPlan(latest.current.plan, latest.current.entries, { edgesPending: latest.current.edgesPending });
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -597,6 +597,18 @@ stamps, the finale, a note's anchor — is that context's time mapped through th
estimate's clock) is seeked by the source second playing, so a stamp lands on its word. A clip whose sound is not
decoded yet holds the clock at its first second (**loading…**), nothing skipped.
+**Post items are fetched ahead, and never cut short by loading** (operator, 4 Nov: "the rapid sections ... don't load
+fast enough"). While one item plays, the post items after it — those starting within ~20 s of its end, at least three,
+at most 24, so a `pace: "fast"` burst has many ahead — are fetched a few requests at a time, nearest first
+(`playEngine/postPreload.ts`): each card's page with its faces, avatars and a parent's screenshot written into it, the
+picked take, every attachment the plan shows (and a video's words, the panel's, what a join opens on), held as blobs
+in memory (a file over 64 MB, or past 384 MB in all, is left to its element) and let go once behind the playhead. The
+player draws from them as it comes on screen, so the item is ready at its first frame; a seek or opening Play at a
+place fetches from there. An item not ready when its time comes HOLDS the clock, like a buffer stall: on the item
+before's last frame while it is still being fetched, then at its first second until its card is drawn and its voice
+and first attachment can play (at most 15 s) — **loading…** over the picture — and then it plays in full. Every hold
+is counted (`window.__umtoolPlayEngine.stats.waits`) and logged in the console (`[play] held 412 ms on pp-3 …`).
+
**The picture follows the clock**: by WebCodecs where the browser has it — each clip decoded from its window a few
frames ahead, the frame due at the audio clock drawn, a crossfade a real dissolve (a `fadeblack` join dips through
the ground) — else on two `<video>` elements slaved to the clock (requestVideoFrameCallback, the speed nudged past a