"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { POST_ENTER_FADE, POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; import { applyJoinState, endMediaOf, joinClockOf, joinEase, joinFrameAt } from "umtool-report-to-video/post-join"; import { applyVisitState } from "umtool-report-to-video/post-link-visit"; import { applyMapState, mapHtml, mapPlace, mapSize } from "umtool-report-to-video/post-branch-map"; import { dryGainAt, mixPhaseAt, wetGainAt } from "umtool-report-to-video/post-narration"; import { READ_REFUSED_REASON, itemReadRefusals, playableTake } from "umtool-report-to-video/post-thread"; import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow"; import { scrollAt, showOpacityAt } from "umtool-report-to-video/post-thread"; import { blurCqw, blurOf, labelBoxOf, pixelGrid } from "umtool-report-to-video/post-censor"; 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, } from "umtool-report-to-video/post-slam"; import { TRAILER_AUDIO, trailerHitSamples } from "umtool-report-to-video/trailer-hits"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- // A POST ITEM PLAYED (report-to-video/post-item.mjs; knobs.md, "Play the cut"): // the card drawn by the build's own page (/api/report/post-item, the HTML the // render screenshots) at the footage box's size and scaled into it, and its // attachments laid over the card's slot where the render lays them // (postLayout, stepBoxes) on the item's plan (postItemPlan): the first one's // first frame while the words are read, then each in turn -- a video playing // with its sound, a GIF looped, an image held (pushed in on when it asks). // The cut's clock is Play's own; each element follows it, re-seeked when it // drifts -- and plays at its speed (`speed`, Play's 0.75-3x: playbackRate, // the pitch kept), so a fast-forward SPEEDS the item up rather than seeking // it forward every few frames. The voice plays at that times the read's own // `rate` (post-narration.mjs). A video's words show at the slot's foot. // // A WORD ZOOM (word-zoom.mjs) plays live on the same curve as the render's: the // card's contents scaled toward the word's box (measured in the card page: its // `data-w` spans) inside the card, which clips them, its highlight fading in // under the word -- the card page's own elements transformed, nothing redrawn. // // A CAPTION (post-caption.mjs) plays live on the build's own markup: the chips // mounted in the card page (its CSS, in the page's palette), placed by the same // rule (placeCaption, the words read while it is up avoided), faded and slid in // on the same curve, and tracking the phrase as the card pans (measured each tick). // // THE CLOCK (post-clock.mjs) plays live from `clock` (clockPlan: the caller has // the item before it): the build's chip mounted in the card page, placed by the // same rule, set each tick to clockStateAt -- the run, the badge, the rewind. // // READ-FOLLOW (read-follow.mjs) plays live on the plan's `follow`: the card // page carries the read's blocks and its flow; the pan's path is worked out // from the page's geometry once it is drawn, and each tick sets the state at // the item's second (followStateAt -- the build's frames are the same states). // A THREADED card (post-thread.mjs) is the same: its tiles' sizes and // strengths are part of the state (the page's slots and tiles set by it). // --------------------------------------------------------------------------- type Rect = { x: number; y: number; width: number; height: number }; /** A progress bar's plan (post-progress.mjs progressPlan): the read's span on the item's clock, the parts' ticks. */ export type ProgressPlan = { from: number; to: number; ticks: number[]; until: number; mode: string }; /** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */ /** A caption of the item, placed in its card page: its span, its place, the phrase's box and lines when placed. */ type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: NonNullable>; base: Rect; lines: Rect[] }; /** A slam of the item, placed in its card page: its plan (span, units, its fx), each unit's centre, the words' box when placed. */ type LiveSlam = { i: number; span: { t0: number; t2: number; t3: number; landings: number[] }; fx: Record & { fromScale: number; volume: number }; scope: string | null; from: number; to: number; centers: Array<{ x: number; y: number }>; bar: { cx: number; cy: number } | null; base: Rect | null; where: string }; type LiveZoom = { i: number; span: ReturnType; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect }; /** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */ function applyZoom(doc: Document, z: LiveZoom | null, zf: number, hl: number, boxes: Map) { const card = doc.querySelector("[data-post-card]"); if (!card) return; const kids = Array.from(card.children) as HTMLElement[]; if (!z || zf <= 1.0005) { for (const k of kids) if (k.style.transform) k.style.transform = ""; } else { const win = zoomWindow(z.region, z.word, z.span.scale, zf); for (const k of kids) { const c = boxes.get(k); if (!c) continue; // Window point P is drawn at R + (P - W)·z: a child's corner C moves by R - z·W + (z - 1)·C, scaled about it. const tx = z.region.x - zf * win.x + (zf - 1) * c.x; const ty = z.region.y - zf * win.y + (zf - 1) * c.y; k.style.transformOrigin = "0 0"; k.style.transform = `translate(${tx}px, ${ty}px) scale(${zf})`; } } doc.querySelectorAll("[data-w-live-hl]").forEach((el) => { (el as HTMLElement).style.background = ""; (el as HTMLElement).style.boxShadow = ""; el.removeAttribute("data-w-live-hl"); }); if (z && z.color && hl > 0) { const [r, g, b] = [1, 3, 5].map((o) => parseInt((z.color!.length === 4 ? z.color!.replace(/^#(.)(.)(.)$/, "#$1$1$2$2$3$3") : z.color!).slice(o, o + 2), 16)); for (let i = z.from; i <= z.to; i += 1) { const el = doc.querySelector(`[data-w="${z.scope}:${i}"]`) as HTMLElement | null; if (!el) continue; el.setAttribute("data-w-live-hl", ""); el.style.background = `rgba(${r}, ${g}, ${b}, ${WORD_ZOOM_HIGHLIGHT_ALPHA * hl})`; el.style.boxShadow = `inset 0 -0.12em 0 rgba(${r}, ${g}, ${b}, ${hl})`; el.style.borderRadius = "0.16em"; } } } /** A narrated item's mix on its clock (post-narration.mjs narrationSchedule). */ export type NarrationSchedule = { at: number; seconds: number; takeSeconds?: number; rate?: number; voiceEnd: number; rampEnd: number; wet: number; lowpassHz: number; duck: boolean; attach?: string; lufs?: number }; /** The plan's read-follow (read-follow.mjs followSchedule). */ export type FollowPlan = { join?: { seconds: number }; /** PICTURE-ONLY context posts' beats before the read (post-thread.mjs pictureBeats). */ beats?: Array<{ scope: string; t0: number; t1: number }>; dim: number; ease: number; readEnd: number; source: string; blocks: Array<{ k: number; scope: string; from: number | null; to: number | null; part: number | null; start: number | null; end: number | null }>; /** A threaded card (post-thread.mjs threadSchedule): each tile's size and strength on the item's clock. */ thread?: { shrink: number; dim: number; seconds: number; pan: number; tiles: Array<{ scope: string; mode: string; read: boolean; from: number[]; to: number[]; t0: number; t1: number }>; }; }; /** A context post's attachment over the slot (post-thread.mjs panelSchedule). */ export type PanelShow = { scope: string; media: Array & { src: string; kind: string; width?: number; height?: number }>; t0: number; t1: number; scroll?: number[][] }; export type PostPlan = { panel?: { fade: number; shows: PanelShow[] }; /** PICTURE-ONLY posts (post-picture.mjs): each picture drawn in its own card (Play: the card's page plays it). */ pics?: Array<{ scope: string; media: PanelShow["media"]; sound?: { t0: number; t1: number } }>; /** Its own attachments come in at this item second, with his own post (post-item.mjs ownMediaEnterAt). */ enter?: number; reading: number; total: number; held: number; narration?: NarrationSchedule; follow?: FollowPlan; steps: Array<{ kind: string; at: number; seconds: number; srcFrom?: number; srcTo?: number; loop: boolean; sound: boolean; items: Array & { i: number; src: string; kind: string; crop?: number[]; push?: boolean; words?: string }>; }>; }; type Box = { width: number; height: number }; type Cue = { start: number; end: number; text: string }; const pct = (n: number, of: number) => `${(n / of) * 100}%`; /** How far a playing element may drift from the cut's clock before it is re-seeked (times the speed, above 1x). */ const DRIFT = 0.3; /** An element played at `rate`, its pitch kept (the bench's and Play's clips do the same). */ function setRate(el: HTMLMediaElement, rate: number) { const want = Number.isFinite(rate) && rate > 0 ? rate : 1; const m = el as HTMLMediaElement & { preservesPitch?: boolean; mozPreservesPitch?: boolean; webkitPreservesPitch?: boolean }; if (m.preservesPitch !== true) { m.preservesPitch = true; m.mozPreservesPitch = true; m.webkitPreservesPitch = true; } // The load algorithm resets playbackRate to defaultPlaybackRate: set both (ClipBench's lesson). if (Math.abs(el.defaultPlaybackRate - want) > 1e-3) el.defaultPlaybackRate = want; if (Math.abs(el.playbackRate - want) > 1e-3) el.playbackRate = want; } export function postFileUrl(project: string, rel: string) { return `/api/report/post-item?project=${encodeURIComponent(project)}&file=${encodeURIComponent(rel)}`; } /** A narration take, a file of the project (the "use a file" route). */ export function takeFileUrl(project: string, rel: string) { return `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`; } /** * WHAT THE CARD CENSORS, kind by kind (present mode's toggles, lib/report/present.mjs): the redacted names, the * slurs masked, the private authors blurred, the censored pictures. None given: Play's own `published`/`uncensored`. */ export type CardView = { names: boolean; slurs: boolean; authors: boolean; pictures: boolean }; type PageOpts = { project: string; id: string; box: Box; phase: "read" | "media"; take?: string | null; cardKey?: string | null; published?: boolean; uncensored?: boolean; view?: CardView | null }; /** A card view as the post-item route's query: published for names or slurs, and what is turned off. */ function viewQuery(v: CardView) { const pub = v.names || v.slurs; return `${pub ? `&published=1${v.slurs ? "" : "&uncensored=1"}${v.names ? "" : "&redact=0"}` : ""}${v.authors ? "" : "&authors=0"}${v.pictures ? "" : "&blur=0"}`; } /** 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, view = null }: PageOpts) { const censor = view ? viewQuery(view) : published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""; 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)}` : ""}${censor}`; } /** * 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, view = null, joinFrom = null }: { project: string; take?: string | null; entry: Record & { id: string }; plan: PostPlan; box: Box; published?: boolean; uncensored?: boolean; view?: CardView | null; joinFrom?: { entry: Record & { id: string }; plan: PostPlan } | null; }): PostAssets { const page = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored, view }); 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 ? (playableTake(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)); for (const pc of plan.pics ?? []) for (const m of pc.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()); 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()); 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 -- // dry, and wet (a low-pass at lowpassHz, twice, as the render's) -- whose // gains follow the item's clock: wet at `wet` and dry silent under the read, // a linear ramp back over `ramp`, then clean. One context for the page; an // element is wired once (createMediaElementSource takes it for good). // --------------------------------------------------------------------------- let audioCtx: AudioContext | null = null; const wired = new WeakMap(); function mixGraph(el: HTMLMediaElement, lowpassHz: number) { const had = wired.get(el); if (had) { for (const f of had.lp) f.frequency.value = lowpassHz; return had; } if (typeof window === "undefined" || typeof window.AudioContext === "undefined") return null; audioCtx ??= new window.AudioContext(); const ctx = audioCtx; try { const src = ctx.createMediaElementSource(el); const dry = ctx.createGain(); const wet = ctx.createGain(); const lp = [ctx.createBiquadFilter(), ctx.createBiquadFilter()]; for (const f of lp) { f.type = "lowpass"; f.frequency.value = lowpassHz; } src.connect(dry).connect(ctx.destination); src.connect(lp[0]).connect(lp[1]).connect(wet).connect(ctx.destination); const g = { wet, dry, lp }; wired.set(el, g); return g; } catch { return null; } } // --------------------------------------------------------------------------- // A SLAM's HITS, LIVE (post-slam.mjs, trailer-hits.mjs): each hit's layers made // by the build's own formulas (trailerHitSamples), filtered as its graph filters // them (the punch band-passed, the rumble low-passed, a short echo), at the // trailer's level -- started as Play's clock crosses a landing. No limiter: a // close approximation of the render's mix, not its bytes. // --------------------------------------------------------------------------- const hitBuffers = new Map(); function playTrailerHit(h: { gain: number; decay: number; f0: number; f1: number }, gain = 1) { if (typeof window === "undefined" || typeof window.AudioContext === "undefined") return; audioCtx ??= new window.AudioContext(); const ctx = audioCtx; if (ctx.state === "suspended") void ctx.resume().catch(() => {}); const key = JSON.stringify([h, ctx.sampleRate]); let bufs = hitBuffers.get(key); if (!bufs) { const smp = trailerHitSamples(h, ctx.sampleRate); bufs = [smp.boom, smp.punch, smp.rumble].map((data) => { const b = ctx.createBuffer(1, data.length, ctx.sampleRate); b.copyToChannel(new Float32Array(data), 0); return b; }); hitBuffers.set(key, bufs); } const out = ctx.createGain(); out.gain.value = TRAILER_AUDIO.level * gain; const lp = ctx.createBiquadFilter(); lp.type = "lowpass"; lp.frequency.value = 5000; const echo = ctx.createDelay(0.5); echo.delayTime.value = 0.09; const echoGain = ctx.createGain(); echoGain.gain.value = 0.18; out.connect(lp).connect(ctx.destination); out.connect(echo).connect(echoGain).connect(lp); const chain = [[], [["highpass", 180], ["lowpass", 3200]], [["lowpass", 260], ["lowpass", 260]]] as Array>; const now = ctx.currentTime; bufs.forEach((b, j) => { const src = ctx.createBufferSource(); src.buffer = b; let node: AudioNode = src; for (const [type, f] of chain[j]) { const bq = ctx.createBiquadFilter(); bq.type = type; bq.frequency.value = f; node = node.connect(bq); } node.connect(out); src.start(now); }); } type Censor = { strength: number; boxes: number[][]; band: number[] | null; label: string | null; style: "blur" | "black" | "pixelate" }; /** * A PIXELATED region, live (post-censor.mjs `style: "pixelate"`): the element's * pixels drawn coarse on a canvas over it -- each region (or the whole frame) * read at the render's grid of blocks and scaled back up without smoothing -- * redrawn every frame, so a playing video stays censored. */ function PixelLayer({ source, crop, censor }: { source: React.RefObject; crop: number[] | null; censor: Censor }) { const canvas = useRef(null); const key = JSON.stringify([crop, censor.boxes, censor.strength]); useEffect(() => { let raf = 0; const tiny = document.createElement("canvas"); const draw = () => { const c = canvas.current; const el = source.current; raf = requestAnimationFrame(draw); if (!c || !el) return; const W = Math.max(1, Math.round(c.clientWidth)); const H = Math.max(1, Math.round(c.clientHeight)); if (c.width !== W || c.height !== H) [c.width, c.height] = [W, H]; const sw = el instanceof HTMLVideoElement ? el.videoWidth : el.naturalWidth; const sh = el instanceof HTMLVideoElement ? el.videoHeight : el.naturalHeight; const ctx = c.getContext("2d"); if (!ctx || !sw || !sh) return; ctx.clearRect(0, 0, W, H); const cr = crop ?? [0, 0, 1, 1]; for (const r of censor.boxes.length ? censor.boxes : [[0, 0, 1, 1]]) { const [nx, ny] = pixelGrid(censor.strength, r[2], r[3], W, H); [tiny.width, tiny.height] = [nx, ny]; const t = tiny.getContext("2d"); if (!t) continue; t.imageSmoothingEnabled = true; // The region of the picture as shown (after its crop), in the source's pixels. t.drawImage(el, (cr[0] + r[0] * cr[2]) * sw, (cr[1] + r[1] * cr[3]) * sh, r[2] * cr[2] * sw, r[3] * cr[3] * sh, 0, 0, nx, ny); ctx.imageSmoothingEnabled = false; ctx.drawImage(tiny, 0, 0, nx, ny, r[0] * W, r[1] * H, r[2] * W, r[3] * H); } }; raf = requestAnimationFrame(draw); return () => cancelAnimationFrame(raf); // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, source]); return ; } function MediaEl({ project, m, box, b, step, s, playing, inStep, mix = null, speed = 1, joinOp = 1, sound = true, censored = true, }: { /** Its own sound (present mode's setting): off, the element stays muted. */ sound?: boolean; /** Its censor drawn (post-censor.mjs); off, the picture as captured (present mode's toggle). */ censored?: boolean; /** THE JOIN (post-join.mjs): its strength while it fades in over the attachment the item before ended on. */ joinOp?: number; project: string; m: PostPlan["steps"][number]["items"][number]; box: Box; b: { x: number; y: number; width: number; height: number }; step: PostPlan["steps"][number]; s: number; playing: boolean; inStep: boolean; /** Narrated: its sound muffled under the read, on this schedule. */ mix?: NarrationSchedule | null; /** The clock's speed (Play's rate): the element plays at it. */ speed?: number; }) { const ref = useRef(null); const img = useRef(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(() => { const v = ref.current; if (!v || !muffled || !mix) return; const g = mixGraph(v, mix.lowpassHz); if (!g || !audioCtx) return; if (playing && audioCtx.state === "suspended") void audioCtx.resume().catch(() => {}); const now = audioCtx.currentTime; g.wet.gain.setTargetAtTime(wetGainAt(mix, s), now, 0.01); g.dry.gain.setTargetAtTime(dryGainAt(mix, s), now, 0.01); }, [muffled, mix, s, playing]); const crop = Array.isArray(m.crop) && m.crop.length === 4 ? m.crop : null; const inner: React.CSSProperties = crop ? { position: "absolute", width: `${100 / crop[2]}%`, height: `${100 / crop[3]}%`, left: `${(-crop[0] / crop[2]) * 100}%`, top: `${(-crop[1] / crop[3]) * 100}%`, maxWidth: "none" } : { position: "absolute", inset: 0, width: "100%", height: "100%" }; const timed = step.kind === "video" || step.kind === "gif"; // Before its step: its first frame. In it: the source second the plan says. const target = timed ? (inStep ? mediaTimeAt(step, s) : step.srcFrom ?? 0) : null; const run = playing && inStep; useEffect(() => { const v = ref.current; if (!v || target === null) return; setRate(v, speed); if (Math.abs(v.currentTime - target) > DRIFT * Math.max(1, speed) || !run) { try { v.currentTime = target; } catch { // not seekable yet: the next tick tries again } } if (run && v.paused) void v.play().catch(() => {}); if (!run && !v.paused) v.pause(); }, [target, run, speed]); const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0; // CENSORED (post-censor.mjs): the whole frame, or its regions (its boxes, its band) -- blurred, black or // pixelated, as the render draws them. const blur = censored ? (blurOf(m) as Censor | null) : null; const blurCss = blur && blur.style === "blur" ? `blur(${blurCqw(blur.strength)}cqw)` : undefined; const wholeBlur = blur && blur.style === "blur" && !blur.boxes.length ? blurCss : undefined; const at = blur ? labelBoxOf(blur) : null; return (
{timed ? (