Archilyzer · Source

archilyzer

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

commit db88a46a46692025f68a7be568fa82d6a533efe9
parent 19d582161cdc5b974df1c672b31fefa8f0743d51
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 17:36:16 -0500

umtool: a post item's PROGRESS BAR -- a thin bar along the card's foot, under its counts row, that fills with the item's read over its REAL seconds (a part read faster by a tempo step moves it faster; it never jumps), ticked at each part's start; render.posts.progress auto|on|off (auto: a read of 60 s or more as it plays), an item's progress= over it; the render, Play and the bench; in the segment key only for an item that draws it (operator, 4 Nov: "we might want a per-clip progress bar in the engine specifically for clips like this")

post-progress.mjs: progressPlan (the read's span from the narration schedule, an item with no read its own length;
the ticks; a stack card's until), progressAt (linear), the fade in to the read's start; the look and the DOM
(mountProgress, measureProgressPlace -- judged over the read's start, middle and end on the words as SEEN, clipped to
their window; the counts row only when it is the card's foot; short of the clock on its line; over a word, just
under the card -- setProgressState, the fill clipped at its leading edge). The build shoots its track and its fill
once each on a clear page (shootProgress) and lays them over the card before the clock, the fill's alpha clipped
frame by frame (progressFilters: geq on T), faded in, gone at until. Play (PostItemPlayer `progress`, from playView's
postProgress) and the bench mount the same bar; data-post-progress carries the fill for the e2e. Drawn over the
card, never in it: readInViewErrors never counts it. postFxKeyFields appends `progress` (its plan and
POST_PROGRESS_DRAW_V) only for an item that draws it. The validators (an item's progress, render.posts.progress),
updatePostProgressRender, `umtool posts progress <p> [auto|on|off|default]` (bare: which items draw it), set-item
progress=on|off|auto|default.

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

Diffstat:
Mumtool/components/projects/PostBench.tsx | 5++++-
Mumtool/components/projects/review/PlayCut.tsx | 3+++
Mumtool/components/projects/review/PostItemPlayer.tsx | 53++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/manifest.mjs | 24+++++++++++++++++++++++-
Mumtool/lib/report/playView.mjs | 6+++++-
Mumtool/lib/report/postsCli.mjs | 42++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-item.mjs | 3+++
Aumtool/report-to-video/post-progress.mjs | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-progress.test.mjs | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-redact.mjs | 4+++-
Mumtool/report-to-video/post-render.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
12 files changed, 564 insertions(+), 11 deletions(-)

diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -20,6 +20,7 @@ import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; import { captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; import { slamLandings, slamSpan, slamTimes } from "umtool-report-to-video/post-slam"; import { clockPlan } from "umtool-report-to-video/post-clock"; +import { progressPlan } from "umtool-report-to-video/post-progress"; import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // --------------------------------------------------------------------------- @@ -124,6 +125,8 @@ export default function PostBench({ ); const shown = useMemo(() => panelEntry(sceneEntry(entry, scene), render) as Entry, [entry, scene, render]); const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, scene: conversation, mediaScene: conversation ? null : scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene, conversation]); + // Its progress bar (post-progress.mjs): the read's span and its parts' ticks. + const progressP = useMemo(() => progressPlan(shown, render, plan as never), [shown, render, plan]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -330,7 +333,7 @@ export default function PostBench({ </span> </div> <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}> - <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} clock={clockPlan(shown, render, before)} /> + <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} clock={clockPlan(shown, render, before)} progress={progressP} /> <ComboBadge project={project} entry={shown} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} /> </div> <div className="flex items-center gap-2 text-[12px]"> diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -122,6 +122,8 @@ export type PlayEntry = { /** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */ post?: Record<string, unknown> & { id: string }; postPlan?: PostPlan; + /** Its progress bar (post-progress.mjs progressPlan), or null. */ + postProgress?: { from: number; to: number; ticks: number[]; until: number; mode: string } | null; /** Its clock (post-clock.mjs clockPlan), or null. */ postClock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; /** Its combo badge (post-combo.mjs): the attachment it repeats, its count, the knobs. */ @@ -860,6 +862,7 @@ export default function PlayCut({ uncensored={uncensored} scene={postNow.entry.postScene ?? null} clock={postNow.entry.postClock ?? null} + progress={postNow.entry.postProgress ?? null} joinFrom={(() => { // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended. const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null; diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -13,6 +13,7 @@ import { CAPTION_SLIDE, captionCss, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, measureCaptionWords, mountCaptions, paletteOfDoc, placeCaption, setCaptionState, slideDir, } from "umtool-report-to-video/post-caption"; import { clockCss, clockFace, clockHtml, clockStateAt, measureClockPlace, mountClock, setClockState } from "umtool-report-to-video/post-clock"; +import { measureProgressPlace, mountProgress, progressAt, progressCss, progressHeight, progressOpacityAt, setProgressState } from "umtool-report-to-video/post-progress"; import { SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, setSlamState, slamCss, slamHits, slamLayout, slamListAt, slamPlan, slamShakeAt, slamSize, slamVars, } from "umtool-report-to-video/post-slam"; @@ -56,6 +57,9 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar // --------------------------------------------------------------------------- type Rect = { x: number; y: number; width: number; height: number }; +/** A progress bar's plan (post-progress.mjs progressPlan): the read's span on the item's clock, the parts' ticks. */ +export type ProgressPlan = { from: number; to: number; ticks: number[]; until: number; mode: string }; + /** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */ /** A caption of the item, placed in its card page: its span, its place, the phrase's box and lines when placed. */ type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: NonNullable<ReturnType<typeof placeCaption>>; base: Rect; lines: Rect[] }; @@ -487,7 +491,7 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A } export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, progress = null, }: { project: string; take?: string | null; @@ -511,6 +515,8 @@ export default function PostItemPlayer({ clock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; /** THE JOIN (post-join.mjs): the item before (its entry and plan) -- this one opens on it as it ended. */ joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null; + /** Its progress bar (post-progress.mjs progressPlan), or none. */ + progress?: ProgressPlan | null; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -770,10 +776,44 @@ export default function PostItemPlayer({ }, [clock, box.height, follow, plan.total]); const placeClockRef = useRef(placeClock); placeClockRef.current = placeClock; + // ---- the progress bar, live (post-progress.mjs): mounted and placed as the build places it, set each tick ---- + const [progAt, setProgAt] = useState<{ x: number; y: number; width: number } | null>(null); + const placeProgress = useCallback(() => { + const doc = readFrame.current?.contentDocument; + if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return; + if (!progress) { + mountProgress(null, doc); + setProgAt(null); + return; + } + const k = box.height / 1080; + const h = mountProgress({ css: progressCss({ height: box.height, palette: paletteOfDoc(doc) }), ticks: progress.ticks }, doc) ?? progressHeight(box.height); + const route = follow && doc.querySelector("[data-post-flow]") ? followPath(follow, measureFollow(doc)) : null; + // Judged over the read (its end, start and middle), as the build judges it: the place over fewest words. + const states = follow && route ? [plan.total, 0, plan.total / 2] : [0]; + const cb = clockRect.current ? { x: clockRect.current.x + 240 * k, y: clockRect.current.y, width: clockRect.current.width - 240 * k, height: clockRect.current.height } : null; + let first: ReturnType<typeof measureProgressPlace> = null; + const sums: number[] = []; + for (const st of states) { + if (follow && route) applyFollowState(followStateAt(follow, route, st), doc); + const l = measureProgressPlace({ height: h, inset: Math.round(22 * k), avoid: cb ? [cb] : [], fixed: first?.tries ?? null }, doc); + if (!first) first = l; + (l?.counts ?? []).forEach((c: number, i: number) => (sums[i] = (sums[i] ?? 0) + c)); + } + if (follow && route) applyFollowState(followStateAt(follow, route, 0), doc); + const best = first ? first.tries.map((t: { x: number; y: number; width: number }, i: number) => ({ ...t, covers: sums[i] ?? 0 })).sort((a: { covers: number }, b: { covers: number }) => a.covers - b.covers)[0] : null; + setProgAt(best ? { x: best.x, y: best.y, width: best.width } : null); + }, [progress, box.height, follow, plan.total]); + const placeProgressRef = useRef(placeProgress); + placeProgressRef.current = placeProgress; + useEffect(() => { + placeProgress(); + }, [placeProgress]); const onFrameLoad = useCallback(() => { let tries = 0; const tick = () => { placeClockRef.current(); + placeProgressRef.current(); if (measure() || tries++ > 50) return; setTimeout(tick, 100); }; @@ -892,6 +932,15 @@ export default function PostItemPlayer({ const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity; setClockState(clockSt && clockAt && s < until ? { ...clockAt, st: clockSt } : null, doc); }, [clockSt, clockAt, s, layout.mode, plan.steps]); + // The bar's fill: the read's real seconds (a part read faster moves it faster), gone in a stack card's media phase. + const progFrac = progress ? progressAt(progress, s) : null; + useEffect(() => { + const doc = readFrame.current?.contentDocument; + if (!doc || !progress) return; + const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity; + const op = s < until ? progressOpacityAt(progress, s) : 0; + setProgressState(progAt && progFrac !== null ? { ...progAt, frac: progFrac, opacity: op } : null, doc); + }, [progress, progAt, progFrac, s, layout.mode, plan.steps]); 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 ( @@ -916,6 +965,8 @@ export default function PostItemPlayer({ data-post-slam-fx={slamsUp.length ? slamsUp.map((p) => String(p.i)).join(" ") : undefined} data-post-slam-where={slams.length ? slams.map((p) => p.where).join(" ") : undefined} data-post-slam-landed={slamsUp.length ? String(slamsUp.reduce((a, p) => a + p.span.landings.filter((L) => L <= s).length, 0)) : undefined} + data-post-progress={progFrac !== null ? String(Math.round(progFrac * 1000) / 1000) : undefined} + data-post-progress-place={progress && progAt ? `${Math.round(progAt.x)},${Math.round(progAt.y)},${Math.round(progAt.width)}` : undefined} data-post-clock={clockSt ? `${clockSt.time} ${clockSt.date}` : undefined} data-post-clock-mode={clockSt ? clockSt.mode : undefined} data-post-clock-gap={clockSt && clockSt.gapOpacity > 0 ? clockSt.gap : undefined} diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2356,7 +2356,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i } /** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ -export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ @@ -3079,6 +3079,28 @@ export async function updatePostClock(dir, patch, { token = null } = {}) { }); } +/** + * THE CUT's PROGRESS BAR default (`render.posts.progress`, post-progress.mjs): "auto" (a read of 60 s or more), + * "on", "off"; null back to the default (off). Validated with the build's check. + * + * @param {string} dir + * @param {"auto" | "on" | "off" | null} mode + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostProgressRender(dir, mode, { token = null } = {}) { + return structural(dir, "post-progress", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + if (mode === null || mode === undefined) delete posts.progress; + else posts.progress = mode; + if (Object.keys(posts).length) m.render.posts = posts; + else delete m.render.posts; + const errors = validatePostsRender(m.render); + if (errors.length) throw new StructureRefused(errors); + return { progress: posts.progress ?? null }; + }); +} + // ---- the slur filter (post-slurs.mjs; `umtool posts slurs`) --------------- /** diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -17,6 +17,7 @@ import { dateKeyLabel } from "./playCut.mjs"; import { panelEntry, postDay, postItemPlan } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { clockPlan } from "umtool-report-to-video/post-clock"; +import { progressPlan } from "umtool-report-to-video/post-progress"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; @@ -52,6 +53,7 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu const day = postDay(e.date); const dateKey = day ? Number(day.replace(/-/g, "")) : null; const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); + const plan = postItemPlan(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null }); return { id: e.id, type: "post", @@ -64,7 +66,9 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu post: panelEntry(sceneEntry(e, mediaScene), render), // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: the // posts its run left on screen (post-conversation.mjs: one conversation played as one scene) -- it wins the card. - postPlan: postItemPlan(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null }), + postPlan: plan, + // Its progress bar (post-progress.mjs): the read's span and its parts' ticks (Play lays a stack card's end). + postProgress: progressPlan(e, render, plan), // Its clock (post-clock.mjs): its post's time, run from the clock item before it. postClock: clockPlan(e, render, ctx?.prev ?? null), ...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}), diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -136,6 +136,7 @@ export const POSTS_USAGE = [ " or its CLOCK (add clock [--rewind auto|on|off] [--off]), or a SLAM (add slam --text \"不動心\" --match \"…\":", " a trailer-style title slam, a trailer hit per glyph) (umtool posts fx --help)", " umtool posts clock <project> [on|off|default] [--zone <IANA zone>] the cut's CLOCK default: each post's time on its card, run between items", + " umtool posts progress <project> [auto|on|off|default] the cut's PROGRESS BAR default (auto: a read of 60 s or more); an item's: set-item progress=", " 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.", @@ -478,6 +479,14 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con } return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str, off: flags.has("--off"), has: (f) => flags.has(f) }); } + if (verb === "progress") { + // THE CUT's PROGRESS BAR default (post-progress.mjs): render.posts.progress; bare, which items draw it. + if (!projectArg || flags.has("--help")) { + err(PROGRESS_USAGE); + return 2; + } + return await progressCommand(await projectOf(projectArg, root), words[2] ?? null, { json, out }); + } if (verb === "clock") { const { CLOCK_USAGE, clockCommand } = await import("./postFxCli.mjs"); if (!projectArg || flags.has("--help")) { @@ -731,6 +740,11 @@ export function postItemPatchOf(pairs) { if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw); else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v; else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k); + // Its progress bar (post-progress.mjs): on, off or auto (60 s of read or more); default: the cut's. + else if (k === "progress") { + if (!["on", "off", "auto", "default", ""].includes(v)) throw new CliError("progress= takes on, off, auto or default (the cut's)"); + out.progress = v === "default" || v === "" ? null : v; + } // Its media scene (post-media-scene.mjs): off (never in one), join (joins the scene beside it), auto (by its attachment). else if (k === "scene") { if (!["off", "join", "auto", "on", ""].includes(v) && !OFF.has(v)) throw new CliError("scene= takes off, join or auto"); @@ -941,6 +955,34 @@ async function resolveAttachments(patch, dir) { for (const r of patch.linksAdd ?? []) if (Array.isArray(r.media)) r.media = await fix(r.media); } +const PROGRESS_USAGE = [ + "usage: umtool posts progress <project> [auto|on|off|default] [--json]", + " THE CUT's PROGRESS BAR (render.posts.progress, post-progress.mjs): a thin bar along a card's foot that fills with", + " the item's read (its real seconds: a part read faster moves it faster), ticked at each part. auto: a read of 60 s", + " or more; default: off. One item's: umtool posts set-item <p> <item> progress=on|off|auto|default. Bare: which draw it.", +].join("\n"); + +/** `umtool posts progress <p> [mode]`: the cut's progress bar default, or the items that draw it. */ +async function progressCommand(project, mode, { json, out }) { + const { progressPlan, progressModeOf } = await import("umtool-report-to-video/post-progress"); + const { postItemPlan } = await import("umtool-report-to-video/post-item"); + if (mode !== null) { + if (!["auto", "on", "off", "default"].includes(mode)) throw new CliError("posts progress takes auto, on, off or default"); + const { updatePostProgressRender } = await import("./manifest.mjs"); + await withEditNotes(project, async () => updatePostProgressRender(project.dir, mode === "default" ? null : mode, { token: await manifestToken(project.dir) })); + } + const manifest = await readManifest(project.dir); + const render = manifest?.render ?? {}; + const items = (manifest?.timeline ?? []).filter((e) => e?.type === "post"); + const shown = items.flatMap((e) => { + const pp = progressPlan(e, render, postItemPlan(e, render)); + return pp ? [{ id: e.id, mode: progressModeOf(e, render), from: pp.from, to: pp.to, parts: pp.ticks.length + 1 }] : []; + }); + if (json) out(JSON.stringify({ ok: true, progress: render.posts?.progress ?? null, items: shown }, null, 2)); + else out([`progress bar: the cut's ${render.posts?.progress ?? "off (default)"}; ${shown.length} of ${items.length} post item(s) draw it`, ...shown.slice(0, 60).map((x) => ` ${x.id} ${(x.to - x.from).toFixed(1)} s of read, ${x.parts} part(s)${x.mode !== (render.posts?.progress ?? "off") ? ` (its own: ${x.mode})` : ""}`)].join("\n")); + return 0; +} + /** `posts set-item`: a post item's knobs, through updatePostItem (`fit=read[:linger]`: posts fit, on this item). */ async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread = true }) { const fitPair = pairs.find((p) => /^fit=/.test(p)); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -66,6 +66,7 @@ "./post-combo-render": "./post-combo-render.mjs", "./post-item": "./post-item.mjs", "./post-narration": "./post-narration.mjs", + "./post-progress": "./post-progress.mjs", "./post-censor": "./post-censor.mjs", "./post-media-scene": "./post-media-scene.mjs", "./post-redact": "./post-redact.mjs", diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -39,6 +39,7 @@ import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePos import { panelSchedule, validatePostThread } from "./post-thread.mjs"; import { joinLayerHtml, validatePostJoin, validatePostJoinRender } from "./post-join.mjs"; import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from "./post-link-visit.mjs"; +import { progressErrors } from "./post-progress.mjs"; import { validatePostMapRender } from "./post-branch-map.mjs"; import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; @@ -554,6 +555,8 @@ export function validatePostItem(e) { errors.push(...validatePostJoin(e)); // Its link visit (post-link-visit.mjs): false (none). errors.push(...validatePostLinkVisit(e)); + // Its progress bar (post-progress.mjs): auto, on or off (absent: the cut's). + errors.push(...progressErrors(e.progress, `timeline ${e?.id ?? "?"}.progress`)); return errors; } diff --git a/umtool/report-to-video/post-progress.mjs b/umtool/report-to-video/post-progress.mjs @@ -0,0 +1,248 @@ +// A POST ITEM's PROGRESS BAR (umtool/docs/report-video.md, "The progress bar"; operator, 4 Nov, a 6.5-minute post: +// "we might want a per-clip progress bar in the engine specifically for clips like this"). +// +// A thin bar along the card's foot -- under its counts row, inside the card -- that fills as the item's read goes: +// the READ's own seconds (the narration schedule: from the narrator's first word to the last), linear in real time, +// so a part read faster (a `tempo` step, postReread.mjs) moves it faster and it never jumps. Subtle ticks mark where +// each part of the read starts. An item with no read fills over its own length. +// +// render.posts.progress = "auto" | "on" | "off" // the cut's default (absent: off) +// entry.progress = "auto" | "on" | "off" // one item's (absent: the cut's) +// auto: on for a read of PROGRESS_AUTO_SECONDS (60 s) or more, as the item plays it (its rate counted) +// +// WHERE: drawn OVER the card, never in it (no data-w, no data-post-block): readInViewErrors never counts it. Its +// place is judged over the read (measureProgressPlace): the card's foot, under the counts row; never over a word, +// and short of the clock (post-clock.mjs) when that sits on the same line. Over a word anywhere, it moves just under +// the card's edge. +// +// Pure but for the DOM functions (mountProgress, measureProgressPlace, setProgressState), SELF-CONTAINED: the +// build passes them to a page to shoot its track and fill, Play and the bench call them on their frame. + +import { mixHex, rgbaOf } from "./post-item.mjs"; +import { partStartOnItem, pickedTake } from "./post-narration.mjs"; + +export const PROGRESS_MODES = Object.freeze(["auto", "on", "off"]); +/** auto: a read this long or longer (item seconds) draws the bar. */ +export const PROGRESS_AUTO_SECONDS = 60; +/** The bar fades in over this, ending as the read starts. */ +export const PROGRESS_FADE = 0.35; +/** Its drawing (bumped when its look changes: the segment key carries it). */ +export const POST_PROGRESS_DRAW_V = 1; +/** At most this many ticks (a read of more parts draws none). */ +export const PROGRESS_TICKS_MAX = 120; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r4 = (v) => Math.round(v * 10000) / 10000; + +/** Every reason an item's `progress` is refused. */ +export function progressErrors(v, where) { + if (v === undefined) return []; + return PROGRESS_MODES.includes(v) ? [] : [`${where} must be ${PROGRESS_MODES.join(", ")}`]; +} + +/** Every reason `render.posts.progress` is refused (post-redact.mjs validatePostsRender calls it). */ +export const validateProgressRender = (v) => progressErrors(v, "render.posts.progress"); + +/** The mode an item plays with: its own, else the cut's, else off. */ +export function progressModeOf(entry, render) { + if (PROGRESS_MODES.includes(entry?.progress)) return entry.progress; + const c = render?.posts?.progress; + return PROGRESS_MODES.includes(c) ? c : "off"; +} + +/** + * THE BAR's PLAN for post item `entry` (its plan, postItemPlan's): `{ from, to, ticks, until, mode }` -- it fills + * from item second `from` to `to` (the read; an item with none: 0 to its length), `ticks` each later part's start + * as a fraction of the bar, `until` when it goes (a stack card's media phase covers the card). Null: no bar. + * + * @param {Record<string, any>} entry + * @param {Record<string, any> | undefined} render + * @param {{ total: number, narration?: Record<string, any> | null, steps?: Array<Record<string, any>>, reading?: number }} plan + * @param {{ stack?: boolean }} [o] + */ +export function progressPlan(entry, render, plan, { stack = false } = {}) { + if (entry?.type !== undefined && entry.type !== "post") return null; + if (!plan || !fin(plan.total) || plan.total <= 0) return null; + const mode = progressModeOf(entry, render); + if (mode === "off") return null; + const sch = isObj(plan.narration) ? plan.narration : null; + const from = sch ? sch.at : 0; + const to = sch ? sch.at + sch.seconds : plan.total; + if (!(to > from)) return null; + if (mode === "auto" && !(sch && sch.seconds >= PROGRESS_AUTO_SECONDS)) return null; + const t = sch ? pickedTake(entry) : null; + const parts = Array.isArray(t?.parts) ? t.parts.filter((p) => fin(p?.start)) : []; + const ticks = parts.length > 1 && parts.length <= PROGRESS_TICKS_MAX + ? parts.slice(1).map((p) => r4((partStartOnItem(sch, p) - from) / (to - from))).filter((x) => x > 0.002 && x < 0.998) + : []; + const until = stack && Array.isArray(plan.steps) && plan.steps.length ? plan.steps[0].at : plan.total; + return { from: r4(from), to: r4(to), ticks, until: r4(until), mode }; +} + +/** How full the bar is at item second `s`, 0–1: linear in the read's real seconds. */ +export function progressAt(pp, s) { + if (!pp) return 0; + return Math.min(1, Math.max(0, (s - pp.from) / (pp.to - pp.from))); +} + +/** Its opacity at item second `s`: faded in over PROGRESS_FADE ending at the read's start, gone at `until`. */ +export function progressOpacityAt(pp, s) { + if (!pp || s >= pp.until) return 0; + const fade = Math.min(PROGRESS_FADE, pp.from); + return fade > 0 ? Math.min(1, Math.max(0, (s - (pp.from - fade)) / fade)) : 1; +} + +/** The fill's ffmpeg expression of `T` (seconds): the bar's width fraction, as progressAt. */ +export const progressExpr = (pp) => `clip((T-${pp.from})/${r4(pp.to - pp.from)},0,1)`; + +// --------------------------------------------------------------------------- +// THE LOOK, and the DOM (self-contained). +// --------------------------------------------------------------------------- + +/** The bar's height in px for a page `height` px tall. */ +export const progressHeight = (height = 1080) => Math.max(3, Math.round(5 * (height / 1080))); + +/** The bar's CSS for a page `height` px tall, in the card's palette. */ +export function progressCss({ height = 1080, palette = {} } = {}) { + const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; + const h = progressHeight(height); + const tick = Math.max(1, Math.round(1.5 * (height / 1080))); + return ` +[data-post-progress-layer] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 60; } +.pprog { position: absolute; left: 0; top: 0; height: ${h}px; border-radius: ${h}px; overflow: hidden; } +.pprog-track { position: absolute; inset: 0; background: ${rgbaOf(pal.fg, 0.13)}; } +.pprog-fill { position: absolute; inset: 0; background: linear-gradient(90deg, ${mixHex(pal.accent, pal.bg, 0.25)}, ${pal.accent}); box-shadow: 0 0 ${h * 2}px ${rgbaOf(pal.accent, 0.35)}; } +.pprog-tick { position: absolute; top: 0; bottom: 0; width: ${tick}px; margin-left: -${tick / 2}px; background: ${rgbaOf(pal.bg, 0.55)}; } +[data-post-progress-layer][data-part="track"] .pprog-fill { display: none; } +[data-post-progress-layer][data-part="fill"] .pprog-track { display: none; } +`; +} + +/** + * Mount the bar over the card page (`{ css, ticks }`), hidden. `part`: "track" or "fill" alone (the build shoots + * each), else both (Play). Returns the bar's element height. + * @param {{ css: string, ticks?: number[], part?: "track" | "fill" | null } | null} arg + * @param {Document} [doc] + */ +export function mountProgress(arg, doc = document) { + doc.querySelectorAll("[data-post-progress-layer], style[data-post-progress-css]").forEach((el) => el.remove()); + if (!arg) return null; + const style = doc.createElement("style"); + style.setAttribute("data-post-progress-css", ""); + style.textContent = arg.css || ""; + doc.head.appendChild(style); + const layer = doc.createElement("div"); + layer.setAttribute("data-post-progress-layer", ""); + if (arg.part) layer.setAttribute("data-part", arg.part); + const bar = doc.createElement("div"); + bar.className = "pprog"; + bar.setAttribute("data-post-progress", ""); + bar.style.opacity = "0"; + const ticks = (arg.ticks || []).map((f) => `<span class="pprog-tick" style="left:${(f * 100).toFixed(3)}%"></span>`).join(""); + bar.innerHTML = `<span class="pprog-track"></span><span class="pprog-fill" data-post-progress-fill=""></span>${ticks}`; + layer.appendChild(bar); + doc.body.appendChild(layer); + return Math.ceil(bar.getBoundingClientRect().height); +} + +/** + * Where the bar goes on the card as drawn: `{ x, y, width, height, place, covers, tries }` -- along the card's foot, + * under its own post's counts row (a threaded card's: the post's tile), inset from the card's rounded corners; its + * right end short of `avoid` boxes on its line (the clock). `fixed`: the places to judge (an earlier call's + * `tries`), only counted here -- placed once, judged over the read; else, over a word, just under the card's edge. + * @typedef {{ x: number, y: number, width: number, height: number, place: string }} ProgressPlace + * @param {{ height: number, inset: number, avoid?: Array<{ x: number, y: number, width: number, height: number }>, fixed?: ProgressPlace[] | null }} arg + * @param {Document} [doc] + * @returns {(ProgressPlace & { covers: number, tries: ProgressPlace[], counts: number[] }) | null} + */ +export function measureProgressPlace(arg, doc = document) { + const card = doc.querySelector("[data-post-card]"); + if (!card || !arg) return null; + const c = card.getBoundingClientRect(); + const h = arg.height; + // The words as SEEN: each clipped to its window (a following card's flow pans words past its window's edge, hidden). + const wins = new Map(); + const winOf = (el) => { + const w = el.closest("[data-post-words]"); + if (!w) return null; + if (!wins.has(w)) wins.set(w, w.getBoundingClientRect()); + return wins.get(w); + }; + const words = Array.from(doc.querySelectorAll("[data-w]")).flatMap((el) => { + const w = winOf(el); + return Array.from(el.getClientRects()).map((r) => (w ? { left: Math.max(r.left, w.left), right: Math.min(r.right, w.right), top: Math.max(r.top, w.top), bottom: Math.min(r.bottom, w.bottom) } : r)); + }).filter((r) => r.right - r.left > 0 && r.bottom - r.top > 0); + const hit = (r) => words.filter((w) => Math.min(r.x + r.width, w.right) - Math.max(r.x, w.left) > 0.5 && Math.min(r.y + r.height + 2, w.bottom) - Math.max(r.y - 2, w.top) > 0.5).length; + /** @type {ProgressPlace[]} */ + const tries = arg.fixed || (() => { + const radius = parseFloat((doc.defaultView || window).getComputedStyle(card).borderTopLeftRadius) || 0; + const side = Math.max(arg.inset, Math.round(radius * 0.9)); + const x = Math.round(c.left + side); + let right = Math.round(c.right - side); + const all = Array.from(card.querySelectorAll(".counts")); + const counts = card.querySelector('[data-thread-tile="post"] .counts') || all[all.length - 1] || null; + const cb0 = counts ? counts.getBoundingClientRect() : null; + // A counts row is the card's foot only when it sits at the foot (a threaded card's is a tile's, in its flow). + const cb = cb0 && cb0.height > 0 && c.bottom - cb0.bottom >= 0 && c.bottom - cb0.bottom <= Math.max(60, 3 * arg.inset) ? cb0 : null; + // Under the counts row: centred in the foot below it (else a little above the card's edge). + const foot = cb ? Math.round((cb.bottom + c.bottom) / 2 - h / 2) : Math.round(c.bottom - h - Math.max(6, arg.inset * 0.5)); + const y = Math.min(Math.round(c.bottom - h - 3), Math.max(foot, cb ? Math.round(cb.bottom + 2) : foot)); + for (const a of arg.avoid || []) { + if (a.y < y + h + 4 && a.y + a.height > y - 4 && a.x < right && a.x + a.width > x) right = Math.min(right, Math.round(a.x - arg.inset * 0.6)); + } + const width = Math.max(40, right - x); + const below = Math.round(c.bottom + Math.max(4, h)); + return [ + { x, y, width, height: h, place: "foot" }, + { x, y: below, width: Math.max(40, Math.round(c.right - side) - x), height: h, place: "under" }, + ]; + })(); + const looked = tries.map((t) => ({ ...t, covers: hit(t) })); + const best = looked.find((t) => !t.covers) || looked.slice().sort((a, b) => a.covers - b.covers)[0]; + return { ...best, tries: looked.map(({ covers: _c, ...t }) => t), counts: looked.map((t) => t.covers) }; +} + +/** + * Set the bar: `{ x, y, width, frac, opacity }` (frac progressAt's), or null to hide. The fill is clipped at its + * leading edge (as the build clips it), never squeezed. + * @param {{ x: number, y: number, width: number, frac: number, opacity?: number } | null} arg + * @param {Document} [doc] + */ +export function setProgressState(arg, doc = document) { + const el = doc.querySelector("[data-post-progress]"); + if (!el) return; + if (!arg) { + el.style.opacity = "0"; + return; + } + el.style.transform = `translate(${Math.round(arg.x)}px, ${Math.round(arg.y)}px)`; + el.style.width = `${Math.round(arg.width)}px`; + el.style.opacity = String(arg.opacity === undefined ? 1 : arg.opacity); + el.setAttribute("data-frac", String(Math.round(arg.frac * 1000) / 1000)); + const fill = el.querySelector("[data-post-progress-fill]"); + if (fill) fill.style.clipPath = `inset(0 ${((1 - Math.min(1, Math.max(0, arg.frac))) * 100).toFixed(3)}% 0 0)`; +} + +/** + * THE BAR's FILTERS for the build (post-render.mjs postSegmentArgs): the track and the fill (each a still the size of + * the bar, inputs `ti` and `fi`, looped over the item) laid over `inLabel` at `x, y` -- the fill's alpha clipped at + * its leading edge, frame by frame (geq on T: progressExpr), both faded in as the read starts and gone at `until`. + * Returns `{ chains, out }`. + * + * @param {{ ti: number, fi: number, inLabel: string, outLabel: string, x: number, y: number, pp: ReturnType<typeof progressPlan>, T: number }} o + */ +export function progressFilters({ ti, fi, inLabel, outLabel, x, y, pp, T }) { + const fade = Math.min(PROGRESS_FADE, pp.from); + const fadeIn = fade > 0 ? `,fade=t=in:st=${r4(pp.from - fade)}:d=${r4(fade)}:alpha=1` : ""; + const enable = pp.until < T - 1e-6 ? `:enable='lt(t,${pp.until})'` : ""; + return { + chains: [ + `[${ti}:v]format=rgba,setsar=1${fadeIn}[pgt]`, + `[${fi}:v]format=rgba,setsar=1,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='alpha(X,Y)*clip(W*${progressExpr(pp)}-X,0,1)'${fadeIn}[pgf]`, + `[${inLabel}][pgt]overlay=x=${x}:y=${y}${enable}[${outLabel}t]`, + `[${outLabel}t][pgf]overlay=x=${x}:y=${y}${enable}[${outLabel}]`, + ], + out: outLabel, + }; +} diff --git a/umtool/report-to-video/post-progress.test.mjs b/umtool/report-to-video/post-progress.test.mjs @@ -0,0 +1,103 @@ +// post-progress.mjs: A POST ITEM's PROGRESS BAR -- which items draw it (on, off, auto: a read of 60 s or more; the +// item's own over the cut's), its timing (the read's REAL seconds: linear, so a part read faster by a tempo step moves +// it faster and it never jumps at a part's edge), its ticks, its fade, the validators, the segment key (an item with +// no bar keeps its key), and the build's filters (ffmpeg: the fill clipped at the read's progress frame by frame). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postItemPlan, validatePostItem } from "./post-item.mjs"; +import { validatePostsRender } from "./post-redact.mjs"; +import { postFxKeyFields } from "./post-render.mjs"; +import { PROGRESS_AUTO_SECONDS, progressAt, progressFilters, progressModeOf, progressOpacityAt, progressPlan } from "./post-progress.mjs"; + +const DIR = await mkdtemp(path.join(tmpdir(), "umtool-post-progress-")); +after(() => rm(DIR, { recursive: true, force: true })); + +// A read of three parts; the middle one read 1.35x (a tempo step): shorter in the take, so its share of the bar is too. +const take = (seconds = 90) => ({ + file: "narration/posts/1/take-2.tempo-take.wav", engine: "derived", voice: "zac", seconds, + parts: [{ n: 1, para: 0, text: "a", start: 0, seconds: seconds * 0.4 }, { n: 2, para: 1, text: "b", start: seconds * 0.45, seconds: seconds * 0.2, tempo: 1.35 }, { n: 3, para: 2, text: "c", start: seconds * 0.7, seconds: seconds * 0.3 }], +}); +const item = (o = {}, seconds = 90) => ({ type: "post", id: "p-1", post: "subj-x/1", platform: "x", author: "S", handle: "s", date: "2026-10-30T10:00:00.000Z", text: "Words.", narration: { script: "a\n\nb\n\nc", takes: [take(seconds)], pick: 0 }, ...o }); + +test("WHICH ITEMS: the item's own mode over the cut's (absent: off); auto on for a read of 60 s or more as it plays (its rate counted)", () => { + const render = { postNarration: { lead: 0.4 } }; + assert.equal(progressModeOf(item(), render), "off"); + assert.equal(progressModeOf(item(), { posts: { progress: "auto" } }), "auto"); + assert.equal(progressModeOf(item({ progress: "off" }), { posts: { progress: "on" } }), "off"); + const plan = (e, r) => postItemPlan(e, r); + assert.equal(progressPlan(item(), render, plan(item(), render)), null, "the cut's default: off"); + const auto = { posts: { progress: "auto" } }; + assert.ok(progressPlan(item(), auto, plan(item(), auto)), "90 s of read: on"); + assert.equal(progressPlan(item({}, 40), auto, plan(item({}, 40), auto)), null, "40 s: off"); + // A 62 s take read at 1.08: 57.4 s on the item -- under the line. + const fast = { posts: { progress: "auto" }, postNarration: { rate: 1.08 } }; + assert.equal(progressPlan(item({}, 62), fast, plan(item({}, 62), fast)), null); + assert.ok(PROGRESS_AUTO_SECONDS === 60); + // on: any read; an item with no read fills over its own length. + const bare = { ...item({ progress: "on" }), narration: undefined }; + const pb = progressPlan(bare, {}, plan(bare, {})); + assert.deepEqual([pb.from, pb.to, pb.ticks], [0, plan(bare, {}).total, []]); +}); + +test("ITS TIMING: the read's real seconds, linear -- no jump at a part read faster; the ticks at each part's start; faded in to the read's start; gone at a stack card's media", () => { + const render = { posts: { progress: "on" }, postNarration: { lead: 0.4 } }; + const plan = postItemPlan(item(), render); + const pp = progressPlan(item(), render, plan); + assert.deepEqual([pp.from, pp.to], [0.4, 90.4]); + // The ticks: parts 2 and 3 start at 45% and 70% of the read. + assert.deepEqual(pp.ticks, [0.45, 0.7]); + // Linear: the same step of item seconds is the same step of the bar, inside the stretched part and across its edges. + const step = (s) => progressAt(pp, s + 0.1) - progressAt(pp, s); + for (const s of [10, 40.9, 41, 50, 58.9, 59, 63.4, 80]) assert.ok(Math.abs(step(s) - 0.1 / 90) < 1e-9, `at ${s}`); + assert.deepEqual([progressAt(pp, 0), progressAt(pp, 45.4), progressAt(pp, 95)], [0, 0.5, 1]); + // Faded in over 0.35 s ending at the read's start (here 0.4: from 0.05). + assert.equal(progressOpacityAt(pp, 0.05), 0); + assert.ok(Math.abs(progressOpacityAt(pp, 0.225) - 0.5) < 1e-9); + assert.equal(progressOpacityAt(pp, 0.4), 1); + assert.equal(progressOpacityAt({ ...pp, until: 50 }, 50), 0, "gone at its until"); + const stack = progressPlan(item(), render, { ...plan, steps: [{ at: 91, seconds: 3, items: [] }] }, { stack: true }); + assert.equal(stack.until, 91); +}); + +test("THE VALIDATORS and THE KEY: an item's progress and the cut's are on, off or auto; an item with no bar keeps its key, one with a bar adds its plan", () => { + assert.deepEqual(validatePostItem(item({ progress: "on" })), []); + assert.match(validatePostItem(item({ progress: "yes" })).join(" "), /progress must be auto, on, off/); + assert.deepEqual(validatePostsRender({ posts: { progress: "auto" } }), []); + assert.match(validatePostsRender({ posts: { progress: 1 } }).join(" "), /render.posts.progress must be auto, on, off/); + const render = { postNarration: { lead: 0.4 } }; + const plan = postItemPlan(item(), render); + assert.deepEqual(postFxKeyFields(item(), render, null, { plan }), {}, "no bar: nothing added"); + assert.deepEqual(postFxKeyFields(item(), render, null), {}, "no plan given: nothing added"); + const on = { ...render, posts: { progress: "auto" } }; + const k = postFxKeyFields(item(), on, null, { plan: postItemPlan(item(), on) }); + assert.deepEqual(Object.keys(k), ["progress"]); + assert.deepEqual([k.progress.v, k.progress.from, k.progress.to, k.progress.ticks], [1, 0.4, 90.4, [0.45, 0.7]]); +}); + +test("THE BUILD's FILTERS: the track laid, the fill clipped at the read's progress frame by frame, faded in, gone at until (ffmpeg)", async () => { + const track = path.join(DIR, "track.png"); + const fill = path.join(DIR, "fill.png"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x808080:s=200x6", "-frames:v", "1", track]); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0xff8000:s=200x6", "-frames:v", "1", fill]); + const pp = { from: 1, to: 3, ticks: [], until: 3.6, mode: "on" }; + const f = progressFilters({ ti: 1, fi: 2, inLabel: "0:v", outLabel: "o", x: 20, y: 50, pp, T: 4 }); + const out = path.join(DIR, "out.rgb"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=240x100:r=10:d=4", "-loop", "1", "-framerate", "10", "-t", "4", "-i", track, "-loop", "1", "-framerate", "10", "-t", "4", "-i", fill, "-filter_complex", f.chains.join(";"), "-map", "[o]", "-pix_fmt", "rgb24", "-f", "rawvideo", out]); + const buf = await readFile(out); + const px = (t, x) => { + const i = Math.round(t * 10) * 240 * 100 * 3 + (52 * 240 + 20 + x) * 3; + return [buf[i], buf[i + 1], buf[i + 2]]; + }; + assert.deepEqual(px(0.5, 100), [0, 0, 0], "before its fade: nothing"); + // At 1.5 s a quarter full (50 px of 200): the fill to its edge, the track after. + assert.ok(px(1.5, 40)[0] > 240 && px(1.5, 40)[2] < 10, `fill ${px(1.5, 40)}`); + assert.deepEqual(px(1.5, 55), [128, 128, 128]); + assert.ok(px(2, 90)[0] > 240, "half: the fill at 90 px"); + assert.deepEqual(px(2, 105), [128, 128, 128]); + assert.ok(px(3.2, 190)[0] > 240, "full"); + assert.deepEqual(px(3.7, 100), [0, 0, 0], "gone at its until"); +}); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -31,6 +31,7 @@ import { censorMarkupErrors } from "./post-censor.mjs"; import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; import { validateClockRender } from "./post-clock.mjs"; +import { validateProgressRender } from "./post-progress.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ export const REDACT_MARK = ""; @@ -190,7 +191,8 @@ export function validatePostsRender(render) { if (p === undefined) return []; if (!isObj(p)) return ["render.posts must be an object ({redact, slurs})"]; // Its clock (post-clock.mjs): the cut's default and zone. - return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock)]; + // Its progress bar (post-progress.mjs): the cut's default. + return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock), ...validateProgressRender(p.progress)]; } /** Every reason a channel's posts-markup.json is refused. */ diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -27,6 +27,7 @@ import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs import { sceneEntry } from "./post-media-scene.mjs"; import { CAPTION_OUT, CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs"; import { clockCss, clockFace, clockFrameTimes, clockHtml, clockPlan, clockStateAt, measureClockPlace, mountClock, setClockState } from "./post-clock.mjs"; +import { POST_PROGRESS_DRAW_V, measureProgressPlace, mountProgress, progressCss, progressFilters, progressHeight, progressPlan, setProgressState } from "./post-progress.mjs"; import { SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, setSlamState, slamCss, slamCoverErrors, slamHits, slamLayout, slamListAt, slamPlan, slamShakeExpr, slamSize, slamVars } from "./post-slam.mjs"; import { TRAILER_AUDIO, TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs"; import { panelReadErrors } from "./post-thread.mjs"; @@ -89,7 +90,7 @@ export function scrollExpr(keys) { * * @returns {string[]} */ -export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null, slams = [], slamHitList = [] }) { +export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null, slams = [], slamHitList = [], progress = null }) { const fps = render.fps ?? 30; const T = plan.total; const inputs = []; @@ -169,6 +170,15 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render if (c.mark) layer(c.mark, `cpm${ci}`, null); layer(c.chip, `cpc${ci}`, c.slide); }); + // THE PROGRESS BAR (post-progress.mjs): its track and its fill shot alone, laid along the card's foot -- the fill + // clipped at the read's progress frame by frame (real read seconds: a part read faster moves it faster, never a jump). + if (progress) { + const ti = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", progress.track]); + const fi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", progress.fill]); + const next = `b${++n}`; + parts.push(...progressFilters({ ti, fi, inLabel: cur, outLabel: next, x: progress.x, y: progress.y, pp: progress.plan, T }).chains); + cur = next; + } // THE CLOCK (post-clock.mjs): its frames shot alone -- the run from the item before's time, then held -- laid // over the card's corner from the first frame (a stack card's: until its media phase). if (clock) { @@ -394,7 +404,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, joinFrom = null, captions = [], clock = null, obstacles = [], slams = [] }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null, captions = [], clock = null, obstacles = [], slams = [], progress = null }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -491,6 +501,12 @@ 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 (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total }); + // The progress bar (post-progress.mjs): along the card's foot, short of the clock on its line. + if (progress) { + const k = box.height / 1080; + const cb = out.clock?.box ? { x: out.clock.box.x + Math.round(240 * k), y: out.clock.box.y, width: out.clock.box.width - Math.round(240 * k), height: out.clock.box.height } : null; + out.progress = await shootProgress(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, progress, redaction, follow, total, avoid: cb ? [cb] : [] }); + } // A caption covers none of the attachments (`obstacles`: their boxes) nor the clock. if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow, obstacles: [...obstacles, ...(out.clock ? [out.clock.box] : [])] }); if (slams.length) out.slams = await shootSlams(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, slams, redaction, follow }); @@ -918,6 +934,55 @@ export async function shootSlams(browser, entry, { box, render, dir, fonts, pare } /** + * THE PROGRESS BAR's STILLS (post-progress.mjs): on the card page as drawn, the bar mounted and placed + * (measureProgressPlace: the card's foot under its counts row, short of `avoid` -- the clock -- judged over the read: + * its start, middle and end, the place covering fewest words), then its track and its fill shot alone on a clear + * page. `{ track, fill, x, y, width, height, place, covers, plan }`. + */ +export async function shootProgress(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, progress, redaction = null, follow = null, total = 0, avoid = [] }) { + 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])); + try { + const file = path.join(dir, "progress.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 css = progressCss({ height: box.height, palette: render.palette }); + const h = progressHeight(box.height); + await page.evaluate(mountProgress, { css, ticks: progress.ticks, part: "track" }); + const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; + const states = follow ? [total, 0, total / 2] : [0]; + const looks = []; + for (const s of states) { + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); + looks.push(await page.evaluate(measureProgressPlace, { height: h, inset: Math.round(22 * k), avoid, fixed: looks[0]?.tries ?? null })); + } + if (!looks[0]) throw new Error(`${entry.id}: the progress bar has no card to sit on`); + // Each place's words over all three states: the fewest wins (the foot first when none). + const at = looks[0].tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.counts?.[i] ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0]; + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); + await page.evaluate(() => { + const st = document.createElement("style"); + st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-progress-layer]) { visibility: hidden !important; }"; + document.head.appendChild(st); + }); + const clip = { x: at.x, y: at.y, width: Math.min(box.width - at.x, at.width), height: Math.min(box.height - at.y, h) }; + const shot = async (part) => { + await page.evaluate(mountProgress, { css, ticks: progress.ticks, part }); + await page.evaluate(setProgressState, { x: at.x, y: at.y, width: at.width, frac: 1, opacity: 1 }); + const f = path.join(dir, `progress-${part}.png`); + await page.screenshot({ path: f, clip, omitBackground: true }); + return f; + }; + return { track: await shot("track"), fill: await shot("fill"), x: clip.x, y: clip.y, width: clip.width, height: clip.height, place: at.place, covers: at.covers, plan: progress }; + } finally { + await ctx.close(); + } +} + +/** * THE CLOCK's FRAMES (post-clock.mjs): on the card page as drawn, the chip * mounted at its widest and placed (measureClockPlace: the bottom-right corner * by the counts row, else the top-right -- over no word), then shot alone on a @@ -1039,13 +1104,16 @@ export const POST_CLOCK_DRAW_V = 1; * change to the shared generator rebuilds the items that play it. */ export const POST_SLAM_DRAW_V = 1; -export function postFxKeyFields(entry, render, prev = null) { +export function postFxKeyFields(entry, render, prev = null, { plan = null, layout = null } = {}) { const out = {}; const fx = Array.isArray(entry?.fx) ? entry.fx : []; if (fx.some((f) => f?.kind === "caption")) out.captionV = POST_CAPTION_DRAW_V; if (fx.some((f) => f?.kind === "slam")) out.slam = { v: POST_SLAM_DRAW_V, motion: SLAM_MOTION, hit: TRAILER_HIT_TIERS.title, audio: TRAILER_AUDIO }; const clk = clockPlan(entry, render, prev); if (clk) Object.assign(out, { clockV: POST_CLOCK_DRAW_V, clock: clk }); + // The progress bar (post-progress.mjs): its plan (the read's span, the parts' ticks, when it goes) and its drawing. + const pp = plan ? progressPlan(entry, render, plan, { stack: layout?.mode === "stack" }) : null; + if (pp) out.progress = { v: POST_PROGRESS_DRAW_V, ...pp }; const k = postNarrationKnobs(entry, render); if (isNarrated(entry) && k.pace && k.pace !== "normal") out.pace = { pace: k.pace, lead: k.lead, tail: k.tail, ramp: k.ramp, linger: k.linger }; return out; @@ -1083,7 +1151,7 @@ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], ren ...(plan.panel ? { panel: plan.panel } : {}), ...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}), // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them. - ...postFxKeyFields(entry, render, prev), + ...postFxKeyFields(entry, render, prev, { plan, layout }), ...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}), }; } @@ -1181,7 +1249,9 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const capPlan = captionPlan(entry, render, { zooms: [...zoomPlan.map((z) => ({ ...z.span, i: z.i })), ...slPlan.map((p) => ({ t0: p.span.t0, t3: p.span.t3, i: p.i }))], end: fxEnd, schedule: plan.narration ?? undefined }); // Its clock (post-clock.mjs): the post's own time, run from the clock item before it. const clk = clockPlan(entry, render, prev); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [], slams: slPlan }); + // Its progress bar (post-progress.mjs): the read's span on the item's clock (a long read's, auto). + const prog = progressPlan(entry, render, plan, { stack: layout.mode === "stack" }); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [], slams: slPlan, progress: prog }); // 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). // A part read off a linked post's picture is on screen only while the panel shows it (post-thread.mjs panelReadErrors). @@ -1215,7 +1285,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, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null, slams: cards.slams ?? [], slamHitList: (cards.slams ?? []).flatMap((sl) => slamHits(sl.fx, sl.span).map((h) => ({ ...h, gain: h.gain * sl.fx.volume }))) }); + 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, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null, slams: cards.slams ?? [], slamHitList: (cards.slams ?? []).flatMap((sl) => slamHits(sl.fx, sl.span).map((h) => ({ ...h, gain: h.gain * sl.fx.volume }))), progress: cards.progress ?? null }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { @@ -1234,6 +1304,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box : `${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` }); + if (cards.progress) emit("note", { message: `${entry.id}: progress bar over the read ${prog.from}–${prog.to} s (${prog.mode}${prog.ticks.length ? `, ${prog.ticks.length + 1} parts ticked` : ""}), ${cards.progress.place === "foot" ? "along the card's foot" : "under the card"}${cards.progress.covers ? ` -- WARNING: over ${cards.progress.covers} word(s)` : ""}` }); if (cards.clock) emit("note", { message: `${entry.id}: clock ${clockFace(clk.to, clk.zone).time} ${clockFace(clk.to, clk.zone).date} (${clk.mode === "none" ? "shown" : clk.mode === "rewind" ? "rewound" : "run forward"}${clk.mode === "none" ? "" : ` from the item before, ${clk.gap / 60000 | 0} min`}), ${cards.clock.place}${cards.clock.covers ? ` -- WARNING: over ${cards.clock.covers} word(s)` : ""}` }); 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 ${entry.fx?.[c.span.waited]?.kind === "slam" ? "slam" : "word zoom"} ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` }); for (const sl of cards.slams ?? []) emit("note", { message: `${entry.id}: slam ${sl.i + 1} "${sl.fx.text}" -- ${sl.landings.length} hit(s) at ${sl.landings.map((x) => x.toFixed(2)).join(", ")} s (${sl.source === "words" ? "spread over the words' spoken span" : sl.source === "at" ? "from its at" : "the reading estimate"}), up ${sl.span.t0}–${sl.span.t3} s, ${sl.layout.where} the words${sl.layout.covers ? `, over ${sl.layout.covers} other thing(s) drawn for its window (the gag)` : ""}${sl.fx.sfx === "off" ? ", silent" : ""}` });