Archilyzer · Source

archilyzer

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

commit 81689c0fbe75a237ba5cba186c04909c18e50023
parent d0de22133672dbf7264bcfb3df1204d2804a2937
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 12:45:51 -0500

umtool: a post item's CAPTION -- a chip explaining a phrase, up as the phrase is read and held a beat (operator, 4 Nov: "不動心 · fudōshin — "immovable mind"" on "Fudōshin")

fx: [{kind: "caption", match, text, target?, occurrence?, at?, lead?, hold?, place?}] beside the word zoom
(post-caption.mjs; validated through validatePostFx). Timed by word-zoom's rule -- at, else the matched word's
start in the picked take's word timings, else the reading estimate (a narrated read spread over its script by
characters; un-narrated, 1 s + 3 words a second). It waits for a word zoom it would be up with. Placed by the
phrase (below by default) inside the card, never over a word read while it is up (placeCaption: below, above,
side; fewest other words hidden), with a notch and an underline; it tracks the phrase as the card pans. Drawn
over the card, never in it: no data-w, no data-post-block, so readInViewErrors never counts it.

The build shoots each chip and its underline alone on a clear page (the card's palette and faces, then Noto Sans
CJK for 不動心) and lays them over the card, fading and sliding in (postSegmentArgs captionFx, trackExpr); Play and
the bench mount the same markup in the card frame (mountCaptions, setCaptionState); the bench's word-zoom block
adds one on the selected words (Caption here) and sets its text, place, lead, hold and moment, and the plan
strip marks it. CLI: umtool posts fx <p> <item> add caption --match "…" --text "…" [--target] [--occurrence]
[--at] [--lead] [--hold] [--place below|above|side]; set/remove/ls as a zoom's.

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

Diffstat:
Mumtool/components/projects/PostBench.tsx | 15+++++++++++++++
Mumtool/components/projects/PostZoomPanel.tsx | 115++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/components/projects/review/PostItemPlayer.tsx | 64+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/postFx.test.mjs | 25++++++++++++++++++++++++-
Mumtool/lib/report/postFxCli.mjs | 50++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/report/postsCli.mjs | 6+++---
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/post-caption.mjs | 525+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-caption.test.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/word-zoom.mjs | 9+++++++--
11 files changed, 1036 insertions(+), 28 deletions(-)

diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -17,6 +17,7 @@ import ComboBadge, { type ComboInfo } from "./review/ComboBadge"; import { liveCombo } from "umtool-report-to-video/post-combo"; import PostZoomPanel from "./PostZoomPanel"; import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; +import { captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // --------------------------------------------------------------------------- @@ -279,6 +280,16 @@ export default function PostBench({ .map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number) })), [entry, render], ); + const captionMarks = useMemo( + () => + (captionTimes(entry, render) as Array<{ i: number; t?: number }>) + .filter((c) => typeof c.t === "number") + .map((c) => { + const f = resolveCaption((entry.fx as Array<Record<string, unknown>>)[c.i]); + return { i: c.i, t0: Math.max(0, (c.t as number) - f.lead), t3: (c.t as number) + f.hold + 0.35 }; + }), + [entry, render], + ); const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null; const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const reading = readingSeconds(entry); @@ -340,6 +351,10 @@ export default function PostBench({ {zoomMarks.map((z) => ( <div key={z.i} className="absolute inset-y-0 border-x border-amber-400/80 bg-amber-400/25" style={{ left: `${(z.t0 / total) * 100}%`, width: `${((z.t3 - z.t0) / total) * 100}%` }} title={`word zoom ${z.i + 1}`} data-post-bench-zoom-mark={z.i} /> ))} + {/* Its captions (post-caption.mjs): each from its lead-in to gone (one waiting for a zoom is drawn later). */} + {captionMarks.map((c) => ( + <div key={`c${c.i}`} className="absolute bottom-0 h-1/3 border-x border-sky-400/80 bg-sky-400/30" style={{ left: `${(c.t0 / total) * 100}%`, width: `${((c.t3 - c.t0) / total) * 100}%` }} title={`caption ${c.i + 1}`} data-post-bench-caption-mark={c.i} /> + ))} <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} /> </div> <PostZoomPanel diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx @@ -7,6 +7,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, WORD_ZOOM_LIMITS, cardTokens, normWord, readingEstimate, resolveWordZoom, targetTextOf, wordZoomTimes, zoomSpan, } from "umtool-report-to-video/word-zoom"; +import { CAPTION_DEFAULTS, CAPTION_LIMITS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; // --------------------------------------------------------------------------- // A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A @@ -14,7 +15,9 @@ import { // Zoom here adds the zoom on them (its match and occurrence filled) -- then each // zoom's knobs: scale, lead, hold, ease, highlight, and its moment: from the // take's word timings (Get word timings: the EDITOR's transcription, a job) or -// `at`, nudged. Every change is one write (POST /api/report/post-item, op "fx"). +// `at`, nudged. A CAPTION (post-caption.mjs) is added on the same words (Caption +// here, its text typed), then its text, place, lead, hold and moment set. +// Every change is one write (POST /api/report/post-item, op "fx"). // --------------------------------------------------------------------------- type Entry = Record<string, unknown> & { id: string; fx?: Array<Record<string, unknown>> }; @@ -56,6 +59,8 @@ export default function PostZoomPanel({ const tokens = useMemo(() => cardTokens(text).filter((t) => t.tok !== undefined) as Array<{ tok: string; i: number }>, [text]); const list = Array.isArray(entry.fx) ? entry.fx : []; const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]); + const ctimes = useMemo(() => captionTimes(entry, render), [entry, render]); + const [capText, setCapText] = useState(""); const narrated = isNarrated(entry); const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null; @@ -71,21 +76,24 @@ export default function PostZoomPanel({ return j.entry; }; - const zoomHere = async () => { + const zoomHere = async (kind: "word-zoom" | "caption" = "word-zoom") => { if (!sel) return; + if (kind === "caption" && !capText.trim()) return setError("a caption needs its text"); const words = tokens.slice(sel.from, sel.to + 1).map((t) => t.tok); const match = words.length === 1 ? bare(words[0]) : [bare(words[0]), ...words.slice(1, -1), bare(words[words.length - 1])].join(" "); // Its occurrence: how many times the same run of words came before it, plus one. const want = words.map(normWord); let occurrence = 1; for (let i = 0; i < sel.from; i += 1) if (want.every((w, k) => normWord(tokens[i + k]?.tok ?? "") === w)) occurrence += 1; - const add: Record<string, unknown> = { kind: "word-zoom", match, ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) }; + const add: Record<string, unknown> = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) }; // An un-narrated post has no read to time it by: the reading estimate, to nudge. - if (!narrated) add.at = readingEstimate(sel.from); + // (A caption is timed by the reading estimate itself when it has no at.) + if (!narrated && kind === "word-zoom") add.at = readingEstimate(sel.from); const e = await send({ add }); if (e) { - setStatus(`zoom added on "${match}"`); + setStatus(`${kind === "caption" ? "caption" : "zoom"} added on "${match}"`); setSel(null); + if (kind === "caption") setCapText(""); } }; @@ -143,7 +151,7 @@ export default function PostZoomPanel({ return ( <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12.5px]" data-post-zoom-panel={entry.id}> <div className="flex flex-wrap items-center gap-2"> - <h2 className="micro m-0">word zoom</h2> + <h2 className="micro m-0">word zoom · caption</h2> {targets.length > 1 && ( <select value={target} onChange={(e) => (setTarget(e.target.value), setSel(null))} data-post-zoom-target=""> {targets.map((t) => ( @@ -193,6 +201,17 @@ export default function PostZoomPanel({ <button type="button" className={btn} disabled={!sel} onClick={() => void zoomHere()} data-post-zoom-here=""> Zoom here </button> + <input + value={capText} + onChange={(e) => setCapText(e.target.value)} + placeholder="caption text" + className="min-w-0 flex-1 rounded border border-seam bg-ground px-1 py-0.5" + aria-label="caption text" + data-post-caption-text="" + /> + <button type="button" className={btn} disabled={!sel || !capText.trim()} onClick={() => void zoomHere("caption")} data-post-caption-here=""> + Caption here + </button> {sel && ( <span className="text-text-2" data-post-zoom-sel=""> “{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}” @@ -200,6 +219,90 @@ export default function PostZoomPanel({ )} </div> {list.map((fx0, i) => { + if (fx0?.kind === "caption") { + const c = resolveCaption(fx0); + const t = ctimes[i] as { t?: number; source?: string; error?: string }; + const at = typeof t?.t === "number" ? t.t : null; + const up = at !== null && s >= at - c.lead && s < at + c.hold + 0.35; + const capKnob = (key: "lead" | "hold") => ( + <label className="flex items-center gap-1" key={key}> + {key} + <input + type="number" + step={0.1} + min={CAPTION_LIMITS[key][0]} + max={CAPTION_LIMITS[key][1]} + defaultValue={Number(c[key])} + key={`${entry.id}:${i}:${key}:${String(c[key])}`} + onBlur={(ev) => { + const v = Number(ev.target.value); + if (Number.isFinite(v) && v !== Number(c[key])) void send({ set: i, patch: { [key]: v === CAPTION_DEFAULTS[key] ? null : v } }); + }} + className="w-14 rounded border border-seam bg-ground px-1 py-0.5" + data-post-caption-knob={key} + /> + </label> + ); + return ( + <div key={i} className={cn("space-y-1.5 rounded border p-2", up ? "border-sky-400/70" : "border-seam")} data-post-caption-fx={i}> + <div className="flex flex-wrap items-center gap-2"> + <b> + #{i + 1} caption on “{c.match}” + </b> + {at !== null ? ( + <span data-post-caption-at={String(at)}> + at {at.toFixed(2)} s {t.source === "at" ? "(set by hand)" : t.source === "words" ? "(the take's words)" : "(the reading estimate)"} + </span> + ) : ( + <span className="text-[var(--color-blocking,#c33)]">{t?.error}</span> + )} + <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (at ?? 0) - c.lead - 0.3))} disabled={at === null} data-post-caption-go={i}> + play it + </button> + <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-caption-remove={i}> + remove + </button> + </div> + <input + defaultValue={c.text} + key={`${entry.id}:${i}:text:${c.text}`} + onBlur={(ev) => ev.target.value.trim() && ev.target.value !== c.text && void send({ set: i, patch: { text: ev.target.value } })} + className="w-full rounded border border-seam bg-ground px-1 py-0.5" + aria-label={`caption ${i + 1} text`} + data-post-caption-knob="text" + /> + <div className="flex flex-wrap items-center gap-2"> + at + <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(Math.max(0, (at ?? 0) - 0.1)) } })} data-post-caption-nudge="-"> + −0.1 + </button> + <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2((at ?? 0) + 0.1) } })} data-post-caption-nudge="+"> + +0.1 + </button> + <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(s) } })} data-post-caption-at-playhead=""> + at playhead + </button> + {typeof fx0.at === "number" && ( + <button type="button" className="ink-link" onClick={() => void send({ set: i, patch: { at: null } })} data-post-caption-from-words=""> + {narrated ? "from the read" : "the estimate"} + </button> + )} + {capKnob("lead")} + {capKnob("hold")} + <label className="flex items-center gap-1"> + place + <select value={c.place} onChange={(e) => void send({ set: i, patch: { place: e.target.value === CAPTION_DEFAULTS.place ? null : e.target.value } })} data-post-caption-knob="place"> + {CAPTION_PLACES.map((x) => ( + <option key={x} value={x}> + {x} + </option> + ))} + </select> + </label> + </div> + </div> + ); + } const fx = resolveWordZoom(fx0); const t = times[i] as { t?: number; source?: string; error?: string }; const at = typeof t?.t === "number" ? t.t : null; diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -5,6 +5,9 @@ import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-re import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow"; 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 { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- @@ -26,6 +29,11 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar // `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). +// // 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 @@ -36,6 +44,8 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar type Rect = { x: number; y: number; width: number; height: number }; /** 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: ReturnType<typeof placeCaption>; base: Rect; lines: Rect[] }; type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; 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. */ @@ -433,6 +443,7 @@ export default function PostItemPlayer({ // ---- 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); const [zooms, setZooms] = useState<LiveZoom[]>([]); + const [caps, setCaps] = useState<LiveCaption[]>([]); const boxes = useRef<Map<Element, Rect>>(new Map()); const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]); // ---- read-follow, live: the page's geometry measured once it is drawn, the path from it ---- @@ -451,6 +462,8 @@ export default function PostItemPlayer({ const list = Array.isArray(entry.fx) ? (entry.fx as Array<Record<string, unknown>>) : []; if (!card || !list.length) { setZooms([]); + setCaps([]); + mountCaptions({ css: "", chips: [] }, doc); return true; } const rect = (el: Element): Rect => { @@ -482,8 +495,29 @@ export default function PostItemPlayer({ out.push({ i, span: zoomSpan(fx0, t.t), scope, from: m.from, to: m.to, color: fx.highlight === false ? null : String(fx.highlight), region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } }); }); setZooms(out); + // Its captions: planned as the build plans them (each waits for a zoom), mounted, placed as the card is at each one's peak. + let cplan: ReturnType<typeof captionPlan> = []; + try { + cplan = captionPlan(entry, undefined, { zooms: out.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration as never }); + } catch { + cplan = []; + } + const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })) }, doc); + const k = box.height / 1080; + const inset = Math.round(10 * k); + const placedCaps: LiveCaption[] = []; + for (const c of cplan) { + if (follow) applyFollowState(followStateAt(follow, route, c.span.t1), doc); + const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }, doc) as { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; others: Rect[] }; + const size = sizes.find((x) => x.i === c.i); + if (g.error || !size) continue; + const bounds = { x: g.card.x + inset, y: g.card.y + inset, width: g.card.width - 2 * inset, height: g.card.height - 2 * inset }; + const placed = placeCaption({ word: g.word, chip: size, bounds, place: c.place, avoid: g.avoid, others: g.others, gap: Math.round(16 * k) }); + placedCaps.push({ i: c.i, span: c.span, scope: c.scope, from: c.from, to: c.to, placed, base: g.word, lines: g.lines }); + } + setCaps(placedCaps); return true; - }, [entry, zoomTimes, box.height, follow]); + }, [entry, zoomTimes, box.height, follow, layout.mode, plan.steps, plan.total, plan.narration]); const onFrameLoad = useCallback(() => { let tries = 0; const tick = () => { @@ -508,6 +542,31 @@ export default function PostItemPlayer({ const doc = readFrame.current?.contentDocument; if (doc && follow && doc.querySelector("[data-post-follow]")) applyFollowState(followNow, doc); }, [follow, followNow, followGeo]); + // The captions up now, after the follow state of this tick: each tracking its phrase (measured live when the card pans). + const capsUp = caps.filter((c) => s >= c.span.t0 && s < c.span.t3); + useEffect(() => { + const doc = readFrame.current?.contentDocument; + if (!doc) return; + const k = box.height / 1080; + const list = capsUp.map((c) => { + let dx = 0; + let dy = 0; + let lines = c.lines; + if (follow) { + const g = measureCaptionWords({ scope: c.scope, from: c.from, to: c.to, avoid: [] }, doc) as { error?: string; word: Rect; lines: Rect[] }; + if (!g.error) { + dx = g.word.x - c.base.x; + dy = g.word.y - c.base.y; + lines = g.lines; + } + } + const left = captionSlideAt(c.span, s); + const d = slideDir(c.placed.place); + const opacity = captionOpacityAt(c.span, s); + return { i: c.i, x: c.placed.x, y: c.placed.y, place: c.placed.place, notch: c.placed.notch, opacity, dx: dx + d.x * CAPTION_SLIDE * k * left, dy: dy + d.y * CAPTION_SLIDE * k * left, marks: lines, mark: opacity }; + }); + setCaptionState({ list }, doc); + }, [capsUp, s, follow, followNow, box.height]); 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 ( @@ -525,6 +584,9 @@ export default function PostItemPlayer({ data-post-zooms={zooms.length ? String(zooms.length) : undefined} data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined} data-post-zoom-fx={live ? String(live.i) : undefined} + data-post-captions={caps.length ? String(caps.length) : undefined} + data-post-caption-fx={capsUp.length ? capsUp.map((c) => String(c.i)).join(" ") : undefined} + data-post-caption-place={capsUp.length ? capsUp.map((c) => c.placed.place).join(" ") : undefined} data-post-follow-block={followNow?.current !== null && followNow?.current !== undefined ? String(followNow.current) : undefined} data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined} data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined} diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs @@ -55,7 +55,7 @@ test("posts fx: add (an un-narrated post gets the reading estimate), set, ls, re r = await cli(["fx", "fx", "p-1", "remove", "1"]); assert.equal(r.code, 0, r.err); assert.equal((await manifest(p)).timeline[0].fx, undefined); - assert.match(r.out, /no word zooms/); + assert.match(r.out, /no effects/); await assert.rejects(updatePostFx(p.dir, "p-1", { remove: 0 }), /has no effects/); }); @@ -88,3 +88,26 @@ test("posts narrate --words: the take transcribed by the editor (its parts, at t for (const f of ["p01", "p02"]) await writeFile(path.join(p.dir, `narration/posts/1/take-1.parts/${f}.wav`), ""); assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: parted.parts[0].file, offset: 0 }, { file: parted.parts[1].file, offset: 2.6 }]); }); + +test("posts fx add caption: the chip's text kept (CJK too), timed by the reading estimate, its knobs set -- a zoom's knobs refused", async () => { + const p = await project("cap", [item("1", { text: "I have achieved Fudōshin. Its amazing." })]); + let r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin", "--text", "不動心 · fudōshin — \"immovable mind\""]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /0 word zoom\(s\), 1 caption\(s\)/); + assert.match(r.out, /#1 caption "Fudōshin" \(post, 1st\) at 2.00 s \(the reading estimate\) · "不動心 · fudōshin — "immovable mind"" · in 0.15 s before, held 2.5 s, below/); + assert.deepEqual((await manifest(p)).timeline[0].fx, [{ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"" }]); + r = await cli(["fx", "cap", "p-1", "set", "1", "--place", "above", "--hold", "3", "--at", "1.5"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).timeline[0].fx[0], { kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"", place: "above", hold: 3, at: 1.5 }); + r = await cli(["fx", "cap", "p-1", "set", "1", "--place", "left"]); + assert.equal(r.code, 1); + assert.match(r.err, /fx\[0\]\.place must be one of below, above, side/); + r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin"]); + assert.match(r.err, /add caption needs --text/); + r = await cli(["fx", "cap", "p-1", "add", "caption", "--match", "Fudōshin", "--text", "x", "--scale", "2"]); + assert.match(r.err, /--scale is a word zoom's knob/); + r = await cli(["fx", "cap", "p-1", "add", "word-zoom", "--match", "amazing", "--text", "x"]); + assert.match(r.err, /--text and --place are a caption's knobs/); + r = await cli(["fx", "cap", "p-1", "ls", "--json"]); + assert.deepEqual(JSON.parse(r.out).times, [{ i: 0, t: 1.5, source: "at" }]); +}); diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs @@ -8,6 +8,8 @@ // umtool posts fx <p> <item> [ls] // umtool posts fx <p> <item> add word-zoom --match "…" [--target post|quoted|parent:<i>] [--occurrence n] [--at s] // [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] +// umtool posts fx <p> <item> add caption --match "…" --text "…" [--target …] [--occurrence n] [--at s] +// [--lead s] [--hold s] [--place below|above|side] (post-caption.mjs) // umtool posts fx <p> <item> set <n> [the same flags; a flag's value `default` clears it] // umtool posts fx <p> <item> remove <n> // umtool posts narrate <p> <item> --words [--worker <id>] @@ -19,6 +21,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, findMatch, readingEstimate, resolveWordZoom, scriptWordTimes, targetTextOf, wordZoomTimes, } from "umtool-report-to-video/word-zoom"; +import { CAPTION_DEFAULTS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostFx, updatePostNarration } from "./manifest.mjs"; @@ -28,6 +31,8 @@ export const FX_USAGE = [ "usage: umtool posts fx <project> <item> [ls] [--json]", " umtool posts fx <project> <item> add word-zoom --match \"…\" [--target post|quoted|parent:<i>] [--occurrence n]", " [--at s] [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] [--json]", + " umtool posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post|quoted|parent:<i>] [--occurrence n]", + " [--at s] [--lead s] [--hold s] [--place below|above|side] [--json]", " umtool posts fx <project> <item> set <n> [those flags; `default` clears one] | remove <n>", " A WORD ZOOM: the card pushed in on a word (or a phrase) as it is read, a highlight under it, then back out.", " --match is the word as the card shows it (case and edge punctuation aside); --occurrence its n-th time in the", @@ -36,7 +41,12 @@ export const FX_USAGE = [ " read's rate) -- `umtool posts narrate <p> <item> --words` gets them from the editor's transcription. An", " un-narrated post needs --at (add fills the reading estimate: 1 s + 3 words a second).", ` --scale 1.2–4 (default ${WORD_ZOOM_DEFAULTS.scale}), --lead 0–3 s in before the word (${WORD_ZOOM_DEFAULTS.lead}), --hold 0–10 s on it (${WORD_ZOOM_DEFAULTS.hold}),`, - ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the zoom's number as ls shows it.`, + ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the effect's number as ls shows it.`, + " A CAPTION: a chip explaining a phrase (--text, any script: CJK is drawn), up as the phrase is read and held a beat,", + " by the phrase (--place; it never covers a word read while it is up) with a notch and an underline. WHEN: --at, else", + " the word's start in the take's word timings, else the reading estimate (a narrated read spread over its script).", + ` --lead 0–3 s in before the word (${CAPTION_DEFAULTS.lead}), --hold 0.5–10 s from it (${CAPTION_DEFAULTS.hold}), --place ${CAPTION_PLACES.join("|")} (${CAPTION_DEFAULTS.place}).`, + " A caption up while a word zoom is waits for the zoom to be out.", ].join("\n"); export class FxError extends Error {} @@ -60,6 +70,10 @@ export function fxPatchOf(str) { out[key] = x; } } + const tx = str("--text"); + if (tx !== null) out.text = tx; + const pl = str("--place"); + if (pl !== null) out.place = pl === "default" ? null : pl; const e = str("--ease"); if (e !== null) out.ease = e === "default" ? null : e; const h = str("--highlight"); @@ -69,14 +83,22 @@ export function fxPatchOf(str) { const nth = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`; -/** One item's zooms as lines. */ +/** One item's effects (word zooms, captions) as lines. */ export function fxLines(e, render) { const list = Array.isArray(e.fx) ? e.fx : []; - if (!list.length) return [`${e.id}: no word zooms (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…")`]; + if (!list.length) return [`${e.id}: no effects (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…" | add caption --match "…" --text "…")`]; const times = wordZoomTimes(e, render); + const ctimes = captionTimes(e, render); + const nz = list.filter((f) => f?.kind !== "caption").length; return [ - `${e.id}: ${list.length} word zoom(s)${isNarrated(e) ? "" : " (not narrated: each needs at)"}`, + `${e.id}: ${nz} word zoom(s), ${list.length - nz} caption(s)${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`, ...list.map((fx0, i) => { + if (fx0?.kind === "caption") { + const c = resolveCaption(fx0); + const t = ctimes[i]; + const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s (${t.source === "at" ? "set by hand" : t.source === "words" ? "from the take's words" : "the reading estimate"})`; + return ` #${i + 1} caption "${c.match}" (${c.target}, ${nth(c.occurrence)}) ${when} · "${c.text}" · in ${c.lead} s before, held ${c.hold} s, ${c.place}`; + } const fx = resolveWordZoom(fx0); const t = times[i]; const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s ${t.source === "at" ? "(set by hand)" : `(from the take's words: "${t.word.w}" at ${t.word.start} s)`}`; @@ -95,12 +117,15 @@ export async function fxCommand(project, words, { json = false, out = (s) => con if (!e) throw new FxError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); const write = async (op) => withEditNotes(project, async () => updatePostFx(project.dir, e.id, op, { token: await manifestToken(project.dir) })); const say = (entry, extra = {}) => { - if (json) out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render), ...extra }, null, 2)); + if (json) { + const ct = captionTimes(entry, render); + out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render).map((t, i) => (entry.fx?.[i]?.kind === "caption" ? ct[i] : t)), ...extra }, null, 2)); + } else out(fxLines(entry, render).join("\n")); }; const index = () => { const n = Number(arg); - if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the zoom's number as ls shows it (1 = the first)`); + if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the effect's number as ls shows it (1 = the first)`); return n - 1; }; if (verb === "ls") { @@ -108,8 +133,17 @@ export async function fxCommand(project, words, { json = false, out = (s) => con return 0; } if (verb === "add") { - if (arg !== "word-zoom") throw new FxError("add names the effect: add word-zoom --match \"…\""); + if (arg !== "word-zoom" && arg !== "caption") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\""); const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null)); + if (arg === "caption") { + if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add caption needs --match \"<the phrase, as the card shows it>\""); + if (typeof patch.text !== "string" || !patch.text.trim()) throw new FxError("add caption needs --text \"<what the chip says>\""); + for (const k of ["scale", "ease", "highlight"]) if (k in patch) throw new FxError(`--${k} is a word zoom's knob, not a caption's`); + const { result } = await write({ add: { kind: "caption", ...patch } }); + say(result.entry, { index: result.index }); + return 0; + } + if ("text" in patch || "place" in patch) throw new FxError("--text and --place are a caption's knobs (add caption …)"); if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add word-zoom needs --match \"<the word, as the card shows it>\""); let note = null; if (patch.at === undefined && !isNarrated(e)) { @@ -127,7 +161,7 @@ export async function fxCommand(project, words, { json = false, out = (s) => con if (verb === "set") { const i = index(); const patch = fxPatchOf(str); - if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --scale, --hold, --lead, --ease, --highlight, --occurrence, --target"); + if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --hold, --lead, --occurrence, --target; a zoom's --scale, --ease, --highlight; a caption's --text, --place"); const { result } = await write({ set: i, patch }); say(result.entry); return 0; diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -113,8 +113,8 @@ export const POSTS_USAGE = [ " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", " (umtool posts narrate --help)", " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", - " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] [--scale s] … | set <n> … | remove <n>", - " a WORD ZOOM: the card pushed in on a word as it is read (umtool posts fx --help)", + " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] … | add caption --match \"…\" --text \"…\" | set <n> … | remove <n>", + " a WORD ZOOM (the card pushed in on a word) or a CAPTION (a chip explaining a phrase) as it is read (umtool posts fx --help)", " umtool posts avatar <project> [<handle> <image-file> | <handle> off] [--json]", " an author's PICTURE on every card that draws them (postAvatars): the file copied into posts-media/_avatars/,", " never replaced by the archive's; `off` clears it; no handle lists them. A blurred author never shows one.", @@ -138,7 +138,7 @@ export const POSTS_USAGE = [ " umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment", ].join("\n"); -const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts"]); +const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -75,6 +75,7 @@ "./post-conversation": "./post-conversation.mjs", "./post-render": "./post-render.mjs", "./word-zoom": "./word-zoom.mjs", + "./post-caption": "./post-caption.mjs", "./read-follow": "./read-follow.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.mjs", diff --git a/umtool/report-to-video/post-caption.mjs b/umtool/report-to-video/post-caption.mjs @@ -0,0 +1,525 @@ +// A POST ITEM's CAPTION (umtool/docs/report-video.md, "A caption"; operator, 4 Nov: +// a small explanatory chip tied to a phrase -- "不動心 · fudōshin — "immovable +// mind"" on "Fudōshin" -- appearing as the phrase is read and held a beat). +// +// entry.fx = [{ kind: "caption", +// target?: "post" | "parent:<i>" | "quoted", // whose words (default: the post's own) +// match: "<the word or phrase, as the card shows it>", +// occurrence?: n, // its n-th time in that text (default 1) +// text: "<what the chip says>", // ≤ CAPTION_TEXT_MAX characters, any script (CJK too) +// at?: <item seconds>, // when; absent: the take's word timings, else the estimate +// lead?: s, hold?: s, // in this long before the word; held this long from it +// place?: "below" | "above" | "side" }] // where it sits by the phrase (default below) +// +// WHEN -- word-zoom's rule: `at` when it is set, else the matched word's start in +// the picked take's word timings (the read's lead + start ÷ rate), else the +// READING ESTIMATE: a narrated post's read spread over its script by characters, +// an un-narrated one's 1 s + 3 words a second (word-zoom.mjs readingEstimate). +// A caption never fights a word zoom: one that would be up while a zoom is (its +// lead-in to back out) WAITS for the zoom to be out, then comes in. +// +// WHERE: a chip by the phrase (`place`; below by default), with a notch pointing +// at it and an underline under it, inside the card. It never covers a word read +// while it is up: a place that would is passed over for the next (below, above, +// side), and the chip tracks the phrase while the card pans (read-follow.mjs). +// It is drawn OVER the card, never in it: the read-follow geometry +// (measureFollow, readInViewErrors) is measured without it, and it carries no +// `data-w` / `data-post-block` -- it never counts as text, read or covering. +// +// THE LOOK: the card's palette (a panel of its background toward its accent, the +// accent's border and notch), its faces, then the CJK faces this machine has +// (CAPTION_FONT_STACK) so 不動心 is drawn, not boxes. Text before " — " is bold. +// +// Pure but for the DOM functions (mountCaptions, measureCaptionWords, +// setCaptionState), which are SELF-CONTAINED: the build passes them to a page +// (page.evaluate), Play calls them on its card frame's document. + +import { alignWords, cardWordsOf, findMatch, readingEstimate, scriptWordsOf, targetScope, targetTextOf } from "./word-zoom.mjs"; +import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; +import { esc, mixHex, rgbaOf } from "./post-item.mjs"; + +export const CAPTION_PLACES = Object.freeze(["below", "above", "side"]); +export const CAPTION_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.15, hold: 2.5, place: "below" }); +export const CAPTION_LIMITS = Object.freeze({ at: [0, 600], lead: [0, 3], hold: [0.5, 10], occurrence: [1, 99] }); +export const CAPTION_TEXT_MAX = 160; +/** Its fade (and slide) in, and its fade out, seconds. */ +export const CAPTION_IN = 0.3; +export const CAPTION_OUT = 0.35; +/** How far it slides in from, px at 1080. */ +export const CAPTION_SLIDE = 16; +/** The faces a chip is drawn in: the card's, then the CJK faces (Noto Sans CJK on this machine), then any sans. */ +export const CAPTION_FONT_STACK = "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', 'Source Han Sans CN', 'WenQuanYi Zen Hei', sans-serif"; + +const KEYS = new Set(["kind", "target", "match", "occurrence", "text", "at", "lead", "hold", "place"]); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi; +const r3 = (v) => Math.round(v * 1000) / 1000; +const MATCH_MAX = 120; + +/** + * One caption with every default filled in. + * @param {Record<string, any> | null | undefined} fx + * @returns {{ kind?: string, target: string, match: string, occurrence: number, text: string, at?: number, lead: number, hold: number, place: string }} + */ +export const resolveCaption = (fx) => ({ ...CAPTION_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) }); + +const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`); + +/** Every reason caption `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */ +export function captionErrors(e, fx, fw) { + const errors = []; + for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a caption key (${[...KEYS].join(", ")})`); + const target = fx.target ?? "post"; + const text = typeof target === "string" ? targetTextOf(e, target) : null; + if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:<i>"`); + else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`); + if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase the caption explains, as the card shows it`); + else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`); + if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be what the caption says`); + else if (fx.text.length > CAPTION_TEXT_MAX) errors.push(`${fw}.text is longer than ${CAPTION_TEXT_MAX} characters (a caption is a chip, not a paragraph)`); + if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, CAPTION_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`); + if (typeof fx.match === "string" && fx.match.trim() && text !== null) { + const m = findMatch(text, fx.match, fx.occurrence ?? 1); + if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`); + else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`); + else if (m.error) errors.push(`${fw}.match: ${m.error}`); + } + for (const k of ["at", "lead", "hold"]) if (fx[k] !== undefined && !numIn(fx[k], CAPTION_LIMITS[k])) errors.push(`${fw}.${k} must be ${CAPTION_LIMITS[k][0]}–${CAPTION_LIMITS[k][1]} seconds`); + if (fx.place !== undefined && !CAPTION_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${CAPTION_PLACES.join(", ")}`); + return errors; +} + +// --------------------------------------------------------------------------- +// WHEN. +// --------------------------------------------------------------------------- + +/** Fill each null in `times` between its known neighbours (an end with none: the nearest known). */ +function fillTimes(times) { + const out = times.slice(); + const known = out.map((v, i) => (v === null ? -1 : i)).filter((i) => i >= 0); + if (!known.length) return out; + for (let i = 0; i < out.length; i += 1) { + if (out[i] !== null) continue; + const a = [...known].reverse().find((k) => k < i); + const b = known.find((k) => k > i); + if (a === undefined) out[i] = out[b]; + else if (b === undefined) out[i] = out[a]; + else out[i] = r3(out[a] + ((out[b] - out[a]) * (i - a)) / (b - a)); + } + return out; +} + +/** + * When each card word of `target` is read, item seconds: `{ times, source }` + * -- "words" from the picked take's word timings, "estimate" otherwise (a + * narrated post: its script's characters spread over the read; an un-narrated + * one: readingEstimate). Null when the target draws no words. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {string} [target] + * @param {Record<string, any> | null} [schedule] + * @returns {{ times: Array<number | null>, source: "words" | "estimate" } | null} + */ +export function cardWordTimes(entry, render = undefined, target = "post", schedule = undefined) { + const text = targetTextOf(entry, target); + if (text === null) return null; + const words = cardWordsOf(text); + if (!isNarrated(entry)) return { times: words.map((_, i) => readingEstimate(i)), source: "estimate" }; + const sch = schedule ?? narrationSchedule(entry, render); + const rate = sch.rate || 1; + const take = pickedTake(entry); + const timed = Array.isArray(take?.words) && take.words.length ? take.words : null; + if (timed) { + const map = alignWords(words, timed.map((x) => x.w)); + return { times: fillTimes(map.map((k) => (k >= 0 && fin(timed[k].start) ? r3(sch.at + timed[k].start / rate) : null))), source: "words" }; + } + const script = typeof take?.script === "string" && take.script.trim() ? take.script : String(entry?.narration?.script ?? ""); + const sw = scriptWordsOf(script); + const map = alignWords(words, sw); + const before = []; + let n = 0; + for (const w of sw) { + before.push(n); + n += w.length + 1; + } + const secs = fin(sch.seconds) && sch.seconds > 0 ? sch.seconds : (n / 15); + return { times: fillTimes(map.map((k) => (k >= 0 && n > 0 ? r3(sch.at + (before[k] / n) * secs) : null))), source: "estimate" }; +} + +/** + * Each caption's moment, one per fx (a word zoom's row is `{ i, kind }`): + * `{ i, t, source: "at"|"words"|"estimate" }` or `{ i, error }`. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {Record<string, any> | null} [schedule] + * @returns {Array<{ i: number, t?: number, source?: string, error?: string, kind?: string | null }>} + */ +export function captionTimes(entry, render = undefined, schedule = undefined) { + const list = Array.isArray(entry?.fx) ? entry.fx : []; + const cache = new Map(); + return list.map((fx0, i) => { + if (!isObj(fx0) || fx0.kind !== "caption") return { i, kind: fx0?.kind ?? null }; + const fx = resolveCaption(fx0); + if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" }; + const text = targetTextOf(entry, fx.target); + const m = findMatch(text, fx.match, fx.occurrence); + if (m.error) return { i, error: `${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") is not on the card` }; + if (!cache.has(fx.target)) cache.set(fx.target, cardWordTimes(entry, render, fx.target, schedule)); + const wt = cache.get(fx.target); + const t = wt?.times?.[m.from]; + if (!fin(t)) return { i, t: readingEstimate(m.from), source: "estimate" }; + return { i, t: r3(t), source: wt.source }; + }); +} + +/** + * One caption's span on the item's clock: in from t0 (its lead before the + * word) to t1, held to t2 (`hold` after the word), out by t3. It WAITS for a + * word zoom (`zooms`: their spans, word-zoom.mjs zoomSpan) it would be up + * with, and ends by `end` (the item's last second, or a stack card's media + * phase). `{ t0, t1, t2, t3, at, waited }` or `{ error }`. + * @param {Record<string, any>} fx0 + * @param {number} t + * @param {{ zooms?: Array<Record<string, any>>, end?: number }} [o] + * @returns {{ t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, error?: undefined } | { error: string, t0?: undefined, t1?: undefined, t2?: undefined, t3?: undefined, at?: undefined, waited?: undefined }} + */ +export function captionSpan(fx0, t, { zooms = [], end = Infinity } = {}) { + const fx = resolveCaption(fx0); + let t0 = Math.max(0, t - fx.lead); + let dur = Math.max(CAPTION_IN, t + fx.hold - t0); + /** @type {number | null} */ + let waited = null; + const sorted = zooms.map((z, k) => ({ ...z, k })).filter((z) => fin(z.t0) && fin(z.t3)).sort((a, b) => a.t0 - b.t0); + for (const z of sorted) { + if (t0 < z.t3 && t0 + dur + CAPTION_OUT > z.t0) { + t0 = z.t3; + waited = z.i ?? z.k; + } + } + if (t0 >= end - CAPTION_IN - 0.05) return { error: `starts at ${r3(t0)} s, at or after the item's ${r3(end)} s${waited !== null ? " (it waits for a word zoom)" : ""}` }; + let t2 = t0 + dur; + if (t2 + CAPTION_OUT > end) t2 = Math.max(t0 + CAPTION_IN, end - CAPTION_OUT); + const t1 = Math.min(t2, t0 + CAPTION_IN); + return { t0: r3(t0), t1: r3(t1), t2: r3(t2), t3: r3(Math.min(end, t2 + CAPTION_OUT)), at: r3(t), waited }; +} + +const easeOut = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; + +/** The chip's opacity at item second `s` (0–1). */ +export function captionOpacityAt(span, s) { + if (!span || span.error || s < span.t0 || s >= span.t3) return 0; + if (s < span.t1) return span.t1 > span.t0 ? easeOut((s - span.t0) / (span.t1 - span.t0)) : 1; + if (s < span.t2) return 1; + return 1 - (s - span.t2) / (span.t3 - span.t2); +} + +/** How much of its slide in is left at `s`, 1 → 0 (0 once in). */ +export function captionSlideAt(span, s) { + if (!span || span.error || s >= span.t1) return 0; + if (s < span.t0) return 1; + return 1 - easeOut((s - span.t0) / Math.max(1e-6, span.t1 - span.t0)); +} + +/** The direction a placed chip slides in from (toward the phrase): a unit `{ x, y }`. */ +export const slideDir = (place) => (place === "above" ? { x: 0, y: -1 } : place === "side-right" ? { x: 1, y: 0 } : place === "side-left" ? { x: -1, y: 0 } : { x: 0, y: 1 }); + +/** Two captions of one post up at once: their indices, or null (one at a time). */ +export function overlappingCaptions(spans) { + const s = spans.filter((x) => x && fin(x.t0)).sort((a, b) => a.t0 - b.t0); + for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i]; + return null; +} + +// --------------------------------------------------------------------------- +// WHERE. +// --------------------------------------------------------------------------- + +/** @typedef {{ x: number, y: number, width: number, height: number }} Rect */ +/** @param {Rect} a @param {Rect} b */ +const area = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); +/** @param {Rect} r @param {Rect} b */ +const inside = (r, b) => r.x >= b.x - 0.5 && r.y >= b.y - 0.5 && r.x + r.width <= b.x + b.width + 0.5 && r.y + r.height <= b.y + b.height + 0.5; + +/** + * THE PLACE: the chip's box (`chip`: its size) by the phrase (`word`: its box), + * inside `bounds` (the card), covering no box in `avoid` (the words read while + * it is up). The asked place first, then below, above, side (right, then left); + * the first that fits and covers nothing wins, else the one that fits and + * covers least, else the asked one clamped inside. `{ x, y, width, height, + * place, covers, notch }` -- among places that cover no word read, the one + * covering fewest of the card's other words (`others`) wins; each vertical place + * is tried centred on the phrase, then its left and right edges aligned. + * `place` "below"|"above"|"side-right"|"side-left", + * `covers` how many avoided boxes it touches, `notch` the point (chip px) its + * pointer sits at along the edge that faces the phrase. + * @param {{ word: Rect, chip: { width: number, height: number }, bounds: Rect, place?: string, avoid?: Rect[], others?: Rect[], gap?: number }} o + * @returns {Rect & { place: string, covers: number, notch: number }} + */ +export function placeCaption({ word, chip, bounds, place = "below", avoid = [], others = [], gap = 14 }) { + const order = [place, ...CAPTION_PLACES.filter((p) => p !== place)].flatMap((p) => (p === "side" ? ["side-right", "side-left"] : [p])); + const clampX = (x) => Math.min(bounds.x + bounds.width - chip.width, Math.max(bounds.x, x)); + const clampY = (y) => Math.min(bounds.y + bounds.height - chip.height, Math.max(bounds.y, y)); + const cx = word.x + word.width / 2; + const cy = word.y + word.height / 2; + const xs = [cx - chip.width / 2, word.x - 12, word.x + word.width + 12 - chip.width]; + const at = (p, a = 0) => { + if (p === "below") return { x: clampX(xs[a]), y: word.y + word.height + gap }; + if (p === "above") return { x: clampX(xs[a]), y: word.y - gap - chip.height }; + if (p === "side-right") return { x: word.x + word.width + gap, y: clampY(cy - chip.height / 2) }; + return { x: word.x - gap - chip.width, y: clampY(cy - chip.height / 2) }; + }; + const tries = order.flatMap((p) => (p === "below" || p === "above" ? [0, 1, 2] : [0]).map((a) => { + const r = { ...at(p, a), width: chip.width, height: chip.height }; + const covers = avoid.filter((b) => area(r, b) > 4).length; + const hides = others.filter((b) => area(r, b) > 4).length; + return { ...r, place: p, covers, hides, fits: inside(r, bounds) && area(r, word) <= 1 }; + })); + // Clear of the read: fewest other words hidden, then the asked order (a stable sort keeps it). + const pick = tries.filter((r) => r.fits && !r.covers).sort((a, b) => a.hides - b.hides)[0] ?? tries.filter((r) => r.fits).sort((a, b) => a.covers - b.covers || a.hides - b.hides)[0] ?? (() => { + const r = tries[0]; + return { ...r, x: clampX(r.x), y: clampY(r.y) }; + })(); + const vertical = pick.place === "below" || pick.place === "above"; + const pad = Math.min(24, vertical ? chip.width / 4 : chip.height / 4); + const notch = vertical ? Math.min(chip.width - pad, Math.max(pad, cx - pick.x)) : Math.min(chip.height - pad, Math.max(pad, cy - pick.y)); + const { fits, hides, ...out } = pick; + return { ...out, x: Math.round(out.x), y: Math.round(out.y), notch: Math.round(notch) }; +} + +// --------------------------------------------------------------------------- +// THE PLAN. +// --------------------------------------------------------------------------- + +/** + * Post item `entry`'s captions, resolved: `[{ i, scope, from, to, text, + * place, t, source, span, avoid }]` -- `avoid` the target's word indices read + * while it is up (the chip covers none of them). `zooms`: the item's word + * zooms' spans (each a caption waits for); `end`: the last second a caption + * may be up. Throws in the build's words when one cannot be up, or two are up at once. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {{ zooms?: Array<Record<string, any>>, end?: number, schedule?: Record<string, any> }} [o] + * @returns {Array<{ i: number, scope: string, from: number, to: number, text: string, place: string, t: number, source: string, span: { t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, i: number }, avoid: number[] }>} + */ +export function captionPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) { + const list = Array.isArray(entry?.fx) ? entry.fx : []; + if (!list.some((f) => f?.kind === "caption")) return []; + const times = captionTimes(entry, render, schedule); + const bad = times.filter((t) => t.error); + if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); + const wt = new Map(); + /** @type {ReturnType<typeof captionPlan>} */ + const out = []; + for (const [i, fx0] of list.entries()) { + if (fx0?.kind !== "caption") continue; + const fx = resolveCaption(fx0); + const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence); + const span = captionSpan(fx0, times[i].t, { zooms, end }); + if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") ${span.error} (move its at, or shorten the zoom)`); + if (!wt.has(fx.target)) wt.set(fx.target, cardWordTimes(entry, render, fx.target, schedule)); + const read = wt.get(fx.target)?.times ?? []; + const avoid = read.map((s, k) => (fin(s) && s >= span.t0 - 0.25 && s <= span.t3 + 0.25 && (k < m.from || k > m.to) ? k : -1)).filter((k) => k >= 0); + out.push({ i, scope: targetScope(fx.target), from: m.from, to: m.to, text: fx.text, place: fx.place, t: Number(times[i].t), source: String(times[i].source), span: { ...span, i }, avoid }); + } + const clash = overlappingCaptions(out.map((c) => c.span)); + if (clash) throw new Error(`${entry?.id ?? "?"}: captions ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`); + return out; +} + +// --------------------------------------------------------------------------- +// THE LOOK. +// --------------------------------------------------------------------------- + +/** The chip's inner HTML: the text, its part before " — " bold. */ +export function captionInnerHtml(text) { + const t = String(text ?? ""); + const cut = t.indexOf(" — "); + return cut > 0 ? `<b>${esc(t.slice(0, cut))}</b><span class="pcap-rest"> — ${esc(t.slice(cut + 3))}</span>` : esc(t); +} + +/** + * The chips' CSS, for a page `height` px tall (sizes at 1080), in the card's + * palette (`palette`, the deck's) and faces (the card's @font-face PostSans / + * PostSansBold, then CAPTION_FONT_STACK). + */ +/** @param {{ height?: number, palette?: Record<string, string> }} [o] */ +export function captionCss({ height = 1080, palette = {} } = {}) { + const k = height / 1080; + const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; + const panel = mixHex(pal.bg, pal.accent, 0.16); + const n = Math.round(16 * k); + return ` +[data-post-fx-captions] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 60; } +.pcap { position: absolute; left: 0; top: 0; max-width: ${Math.round(620 * k)}px; padding: ${Math.round(10 * k)}px ${Math.round(18 * k)}px ${Math.round(11 * k)}px; background: ${panel}; color: ${pal.fg}; + border: ${Math.max(1, Math.round(2 * k))}px solid ${pal.accent}; border-radius: ${Math.round(12 * k)}px; box-shadow: 0 ${Math.round(8 * k)}px ${Math.round(26 * k)}px ${rgbaOf("#000000", 0.5)}; + font-family: 'PostSans', ${CAPTION_FONT_STACK}; font-size: ${Math.round(27 * k)}px; line-height: 1.28; font-synthesis: none; opacity: 0; will-change: transform, opacity; overflow-wrap: anywhere; } +.pcap b { font-family: 'PostSansBold', ${CAPTION_FONT_STACK}; font-weight: 700; color: ${pal.fg}; } +.pcap .pcap-rest { color: ${mixHex(pal.fg, pal.muted, 0.25)}; } +.pcap::before { content: ""; position: absolute; width: ${n}px; height: ${n}px; background: ${panel}; border: inherit; border-width: ${Math.max(1, Math.round(2 * k))}px; border-radius: ${Math.round(2 * k)}px; transform: rotate(45deg); } +.pcap[data-place="below"]::before { top: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-right: none; border-bottom: none; } +.pcap[data-place="above"]::before { bottom: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-left: none; border-top: none; } +.pcap[data-place="side-right"]::before { left: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-right: none; border-top: none; } +.pcap[data-place="side-left"]::before { right: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-left: none; border-bottom: none; } +.pcap-mark { position: absolute; height: ${Math.max(2, Math.round(3 * k))}px; background: ${pal.accent}; border-radius: ${Math.max(1, Math.round(2 * k))}px; opacity: 0; } +`; +} + +// --------------------------------------------------------------------------- +// THE DOM (self-contained: passed to page.evaluate by the build, called by Play). +// --------------------------------------------------------------------------- + +/** + * Mount the chips over the card page: `{ css, chips: [{ i, html }] }`, each + * laid out unplaced and hidden. Returns each one's size `[{ i, width, height }]`. + * @param {{ css?: string, chips?: Array<{ i: number, html: string }> } | null} arg + * @param {Document} [doc] + * @returns {Array<{ i: number, width: number, height: number }>} + */ +export function mountCaptions(arg, doc = document) { + doc.querySelectorAll("[data-post-fx-captions], style[data-post-fx-captions-css]").forEach((el) => el.remove()); + const chips = (arg && arg.chips) || []; + if (!chips.length) return []; + const style = doc.createElement("style"); + style.setAttribute("data-post-fx-captions-css", ""); + style.textContent = arg.css || ""; + doc.head.appendChild(style); + const layer = doc.createElement("div"); + layer.setAttribute("data-post-fx-captions", ""); + doc.body.appendChild(layer); + return chips.map((c) => { + const el = doc.createElement("div"); + el.className = "pcap"; + el.setAttribute("data-post-fx-caption", String(c.i)); + el.innerHTML = c.html; + layer.appendChild(el); + const b = el.getBoundingClientRect(); + return { i: c.i, width: Math.ceil(b.width), height: Math.ceil(b.height) }; + }); +} + +/** + * The phrase's geometry as the card is drawn now: `{ scope, from, to, avoid: + * [indices] }` → `{ card, word, lines, avoid }` (px boxes; `lines` the + * phrase's box per line, for its underline) or `{ error }` when a word is not + * drawn or is cut off the card. + * @param {{ scope: string, from: number, to: number, avoid?: number[] }} arg + * @param {Document} [doc] + * @returns {{ error: string } | { error?: undefined, card: Rect, word: Rect, lines: Rect[], avoid: Rect[], others: Rect[] }} + */ +export function measureCaptionWords(arg, doc = document) { + const rect = (el) => { + const b = el.getBoundingClientRect(); + return { x: b.left, y: b.top, width: b.width, height: b.height }; + }; + const card = doc.querySelector("[data-post-card]"); + if (!card) return { error: "the card is not drawn" }; + /** @type {Rect[]} */ + const lines = []; + for (let i = arg.from; i <= arg.to; i += 1) { + const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); + if (!el) return { error: `word ${i} is not on the card` }; + const clip = el.closest(".words, .ptext, .qtext"); + const cb = (clip || card).getBoundingClientRect(); + for (const r of Array.from(el.getClientRects())) { + if (r.width === 0) continue; + if (r.bottom > cb.bottom + 1 || r.top < cb.top - 1) return { error: "cut off the card (the text is longer than the card shows)" }; + const same = lines.find((l) => Math.abs(l.y - r.top) < r.height / 2); + if (same) { + const x1 = Math.max(same.x + same.width, r.right); + same.x = Math.min(same.x, r.left); + same.width = x1 - same.x; + same.height = Math.max(same.height, r.height); + } else lines.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + } + if (!lines.length) return { error: "the words are not drawn" }; + const x0 = Math.min(...lines.map((l) => l.x)); + const y0 = Math.min(...lines.map((l) => l.y)); + const x1 = Math.max(...lines.map((l) => l.x + l.width)); + const y1 = Math.max(...lines.map((l) => l.y + l.height)); + /** @type {Rect[]} */ + const avoid = []; + for (const i of arg.avoid || []) { + const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); + if (el) for (const r of Array.from(el.getClientRects())) if (r.width > 0) avoid.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + // Every other word drawn (any post on the card): a place hiding fewer of them is better. + /** @type {Rect[]} */ + const others = []; + const mine = new Set(Array.from({ length: arg.to - arg.from + 1 }, (_, k) => `${arg.scope}:${arg.from + k}`)); + for (const el of Array.from(doc.querySelectorAll("[data-w]"))) { + if (mine.has(el.getAttribute("data-w") || "")) continue; + for (const r of Array.from(el.getClientRects())) if (r.width > 0) others.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + return { card: rect(card), word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, lines, avoid, others }; +} + +/** + * Set the chips: `[{ i, x, y, place, notch, opacity, dx, dy, marks, mark }]` + * (`marks`: the underline's boxes under the phrase, `mark` their opacity); + * a chip not listed is hidden. `only`: "chip" | "mark" draws just that layer + * (the build shoots them apart), absent both. + * @param {{ list?: Array<Record<string, any>>, only?: string } | null} arg + * @param {Document} [doc] + */ +export function setCaptionState(arg, doc = document) { + const list = (arg && arg.list) || []; + const only = arg && arg.only; + const layer = doc.querySelector("[data-post-fx-captions]"); + if (!layer) return; + layer.querySelectorAll(".pcap-mark").forEach((el) => el.remove()); + for (const el of Array.from(layer.querySelectorAll(".pcap"))) { + const c = list.find((x) => String(x.i) === el.getAttribute("data-post-fx-caption")); + if (!c || only === "mark") { + el.style.opacity = "0"; + continue; + } + el.setAttribute("data-place", c.place); + el.style.setProperty("--notch", `${c.notch}px`); + el.style.transform = `translate(${Math.round(c.x + (c.dx || 0))}px, ${Math.round(c.y + (c.dy || 0))}px)`; + el.style.opacity = String(c.opacity); + } + if (only === "chip") return; + for (const c of list) { + for (const l of c.marks || []) { + const m = doc.createElement("div"); + m.className = "pcap-mark"; + m.setAttribute("data-post-fx-caption-mark", String(c.i)); + const h = Math.max(2, Math.round(l.height * 0.07)); + m.style.left = `${Math.round(l.x)}px`; + m.style.top = `${Math.round(l.y + l.height - h * 0.4)}px`; + m.style.width = `${Math.round(l.width)}px`; + m.style.opacity = String(c.mark ?? c.opacity); + layer.appendChild(m); + } + } +} + +/** + * The card page's palette, read off its drawn styles (Play has the page, not the + * deck's render): `{ bg, fg, muted, accent }` as #rrggbb. + * @param {Document} [doc] + * @returns {Record<string, string>} + */ +export function paletteOfDoc(doc = document) { + const hex = (c) => { + const m = /rgba?\(([^)]+)\)/.exec(String(c || "")); + if (!m) return null; + const [r, g, b] = m[1].split(",").map((v) => Math.round(Number(v))); + return `#${[r, g, b].map((v) => Math.max(0, Math.min(255, v || 0)).toString(16).padStart(2, "0")).join("")}`; + }; + const view = doc.defaultView; + if (!view || !doc.body) return {}; + const probe = (cls) => { + const el = doc.createElement("span"); + el.className = cls; + doc.body.appendChild(el); + const c = view.getComputedStyle(el).color; + el.remove(); + return hex(c); + }; + const st = view.getComputedStyle(doc.body); + const out = { bg: hex(st.backgroundColor), fg: hex(st.color), accent: probe("mention"), muted: probe("pdate") }; + return Object.fromEntries(Object.entries(out).filter(([, v]) => v)); +} diff --git a/umtool/report-to-video/post-caption.test.mjs b/umtool/report-to-video/post-caption.test.mjs @@ -0,0 +1,116 @@ +// A post item's CAPTION (post-caption.mjs): its validation, its time (at, the +// take's words, the reading estimate), its span (waiting for a word zoom), and +// its place (never over a word read while it is up). +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + CAPTION_IN, CAPTION_OUT, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, captionSpan, captionTimes, cardWordTimes, placeCaption, +} from "./post-caption.mjs"; +import { validatePostFx, wordZoomTimes } from "./word-zoom.mjs"; + +const TEXT = "I'm ignoring my broken bones so my training can continue. I have achieved Fudōshin. Its amazing."; +const base = (o = {}) => ({ type: "post", id: "p1", post: "s/1", platform: "x", author: "S", handle: "s", date: "2026-10-20T19:46:00.000Z", text: TEXT, ...o }); +const cap = (o = {}) => ({ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin — \"immovable mind\"", ...o }); +const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 10, script: TEXT, ...o }); + +test("validation: a caption's keys, its match, its text, its knobs -- in the build's words", () => { + assert.deepEqual(validatePostFx(base({ fx: [cap()] })), []); + const errs = validatePostFx(base({ fx: [cap({ match: "Fudoshinn", text: "", place: "left", hold: 0.1, scale: 2 })] })); + assert.ok(errs.some((e) => /fx\[0\]\.scale is not a caption key/.test(e)), errs.join("\n")); + assert.ok(errs.some((e) => /match "Fudoshinn" is not in the post's words/.test(e))); + assert.ok(errs.some((e) => /\.text must be what the caption says/.test(e))); + assert.ok(errs.some((e) => /\.place must be one of below, above, side/.test(e))); + assert.ok(errs.some((e) => /\.hold must be 0.5–10 seconds/.test(e))); + assert.ok(validatePostFx(base({ fx: [cap({ text: "x".repeat(161) })] })).some((e) => /longer than 160 characters/.test(e))); +}); + +test("a caption is not a word zoom: wordZoomTimes gives it no time and no error", () => { + assert.deepEqual(wordZoomTimes(base({ fx: [cap()] })), [{ i: 0, kind: "caption" }]); +}); + +test("WHEN: at wins; un-narrated, the reading estimate (1 s + 3 words a second)", () => { + assert.deepEqual(captionTimes(base({ fx: [cap({ at: 2.25 })] })), [{ i: 0, t: 2.25, source: "at" }]); + // "Fudōshin." is the card's 14th word (index 13): 1 + 13/3. + assert.deepEqual(captionTimes(base({ fx: [cap()] })), [{ i: 0, t: 5.33, source: "estimate" }]); +}); + +test("WHEN: narrated with no word timings -- the read spread over its script by characters, on the item's clock", () => { + const e = base({ narration: { script: TEXT, takes: [take()], lead: 0.5, rate: 1.25 }, fx: [cap()] }); + const [t] = captionTimes(e); + assert.equal(t.source, "estimate"); + // 72 characters of 101 before it, over 10 ÷ 1.25 = 8 s, from 0.5. + const before = TEXT.indexOf("Fudōshin"); + const n = TEXT.split(/\s+/).reduce((a, w) => a + w.length + 1, 0); + assert.equal(t.t, Math.round((0.5 + (before / n) * 8) * 1000) / 1000); + // Each card word has a time, in order. + const wt = cardWordTimes(e); + assert.equal(wt.times.length, TEXT.split(/\s+/).length); + for (let k = 1; k < wt.times.length; k += 1) assert.ok(wt.times[k] >= wt.times[k - 1]); +}); + +test("WHEN: narrated and timed -- the matched word's start in the take (lead + start ÷ rate)", () => { + const words = TEXT.split(" ").map((w, i) => ({ w, start: i * 0.5, end: i * 0.5 + 0.4 })); + const e = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4, rate: 1.25 }, fx: [cap()] }); + assert.deepEqual(captionTimes(e), [{ i: 0, t: 5.6, source: "words" }]); +}); + +test("the span: in over its lead, held from the word, out; it waits for a word zoom it would be up with; it ends by the item's end", () => { + const s = captionSpan(cap(), 4, {}); + assert.deepEqual(s, { t0: 3.85, t1: 3.85 + CAPTION_IN, t2: 6.5, t3: 6.5 + CAPTION_OUT, at: 4, waited: null }); + const w = captionSpan(cap(), 4, { zooms: [{ i: 0, t0: 3.5, t1: 4, t2: 5.2, t3: 5.6 }] }); + assert.equal(w.t0, 5.6); + assert.equal(w.waited, 0); + assert.equal(Math.round((w.t2 - w.t0) * 100) / 100, 2.65); + const short = captionSpan(cap(), 4, { end: 5 }); + assert.equal(short.t3, 5); + assert.match(captionSpan(cap(), 4.9, { end: 5 }).error, /at or after the item's 5 s/); + assert.equal(captionOpacityAt(s, 3.8), 0); + assert.equal(captionOpacityAt(s, 5), 1); + assert.ok(captionOpacityAt(s, 6.6) > 0 && captionOpacityAt(s, 6.6) < 1); + assert.equal(captionSlideAt(s, 3.85), 1); + assert.equal(captionSlideAt(s, 4.5), 0); +}); + +test("the plan: the words read while it is up are what it must not cover; two up at once are refused", () => { + const plan = captionPlan(base({ fx: [cap({ at: 2 })] })); + assert.equal(plan.length, 1); + assert.deepEqual([plan[0].scope, plan[0].from, plan[0].to], ["post", 13, 13]); + // Up 1.85–4.85 s (± 0.25), the words read at 1 s + 3 a second: words 2..12 -- never the phrase itself. + assert.deepEqual(plan[0].avoid, [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + assert.throws(() => captionPlan(base({ fx: [cap({ at: 2 }), cap({ at: 3, match: "amazing." })] })), /captions 1 and 2 are up at once/); +}); + +test("THE PLACE: below by default; a place over a word read while it is up is passed over; side when neither fits; fewest words hidden", () => { + const bounds = { x: 0, y: 0, width: 800, height: 600 }; + const word = { x: 300, y: 300, width: 100, height: 40 }; + const chip = { width: 240, height: 60 }; + const below = placeCaption({ word, chip, bounds }); + assert.equal(below.place, "below"); + assert.deepEqual([below.x, below.y, below.covers], [230, 354, 0]); + assert.equal(below.notch, 120); + // The next line is read while it is up: above. + const next = { x: 100, y: 350, width: 600, height: 40 }; + const above = placeCaption({ word, chip, bounds, avoid: [next] }); + assert.equal(above.place, "above"); + assert.equal(above.y, 300 - 14 - 60); + // Both lines read: to the side. + const prev = { x: 100, y: 250, width: 600, height: 40 }; + const side = placeCaption({ word: { ...word, x: 100 }, chip, bounds, avoid: [next, prev] }); + assert.equal(side.place, "side-right"); + assert.equal(side.covers, 0); + // Nothing is clear: the one covering least, and it says so. + const all = placeCaption({ word, chip, bounds: { x: 0, y: 200, width: 800, height: 250 }, avoid: [next, prev, { x: 0, y: 300, width: 300, height: 40 }, { x: 400, y: 300, width: 400, height: 40 }] }); + assert.ok(all.covers >= 1); + // Clear of the read either way: the place hiding fewer of the card's other words. + const fewer = placeCaption({ word, chip, bounds, others: [{ x: 200, y: 360, width: 400, height: 40 }] }); + assert.equal(fewer.place, "above"); + // Kept inside the card: a phrase at the edge pulls the chip in, the notch still under the phrase. + const edge = placeCaption({ word: { x: 700, y: 300, width: 80, height: 40 }, chip, bounds }); + assert.equal(edge.x, 800 - 240); + assert.equal(edge.notch, Math.min(240 - 24, 740 - 560)); +}); + +test("the chip's markup: the part before the dash bold, every character escaped, CJK kept", () => { + assert.equal(captionInnerHtml("不動心 · fudōshin — \"immovable mind\""), "<b>不動心 · fudōshin</b><span class=\"pcap-rest\"> — &quot;immovable mind&quot;</span>"); + assert.equal(captionInnerHtml("<b>x</b>"), "&lt;b&gt;x&lt;/b&gt;"); +}); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -25,6 +25,7 @@ import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.mjs"; import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs"; import { sceneEntry } from "./post-media-scene.mjs"; +import { CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; @@ -68,7 +69,7 @@ export function stepCaptions(step, cues) { * * @returns {string[]} */ -export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null }) { +export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, captionFx = [] }) { const fps = render.fps ?? 30; const T = plan.total; const inputs = []; @@ -124,6 +125,29 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render parts.push(`[${cur}][wz${zi}]overlay=x=${region.x}:y=${region.y}:eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`); cur = next; }); + // CAPTIONS (post-caption.mjs): each chip shot alone on a clear page, laid over the card while it is up -- fading + // and sliding in toward its phrase, the underline fading under the words, both tracking the words as the card + // pans -- after the zooms (a caption waits for one to be out), before the attachments (it stays on the card). + captionFx.forEach((c, ci) => { + const { span } = c; + const D = Math.max(1 / fps, span.t3 - span.t0); + const track = (axis) => trackExpr(c.track ?? [], axis); + const layer = (shot, label, slide) => { + const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", shot.file]); + parts.push( + `[${k}:v]format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` + + `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[${label}]`, + ); + const left = span.t1 > span.t0 ? `pow(1-clip((t-${num(span.t0)})/${num(span.t1 - span.t0)},0,1),3)` : "0"; + const sx = slide && slide.x ? `+${num(slide.x)}*${left}` : ""; + const sy = slide && slide.y ? `+${num(slide.y)}*${left}` : ""; + const next = `b${++n}`; + parts.push(`[${cur}][${label}]overlay=x='${shot.x}${track("dx")}${sx}':y='${shot.y}${track("dy")}${sy}':eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`); + cur = next; + }; + if (c.mark) layer(c.mark, `cpm${ci}`, null); + layer(c.chip, `cpc${ci}`, c.slide); + }); const audio = []; const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif"); plan.steps.forEach((step, si) => { @@ -220,6 +244,21 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render ]; } +/** + * A caption's track (`[{ t, dx, dy }]`: how far its phrase has moved from where + * it was placed, from item second t) as an ffmpeg term of `t` to add to its + * x or y ("" when it never moves). + */ +export function trackExpr(track, axis) { + const steps = []; + for (const p of track) if (!steps.length ? p[axis] !== 0 : p[axis] !== steps[steps.length - 1].v) steps.push({ t: p.t, v: p[axis] }); + if (!steps.length) return ""; + // Nested from the last change back: before each change, what held until it. + let e = String(steps[steps.length - 1].v); + for (let k = steps.length - 1; k >= 0; k -= 1) e = `if(lt(t,${num(steps[k].t)}),${k ? steps[k - 1].v : 0},${e})`; + return `+(${e})`; +} + async function loadChromium() { let mod; try { @@ -237,7 +276,7 @@ async function loadChromium() { * stack layout. The page is a file beside them, so its faces and the parent * shot load from disk (an about:blank page may not read file: urls). */ -export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0 }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, captions = [] }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -279,6 +318,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la } await ctx.close(); if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow }); + if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow }); } finally { await browser.close(); } @@ -415,17 +455,98 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU } /** + * Each CAPTION's shots and place (post-caption.mjs): on the card page as it is + * drawn when the caption is fully in (read-follow's state at its t1), the + * phrase measured -- refused when it is cut off the card -- and the words read + * while it is up; the chip placed by them (placeCaption: never covering one), + * then shot alone on a clear page (the chip with its notch; the underline + * apart, as it does not slide). Following, the phrase is measured frame by + * frame over the caption's span: its `track`, which the chip rides. + * `captions`: captionPlan's. Returns `[{ ...caption, chip, mark, slide, track, placed }]`. + */ +export async function shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction = null, follow = null }) { + const fps = render.fps ?? 30; + const k = box.height / 1080; + const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); + const page = await ctx.newPage(); + const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])); + const out = []; + try { + const file = path.join(dir, "caption.html"); + await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null }), "utf8"); + await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); + await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); + const sizes = await page.evaluate(mountCaptions, { css: captionCss({ height: box.height, palette: render.palette }), chips: captions.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })) }); + await page.evaluate(() => document.fonts.ready.then(() => true)); + const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; + const stateAt = async (s) => { + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); + }; + const inset = Math.round(10 * k); + for (const c of captions) { + await stateAt(c.span.t1); + const geo = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: c.avoid }); + if (geo.error) throw new Error(`${entry.id}: caption ${c.i + 1}: the phrase is ${geo.error}`); + const size = sizes.find((x) => x.i === c.i); + const bounds = { x: geo.card.x + inset, y: geo.card.y + inset, width: geo.card.width - 2 * inset, height: geo.card.height - 2 * inset }; + const placed = placeCaption({ word: geo.word, chip: size, bounds, place: c.place, avoid: geo.avoid, others: geo.others, gap: Math.round(16 * k) }); + // The phrase's track while it is up (a pan moves it): measured each frame, kept where it changes. + const track = []; + if (follow) { + for (let f = Math.floor(c.span.t0 * fps); f <= Math.ceil(c.span.t3 * fps); f += 1) { + await stateAt(f / fps); + const g = await page.evaluate(measureCaptionWords, { scope: c.scope, from: c.from, to: c.to, avoid: [] }); + if (g.error) continue; + track.push({ t: r3(f / fps), dx: Math.round(g.word.x - geo.word.x), dy: Math.round(g.word.y - geo.word.y) }); + } + await stateAt(c.span.t1); + } + // Shot alone: the card hidden, the page clear. + await page.evaluate(() => { + const st = document.createElement("style"); + st.setAttribute("data-pcap-solo", ""); + st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-captions]) { visibility: hidden !important; }"; + document.head.appendChild(st); + }); + const pad = Math.round(40 * k); + const clipOf = (r) => { + const x = Math.max(0, Math.floor(r.x - pad)); + const y = Math.max(0, Math.floor(r.y - pad)); + return { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width + pad) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height + pad) - y) }; + }; + const state = { i: c.i, x: placed.x, y: placed.y, place: placed.place, notch: placed.notch, opacity: 1, marks: geo.lines, mark: 1 }; + await page.evaluate(setCaptionState, { list: [state], only: "chip" }); + const chipClip = clipOf(placed); + const chip = { file: path.join(dir, `caption-${c.i}.png`), x: chipClip.x, y: chipClip.y }; + await page.screenshot({ path: chip.file, clip: chipClip, omitBackground: true }); + await page.evaluate(setCaptionState, { list: [state], only: "mark" }); + const markClip = clipOf({ x: geo.word.x, y: geo.word.y + geo.word.height * 0.6, width: geo.word.width, height: geo.word.height * 0.6 }); + const mark = { file: path.join(dir, `caption-${c.i}-mark.png`), x: markClip.x, y: markClip.y }; + await page.screenshot({ path: mark.file, clip: markClip, omitBackground: true }); + await page.evaluate(setCaptionState, { list: [] }); + await page.evaluate(() => document.querySelectorAll("style[data-pcap-solo]").forEach((el) => el.remove())); + const d = slideDir(placed.place); + out.push({ ...c, chip, mark, slide: { x: d.x * CAPTION_SLIDE * k, y: d.y * CAPTION_SLIDE * k }, track, placed: { ...placed, word: geo.word, covers: placed.covers } }); + } + } finally { + await ctx.close(); + } + return out; +} + +/** * A post item's word zooms, resolved for the build: `[{ i, scope, from, to, * scale, highlight, span }]`, each on its time (wordZoomTimes) -- refused in * the build's words when one has no time, or two are up at once. */ export function postZoomPlan(entry, render, total = Infinity) { const fx = Array.isArray(entry?.fx) ? entry.fx : []; - if (!fx.length) return []; + if (!fx.some((f) => f?.kind === "word-zoom")) return []; const times = wordZoomTimes(entry, render); const bad = times.filter((t) => t.error); if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); - const zooms = fx.map((f0, i) => { + // Its captions (post-caption.mjs) are timed and drawn apart: only the word zooms here. + const zooms = fx.flatMap((f0, i) => (f0?.kind === "word-zoom" ? [[f0, i]] : [])).map(([f0, i]) => { const f = resolveWordZoom(f0); const m = findMatch(targetTextOf(entry, f.target), f.match, f.occurrence); return { i, scope: targetScope(f.target), from: m.from, to: m.to, scale: f.scale, highlight: f.highlight === false ? null : f.highlight, t: times[i].t, source: times[i].source, span: zoomSpan(f0, times[i].t) }; @@ -491,7 +612,9 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); const zoomPlan = postZoomPlan(entry, render, plan.total); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total }); + // Its captions (post-caption.mjs): each waits for a zoom it would be up with, and is gone by the media phase (a stack card). + const capPlan = captionPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration ?? undefined }); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, captions: capPlan }); // NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it // is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note). if (cards.inView?.length) { @@ -522,7 +645,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg }); narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) }; } - const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null }); + const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, captionFx: cards.captions ?? [] }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { @@ -532,13 +655,14 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box await rename(tmp, seg); // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides). if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); - await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); + await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, moves: c.track.filter((p, k, a) => k && (p.dx !== a[k - 1].dx || p.dy !== a[k - 1].dy)).length })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8"); emit("note", { message: narration ? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)` : `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`, }); if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` }); + for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after word zoom ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.place} the phrase${c.placed.covers ? ` -- WARNING: it covers ${c.placed.covers} word(s) read while it is up (no place by the phrase is clear: set its place, hold or at)` : ""}` }); for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` }); return seg; } diff --git a/umtool/report-to-video/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs @@ -31,8 +31,10 @@ import { cardText, contextText, parentsOf } from "./post-item.mjs"; import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; +import { captionErrors } from "./post-caption.mjs"; -export const POST_FX_KINDS = Object.freeze(["word-zoom"]); +// A post's effects: a word zoom, and a CAPTION (post-caption.mjs: a chip explaining a phrase as it is read). +export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption"]); export const POST_FX_MAX = 8; export const WORD_ZOOM_EASES = Object.freeze(["out", "inOut", "snap"]); export const WORD_ZOOM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.5, hold: 1.2, scale: 2, ease: "inOut", highlight: "#ffd84d" }); @@ -136,6 +138,7 @@ export function validatePostFx(e) { const fw = `${w}[${i}]`; if (!isObj(fx)) return errors.push(`${fw} must be an object`); if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`); + if (fx.kind === "caption") return errors.push(...captionErrors(e, fx, fw)); for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a word-zoom key (${[...KEYS].join(", ")})`); const target = fx.target ?? "post"; const text = typeof target === "string" ? targetTextOf(e, target) : null; @@ -281,7 +284,7 @@ export function scriptWordTimes(script, recognized) { * @param {Record<string, any>} entry * @param {Record<string, any>} [render] * @param {Record<string, any> | null} [schedule] - * @returns {Array<{ i: number, t?: number, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>} + * @returns {Array<{ i: number, t?: number, kind?: string, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>} */ export function wordZoomTimes(entry, render = undefined, schedule = undefined) { const list = Array.isArray(entry?.fx) ? entry.fx : []; @@ -290,6 +293,8 @@ export function wordZoomTimes(entry, render = undefined, schedule = undefined) { // `schedule`: the item's narration schedule when the caller has it (Play: the plan's), else worked out here. const sch = narrated ? schedule ?? narrationSchedule(entry, render) : null; return list.map((fx0, i) => { + // Another effect (a caption, post-caption.mjs) is timed by its own module: no time here, and no error. + if (isObj(fx0) && fx0.kind !== "word-zoom" && POST_FX_KINDS.includes(fx0.kind)) return { i, kind: fx0.kind }; if (!isObj(fx0) || fx0.kind !== "word-zoom") return { i, error: "not a word zoom" }; const fx = resolveWordZoom(fx0); if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" };