Archilyzer · Source

archilyzer

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

commit 1036143aa936b2be6161b524037d9bca7137c7e4
parent 9e50701314684bfc73b017cfe8838d6bda20f602
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 00:01:08 -0500

Merge main (run-queue, play-preload) into lane/take-items: the fixture builder makes both the take-items and the play-preload fixtures

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

Diffstat:
Mumtool/components/projects/review/PlayCut.tsx | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/review/PostItemPlayer.tsx | 147++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/components/projects/review/playEngine/engine.ts | 71++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aumtool/components/projects/review/playEngine/postPreload.ts | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/playEngine/usePlayEngine.ts | 9+++++++--
Mumtool/docs/knobs.md | 14++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/play-preload-fixture.mjs | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/play-preload.spec.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/post-narration.spec.ts | 2++
10 files changed, 779 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"; // --------------------------------------------------------------------------- @@ -242,6 +243,17 @@ 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; +/** 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; @@ -397,8 +409,37 @@ 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), its player is ready the frame its card is drawn; the clock holds on the item before + // while it is still fetching. `postReady`: what the MOUNTED player said (one at a time; "gone" as it unmounts). + // `started`: the item on screen once it has played -- a player mounted again under it (the deck composed) is not + // waited for (the clock runs on, as it always did). + const entryOfRef = useRef(entryOf); + entryOfRef.current = entryOf; + const postReady = useRef<string | null>(null); + const started = 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"; + if (next) return postPreload.itemState(id) === "loading" ? "fetching" : "ready"; + if (started.current === id) return "ready"; + if (postReady.current !== id) return "wait"; + started.current = id; + return "ready"; + }, []); + const onPostReady = useCallback((id: string, state: "ready" | "gone") => { + if (state !== "gone") postReady.current = id; + else if (postReady.current === id) postReady.current = null; + }, []); 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; @@ -833,6 +874,45 @@ 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(); + }, [ui.cur, plan]); + // Another item on screen: the one before is no longer "started" (a revisit waits as the first visit did). + const curId = plan.items[ui.cur]?.id ?? null; + useEffect(() => { + if (started.current !== curId) started.current = null; + }, [curId]); + useEffect(() => { + // Not while the deck composes: its pages would be fetched at the plain frame's size (the deck's box is + // another URL), and the requests would queue ahead of the composition itself. + if (composeState === "composing") return; + 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, composeState]); + 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; @@ -862,6 +942,7 @@ export default function PlayCut({ uncensored={uncensored} scene={postNow.entry.postScene ?? null} clock={postNow.entry.postClock ?? null} + onReady={onPostReady} progress={postNow.entry.postProgress ?? null} joinFrom={(() => { // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended. @@ -1056,6 +1137,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 { measureProgressPlace, mountProgress, progressAt, progressCss, progressHeight, progressOpacityAt, setProgressState } from "umtool-report-to-video/post-progress"; import { SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, slamBarOf, setSlamState, slamCss, slamHits, slamLayout, slamListAt, slamPlan, slamShakeAt, slamSize, slamVars, @@ -179,6 +180,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 -- @@ -339,6 +404,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(() => { @@ -393,7 +459,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)} @@ -407,7 +473,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 }} @@ -440,6 +506,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) => { @@ -460,9 +527,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> ); @@ -473,13 +540,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 @@ -496,8 +564,14 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A type ClockPlan = { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean }; 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, progress = null, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, progress = null, onReady, }: { + /** + * THIS player's readiness, for Play's clock (engine.ts `gate`): "ready" once its card is drawn and its voice and + * first attachment can play (or failed: nothing to wait for) -- fetched ahead (postPreload.ts), as soon as its + * card is drawn, the rest being here; "gone" as it unmounts. + */ + onReady?: (id: string, state: "ready" | "gone") => void; project: string; take?: string | null; entry: Record<string, unknown> & { id: string }; @@ -558,10 +632,19 @@ 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(); + // Everything it opens on already here (fetched ahead), as it mounts: the card's page, the voice, the first step. + const [ahead] = useState(() => { + const here = (u: string) => postPreload.urlOf(u) !== u; + if (postPreload.docOf(pageUrl("read")) === null) return false; + const take = plan.narration ? (pickedTake(entry) as { file?: string } | null) : null; + if (take?.file && !here(takeFileUrl(project, take.file))) return false; + return (plan.steps[0]?.items ?? []).every((m) => here(postFileUrl(project, String(m.src)))); + }); 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. @@ -578,7 +661,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; @@ -589,7 +672,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 ---- @@ -975,6 +1058,38 @@ export default function PostItemPlayer({ const at = clockAt && jc?.move ? { x: clockAt.x + jc.move.dx * left, y: clockAt.y + jc.move.dy * left } : clockAt; setClockState(clockSt && at && s < until ? { ...at, st: clockSt, ...(jc?.fadeIn ? { opacity: Math.max(0, s / joinSecs) } : {}) } : null, doc); }, [clockSt, clockAt, s, layout.mode, plan.steps, joinClock, joinSecs]); + // ---- READY (Play's clock waits for it): the card measured, the voice and the first attachment able to play ---- + const onReadyRef = useRef(onReady); + onReadyRef.current = onReady; + useEffect(() => { + if (!onReadyRef.current) return; + const mine = entry.id; + // Looked at every frame: an item fetched ahead is ready the frame its card is drawn. + let raf = 0; + const look = () => { + raf = requestAnimationFrame(look); + const node = wrap.current; + const doc = readFrame.current?.contentDocument; + if (!node || doc?.body?.getAttribute("data-post-ready") !== "1") return; + // Fetched ahead, the rest is here (blobs); else the voice at HAVE_FUTURE_DATA and the first attachment's + // frame (an error is nothing to wait for). + if (!ahead) { + const a = voice.current; + 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; + } + cancelAnimationFrame(raf); + raf = 0; + onReadyRef.current?.(mine, "ready"); + }; + raf = requestAnimationFrame(look); + return () => { + if (raf) cancelAnimationFrame(raf); + onReadyRef.current?.(mine, "gone"); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [entry.id]); // The bar's fill: the read's real seconds (a part read faster moves it faster), gone in a stack card's media phase. const progFrac = progress ? progressAt(progress, s) : null; useEffect(() => { @@ -1028,7 +1143,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" }}> @@ -1036,7 +1151,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" }} @@ -1047,7 +1162,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={{ @@ -1061,7 +1176,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,244 @@ +// --------------------------------------------------------------------------- +// 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 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); + }); + // Let go after: a file the items wanted now share with one let go (a repeated attachment) is kept, not fetched again. + for (const id of [...this.items.keys()]) if (!ids.has(id)) this.release(id); + 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 `&amp;`, 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(/&amp;/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,20 @@ 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 (once the deck is composed: its box is the pages' size) 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 (fetched ahead: until its card is drawn, a frame or two; at most 15 s) — **loading…** +over the picture — and then it plays in full; once it has played, a player mounted again under it (the deck composed) +is not waited for. 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 diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -56,6 +56,7 @@ import { makeIntakeFixture } from "./intake-fixture.mjs"; import { makePostItemsFixture } from "./post-items-fixture.mjs"; import { makePostNarrationFixture } from "./post-narration-fixture.mjs"; import { makeTakeItemsFixture } from "./take-items-fixture.mjs"; +import { makePlayPreloadFixture } from "./play-preload-fixture.mjs"; import { makePostComboFixture } from "./post-combo-fixture.mjs"; import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs"; @@ -1918,6 +1919,8 @@ makePostItemsFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: makePostNarrationFixture({ reports, deckManifest }); // A take's own items (takeImport.mjs, takeScope.mjs): a post imported from another project into a draft take, edited in the take only (take-items.spec.ts). makeTakeItemsFixture({ reports, deckManifest }); +// A fast burst of narrated posts (Play's prefetch and its gate: play-preload.spec.ts). +makePlayPreloadFixture({ reports, deckManifest }); // The combo counter (report-to-video/post-combo.mjs): one GIF answering three people (post-combo.spec.ts). makePostComboFixture({ reports, channels: CHANNELS, deckManifest }); // Media scenes and the band censor (post-media-scene.mjs, post-censor.mjs): one picture answered three times in a row (media-scenes.spec.ts). diff --git a/umtool/e2e/fixtures/play-preload-fixture.mjs b/umtool/e2e/fixtures/play-preload-fixture.mjs @@ -0,0 +1,82 @@ +// A FAST BURST OF POST ITEMS (operator, 4 Nov: "The rapid sections on play the +// cut don't load fast enough such that most of it is cut out"): Play's +// prefetch and its gate (PlayCut.tsx, playEngine/postPreload.ts, engine.ts +// `gate`), played by play-preload.spec.ts with every post-item request slowed. +// +// play-preload-fixture pp-1 … pp-10 ten narrated posts at `pace: "fast"`, the +// clock on: each read by a take of +// 0.6-1.3 s (a tone), so each item is +// ~1.3-2 s, back to back; pp-3, pp-6 and +// pp-9 carry a picture, pp-5 a 1.2 s video; +// pp-10 a stinger an hour EARLIER (the +// clock rewinds). The deck on. Read only. +// +// Synthetic, like every fixture. +import { mkdirSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +const ff = (args) => { + const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]); + if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`); +}; + +/** The burst: id, its take's seconds, its attachment. */ +export const PLAY_PRELOAD_ITEMS = [ + ["pp-1", 0.8, null], + ["pp-2", 0.6, null], + ["pp-3", 1.0, "image"], + ["pp-4", 0.7, null], + ["pp-5", 1.1, "video"], + ["pp-6", 0.9, "image"], + ["pp-7", 0.6, null], + ["pp-8", 1.3, null], + ["pp-9", 0.8, "image"], + ["pp-10", 0.9, null], +]; + +/** @param {{ reports: string, deckManifest: Function }} o */ +export function makePlayPreloadFixture({ reports, deckManifest }) { + const name = "play-preload-fixture"; + const dir = path.join(reports, name); + const chan = "burstchan-x"; + const colours = ["red", "green", "blue", "yellow", "purple", "orange", "cyan", "white", "pink", "gray"]; + const timeline = PLAY_PRELOAD_ITEMS.map(([id, secs, kind], k) => { + const n = id.slice(3); + const media = path.join(dir, "posts-media", chan, n); + mkdirSync(media, { recursive: true }); + const takes = path.join(dir, "narration", "posts", n); + mkdirSync(takes, { recursive: true }); + ff(["-f", "lavfi", "-i", `sine=frequency=${300 + 40 * k}:sample_rate=48000:duration=${secs}`, "-ac", "1", "-c:a", "pcm_s16le", path.join(takes, "take-1.orpheus-zac.wav")]); + const att = []; + if (kind === "image") { + ff(["-f", "lavfi", "-i", `color=c=${colours[k]}:size=320x180`, "-frames:v", "1", path.join(media, `${n}_1.png`)]); + att.push({ src: `posts-media/${chan}/${n}/${n}_1.png`, kind: "image", width: 320, height: 180 }); + } else if (kind === "video") { + ff([ + "-f", "lavfi", "-i", "testsrc=size=320x180:rate=30:duration=1.2", + "-f", "lavfi", "-i", "sine=frequency=880:duration=1.2", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", "-shortest", path.join(media, `${n}_1.mp4`), + ]); + att.push({ src: `posts-media/${chan}/${n}/${n}_1.mp4`, kind: "video", seconds: 1.2, width: 320, height: 180, audio: true }); + } + const text = `Burst post ${n}: you want to die? ${"again ".repeat(k % 3)}`.trim(); + // A minute apart, the stinger an hour back (the clock rewinds). + const date = new Date(Date.UTC(2026, 10, 4, 9, id === "pp-10" ? 0 : 10 + k)).toISOString(); + return { + type: "post", id, post: `${chan}/${n}`, platform: "x", author: "Burst Subject", handle: "burstsubject", + date, text, url: `https://x.com/burstsubject/status/${n}`, engagement: { likes: k }, subjects: ["burstsubject"], + ...(att.length ? { media: att } : {}), + narration: { + script: text, pace: "fast", + takes: [{ file: `narration/posts/${n}/take-1.orpheus-zac.wav`, engine: "orpheus", voice: "zac", seconds: secs, script: text, at: "2026-11-04T00:00:00.000Z" }], + pick: 0, + }, + }; + }); + const m = deckManifest(name, "The Play Preload Fixture", timeline); + m.provenance = { ...m.provenance, channelSlug: chan }; + m.render = { ...m.render, posts: { ...(m.render.posts ?? {}), clock: { on: true } } }; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { dir }; +} diff --git a/umtool/e2e/play-preload.spec.ts b/umtool/e2e/play-preload.spec.ts @@ -0,0 +1,140 @@ +import { test, expect, type Page } from "@playwright/test"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// A FAST BURST, PLAYED IN FULL ON A SLOW NETWORK (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?"). Fixture: e2e/fixtures/play-preload-fixture.mjs -- +// ten narrated posts at `pace: "fast"`, ~1.3-2 s each, the clock on, three with +// a picture and one with a video. +// +// Every post item's request (the card's page, its faces, the takes, the +// attachments) is held 300-800 ms before it goes on. Play fetches the items +// ahead (playEngine/postPreload.ts) and holds its clock on an item that is not +// ready (engine.ts `gate`), so each item is played in full: its card drawn +// for at least 90% of its seconds on the cut's clock while the clock runs, and +// its voice heard. What it waited is printed (and in the console: "[play] held"). +// --------------------------------------------------------------------------- + +const PROJECT = "reports/play-preload-fixture"; +const IDS = ["pp-1", "pp-2", "pp-3", "pp-4", "pp-5", "pp-6", "pp-7", "pp-8", "pp-9", "pp-10"]; + +test.use({ launchOptions: { args: ["--autoplay-policy=no-user-gesture-required"] } }); +test.beforeEach(() => test.setTimeout(180_000)); + +const root = (page: Page) => page.locator("[data-play-cut]"); + +/** 300-800 ms, the same for a URL every run. */ +const delayOf = (url: string) => { + let h = 2166136261; + for (let i = 0; i < url.length; i += 1) h = Math.imul(h ^ url.charCodeAt(i), 16777619) >>> 0; + return 300 + (h % 501); +}; + +async function throttle(page: Page) { + const seen = { n: 0 }; + await page.route(/\/api\/report\/(post-item|file)\?/, async (route) => { + if (route.request().method() !== "GET") return route.continue(); + seen.n += 1; + await new Promise((r) => setTimeout(r, delayOf(route.request().url()))); + await route.continue().catch(() => {}); + }); + return seen; +} + +/** Every animation frame from now: the post item on screen, its second, its card drawn, its voice, the clock's state. */ +const startSampling = (page: Page) => + page.evaluate(() => { + const w = window as unknown as { __pp: unknown[]; __ppStop?: boolean }; + w.__pp = []; + w.__ppStop = false; + const loop = () => { + const cut = document.querySelector("[data-play-cut]"); + const p = document.querySelector("[data-post-play]"); + if (cut && p) { + const id = p.getAttribute("data-post-play"); + const f = p.querySelector('iframe[data-post-card-frame="read"]') as HTMLIFrameElement | null; + const body = f?.contentDocument?.body; + const a = p.querySelector("audio[data-post-narration-audio]") as HTMLAudioElement | null; + w.__pp.push({ + id, + s: Number(p.getAttribute("data-post-s")), + card: !!body && body.getAttribute("data-post-ready") === "1" && body.getAttribute("data-post-item") === id && f!.style.visibility !== "hidden", + voice: !!a && !a.paused && a.currentTime > 0.02, + state: cut.getAttribute("data-play-state"), + }); + } + if (!w.__ppStop) requestAnimationFrame(loop); + }; + requestAnimationFrame(loop); + }); + +type Sample = { id: string; s: number; card: boolean; voice: boolean; state: string }; +type Report = { id: string; seconds: number; covered: number; voice: boolean }; + +/** Per item: the share of its seconds (0.1 s at a time, as the page shows it: from-start to to-start) drawn while the clock ran, and its voice. */ +async function coverage(page: Page, ids: string[]): Promise<{ items: Report[]; waits: { count: number; ms: number; last: unknown[] } }> { + const { samples, items, waits } = await page.evaluate(() => { + const w = window as unknown as { __pp: Sample[]; __ppStop?: boolean; __umtoolPlayEngine?: { plan: { items: { id: string; start: number; from: number; to: number }[] }; stats: { waits: { count: number; ms: number; last: unknown[] } } } }; + w.__ppStop = true; + const e = w.__umtoolPlayEngine!; + // (No `waits` before the gate existed: none counted.) + return { samples: w.__pp, items: e.plan.items.map((x) => ({ id: x.id, start: x.start, from: x.from, to: x.to })), waits: e.stats.waits ?? { count: 0, ms: 0, last: [] } }; + }); + const out: Report[] = []; + for (const id of ids) { + const it = items.find((x) => x.id === id)!; + const s0 = it.from - it.start; + const n = Math.max(1, Math.ceil((it.to - it.from) * 10 - 1e-6)); + const lit = new Set<number>(); + let voice = false; + for (const x of samples) { + if (x.id !== id) continue; + voice ||= x.voice; + if (!x.card || x.state !== "playing") continue; + const k = Math.floor((x.s - s0) * 10 + 1e-6); + if (k >= 0 && k < n) lit.add(k); + } + out.push({ id, seconds: Math.round((it.to - it.from) * 100) / 100, covered: Math.round((lit.size / n) * 100) / 100, voice }); + } + return { items: out, waits }; +} + +async function playToEnd(page: Page) { + await startSampling(page); + await page.locator("[data-play-toggle]").click(); + await expect(root(page)).toHaveAttribute("data-play-state", "ended", { timeout: 120_000 }); +} + +function judge(label: string, r: Awaited<ReturnType<typeof coverage>>, requests: number) { + console.log(`play-preload ${label}: ${requests} slowed requests; held ${r.waits.count} time(s), ${(r.waits.ms / 1000).toFixed(2)} s in all`); + for (const x of r.items) console.log(` ${x.id.padEnd(6)} ${x.seconds.toFixed(2)} s card drawn ${(x.covered * 100).toFixed(0)}% voice ${x.voice ? "heard" : "NOT HEARD"}`); + for (const x of r.items) { + expect.soft(x.covered, `${x.id}: its card drawn for at least 90% of its ${x.seconds} s`).toBeGreaterThanOrEqual(0.9); + expect.soft(x.voice, `${x.id}: its narration started`).toBe(true); + } +} + +test("THE BURST, SLOWED: every item of a fast run plays in full -- its card drawn for >= 90% of its seconds, its voice heard", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const seen = await throttle(page); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "pp-1" })); + await expect(root(page)).toHaveAttribute("data-play-item", "pp-1"); + await expect(root(page)).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 }); + await expect(page.locator('[data-post-play="pp-1"]')).toHaveCount(1); + await playToEnd(page); + judge("from the top", await coverage(page, IDS), seen.n); +}); + +test("A JUMP INTO THE BURST: the items after a seek are fetched from there, and play in full", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const seen = await throttle(page); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "pp-1" })); + await expect(root(page)).toHaveAttribute("data-play-item", "pp-1"); + await expect(root(page)).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 }); + // N: the next item, five times -- a seek to pp-6. + for (let k = 0; k < 5; k += 1) await page.keyboard.press("n"); + await expect(root(page)).toHaveAttribute("data-play-item", "pp-6"); + await playToEnd(page); + judge("after a jump to pp-6", await coverage(page, IDS.slice(5)), seen.n); +}); diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -123,6 +123,8 @@ test("THE READ's RATE in Play: render.postNarration.rate 1.25 plays the voice at await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); await expect(root(page)).toHaveAttribute("data-play-item", "p-11"); + // The deck composed first: its frame mounts the player afresh, and a sample across that would read a player gone. + await expect(root(page)).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 }); const player = page.locator('[data-post-play="p-11"]'); await page.locator("[data-play-toggle]").click(); await expect(player).toHaveAttribute("data-post-narration-playing", "1", { timeout: 15_000 });