Archilyzer · Source

archilyzer

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

commit 031df858f4f77d9d8a1c2ab272200ce303f9f171
parent a98b2270962ac2bcfe7599d940fcc2eef2e17125
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 20:02:59 -0500

Merge main (post-slam, long-reads, fast-fix-render) into lane/join-continuity: the join's fields appended to postSegmentKeyOf after main's slam, progress and pool fields; the clock shot before the read's frames (the join decides from it) with main's progress bar after it; the frames lists read at the item's rate, the slam's too; Play's join clock and main's progress bar both

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mumtool/app/api/report/post-narration/route.ts | 16+++++++++++++---
Mumtool/bin/umtool.mjs | 6++++++
Mumtool/components/projects/PostBench.tsx | 25++++++++++++++++++++++++-
Mumtool/components/projects/PostZoomPanel.tsx | 46+++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/review/PlayCut.tsx | 3+++
Mumtool/components/projects/review/PostItemPlayer.tsx | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/docs/cli.md | 4++++
Mumtool/docs/knobs.md | 32++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 203++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/e2e/long-reads.spec.ts | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/post-slam.spec.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 24+++++++++++++++++++++++-
Mumtool/lib/report/playView.mjs | 6+++++-
Aumtool/lib/report/poolCli.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postFx.test.mjs | 28++++++++++++++++++++++++++++
Mumtool/lib/report/postFxCli.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/postReread.mjs | 299+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/lib/report/postReread.test.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postYell.mjs | 393+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postYell.test.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/report/takeFrom.mjs | 11+++++++----
Mumtool/lib/report/takePrune.mjs | 28++++++++++++++++++++++++++--
Mumtool/lib/report/takePrune.test.mjs | 19+++++++++++++++++++
Mumtool/report-to-video/README.md | 34+++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/build-video.mjs | 442+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mumtool/report-to-video/chunked-encode.mjs | 67++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/chunked-encode.test.mjs | 225++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/compose-chrome.mjs | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/deck.mjs | 11++++-------
Mumtool/report-to-video/frame-keys.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/hardcut-deck.test.mjs | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 4++++
Mumtool/report-to-video/post-item.mjs | 3+++
Mumtool/report-to-video/post-narration.mjs | 20++++++++++++++++----
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 | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/report-to-video/post-slam.mjs | 615+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-slam.test.mjs | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/prune-frames.mjs | 12+++++++++---
Aumtool/report-to-video/render-pool.mjs | 370+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/render-pool.test.mjs | 237+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/segment-cache.mjs | 18+++++++++++++++++-
Aumtool/report-to-video/trailer-hits.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/word-zoom.mjs | 7+++++--
48 files changed, 5202 insertions(+), 252 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A small fix to a report-video take re-renders in minutes, not half an hour.** A take renders hard cuts, and its final picture was one overlay pass over the whole cut on every take -- 12.6 of mid-6's 30 minutes, 26 of mid-7's 60 -- however small the change. The pass is now in keyed chunks, one segment's run each: `umtool take … --from <take>` re-encodes only the chunks of the post it touched, and a post that grew or shrank moves the chunks after it without changing them (the deck's frames after it are the same frames, later). The deck is drawn only where a chunk to encode reads it, so a take `--from` a pruned one no longer captures the whole deck again (12,347 captures, ~3 minutes on mid-7), and the cut's sound is keyed by each segment's audio, so a caption or a knob that moves no word keeps it. The picture is now frame-exact: the old pass laid each next segment at the longer of its picture and its sound, the footage up to 0.3 s behind the deck by the end of the cut. - **A recorded take can be cleaned up, or given a stock synthetic voice, by the editor.** umtool's derived takes (`umtool posts narrate <p> <item> --derive <n> --op enhance|convert`, the post bench's **run AI on take #n**) said "not installed": the editor had no voice ops. It now has two, each a job on a new `voice` queue, its engine run behind the machine's heavy slot with a declared memory estimate: `pnpm ops voice-enhance` (denoise, soften the room, level — DeepFilterNet 3, or RNNoise through ffmpeg with nothing to install) and `pnpm ops voice-convert` (the timing and pitch contour kept, the timbre swapped — OpenVoice v2's converter or Seed-VC). The result is a 48 kHz mono WAV exactly as long as the take, so a derived take lines up with its source; a take recorded part by part is processed part by part. A conversion lands only on a STOCK voice of our own TTS engines (`zac`, `orpheus:leah`, `kokoro:am_michael`): a file or a recording is refused as a target, whatever it holds. The engines are installed by `archilyzer voice setup --engine <id>`, which says what it downloads and how big first; `settings.voice` picks the defaults (SETTINGS.md); OPERATING.md, "Enhance or convert a recorded take". - **X post captures keep the post's context: what it quotes and what it answers.** A post video drew a reply ("you called me a Leftist…") with nothing it answered, because the archive row named no parent, no quote and no links. `capture-posts` on an X channel now reads, off the page it already loads, the post it answers (the archive's in-reply-to id, else the post directly above it) and the post it quotes — author, display name, check, date, words and media links — into the post's `capture.json` as `context`, with no extra page load (`"context": false` turns it off). `"contextOnly": true` loads one page per post for that alone (and the avatars it shows) and writes nothing else: `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<post id>", …],"contextOnly":true}' --wait`. Not verified against live X yet; the first run is the check. Needs a restart of the editor. - **The X fetcher keeps quoted posts.** A timeline read never recorded what a post quotes (gallery-dl drops the quoted tweet unless asked). Every read now asks for it, and a quote becomes the quoting post's `quoted` — never archived as one of the account's own posts; an account quoting its own older post still archives that post when the walk reaches it. Posts already archived keep what they have (a re-fetch does not rewrite them; their context comes from `contextOnly`). Needs a restart of the editor. diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -11,7 +11,7 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; -import { rereadTake } from "@/lib/report/postReread.mjs"; +import { parseTempoSpec, rereadTake } from "@/lib/report/postReread.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; @@ -42,6 +42,7 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // when the editor has no engine for it // POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) // POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece +// POST {project, op: "reread", id, tempo: "4-16=1.35", stretch?} its parts RE-TIMED (no TTS); {…, yell: true, yellGain?, yellStyle?}: its caps raised // (postReread.mjs: no TTS; a new take, picked, one undo point) // POST {project, op: "undo"} the last structural write undone @@ -223,10 +224,19 @@ export async function POST(request: Request) { // The bench's "Read without it" (postReread.mjs): the picked take's kept parts cut and joined again, no TTS. const list = (v: unknown) => (Array.isArray(v) ? v.map(String) : typeof v === "string" && v ? v.split(",") : []); try { - const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true }); + // `tempo`: "4-16=1.35,21-25=1.3" (postReread.mjs parseTempoSpec) -- the parts re-timed; `yell: true` -- the caps raised (postYell.mjs). + if (body.yell === true) { + const { yellTake } = await import("@/lib/report/postYell.mjs"); + const { cutSlurs } = await import("umtool-report-to-video/post-redact-files"); + const yy = await yellTake(r.project, e, { slurs: cutSlurs(m), ...(typeof body.yellGain === "number" ? { gain: body.yellGain } : {}), ...(typeof body.yellStyle === "string" ? { style: body.yellStyle } : {}) }); + return Response.json({ ok: true, take: yy.take, spans: yy.plan.spans, entry: yy.result?.entry ?? null, token: yy.result?.token ?? null }, { headers: noStore }); + } + const pt = pickedTake(e) as { parts?: unknown[] } | null; + const tempo = typeof body.tempo === "string" && body.tempo ? parseTempoSpec({ spec: body.tempo, count: Array.isArray(pt?.parts) ? pt.parts.length : 0 }) : null; + const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true, tempo, ...(body.stretch === "rubberband" ? { stretch: "rubberband" } : {}) }); return Response.json({ ok: true, take: rr.take, entry: rr.result?.entry ?? null, token: rr.result?.token ?? null }, { headers: noStore }); } catch (err) { - if ((err as Error)?.name === "RereadError") return Response.json({ error: (err as Error).message }, { status: 400 }); + if ((err as Error)?.name === "RereadError" || (err as Error)?.name === "YellError") return Response.json({ error: (err as Error).message }, { status: 400 }); throw err; } } diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -79,6 +79,7 @@ // | delete <project> <take> [--dry-run] [--force] take housekeeping // umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render gets the machine // umtool render-mode on [--for 90m] [--print-token] -- <cmd …> held while <cmd> runs (its env carries the token) +// umtool pool [stats|prune|verify] [--json] the render pool: every built unit by its key, shared by every take // umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] // [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master // | --reel <name> [--take <t>] a beat reel (promo/<name>-beats.json) -> <slug>.<name>.mp4 @@ -972,6 +973,9 @@ function usage() { " on [--for D] [--print-token] -- <cmd …>: held while <cmd> runs (its env carries the token,", " the hold is its pid), released when it exits -- the form for a script; --print-token prints", " the token alone on stdout", + " umtool pool [stats] [--since 7d] | prune [--max-gb N] [--dry-run] | verify [--sample N | --all] [--json]", + " the render pool: every post, clip, chunk, sound and chrome frame a build made, by its key,", + " hard-linked into any take that needs it again (UMTOOL_RENDER_POOL=0 off; _MAX_GB its cap)", " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]", " a trailer cut from the take's finished master: the master's own frames, so the deck shows the", " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)", @@ -1105,6 +1109,8 @@ const COMMANDS = { takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), // Render mode (2026-10-30): lib/report/renderMode.mjs. "render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))), + // The render pool (report-to-video render-pool.mjs): lib/report/poolCli.mjs. + pool: async () => process.exit(await (await import("../lib/report/poolCli.mjs")).poolCommand(argv.slice(argv.indexOf("pool") + 1))), trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -18,7 +18,9 @@ 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 { 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"; // --------------------------------------------------------------------------- @@ -123,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); @@ -291,6 +295,18 @@ export default function PostBench({ }), [entry, render], ); + // Its slams (post-slam.mjs): each from its first glyph in to gone, a tick at each hit. + const slamMarks = useMemo( + () => + (slamTimes(entry, render) as Array<{ i: number; t?: number; end?: number | null }>) + .filter((x) => typeof x.t === "number") + .map((x) => { + const fx = (entry.fx as Array<Record<string, unknown>>)[x.i]; + const sp = slamSpan(fx, slamLandings(fx, { t: x.t as number, end: x.end ?? null })); + return { i: x.i, t0: sp.t0 ?? 0, t3: sp.t3 ?? 0, landings: sp.landings ?? [] }; + }), + [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); @@ -317,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]"> @@ -356,6 +372,13 @@ export default function PostBench({ {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} /> ))} + {slamMarks.map((m) => ( + <div key={`s${m.i}`} className="absolute top-0 h-1/3 border-x border-yellow-300/90 bg-yellow-300/30" style={{ left: `${(m.t0 / total) * 100}%`, width: `${((m.t3 - m.t0) / total) * 100}%` }} title={`slam ${m.i + 1}: ${m.landings.length} hit(s)`} data-post-bench-slam-mark={m.i}> + {m.landings.map((L, j) => ( + <span key={j} className="absolute inset-y-0 w-0.5 bg-yellow-200" style={{ left: `${((L - m.t0) / Math.max(0.01, m.t3 - m.t0)) * 100}%` }} data-post-bench-slam-hit={j} /> + ))} + </div> + ))} <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 @@ -8,6 +8,7 @@ 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"; +import { resolveSlam, slamLandings, slamTimes } from "umtool-report-to-video/post-slam"; // --------------------------------------------------------------------------- // A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A @@ -61,6 +62,8 @@ export default function PostZoomPanel({ const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]); const ctimes = useMemo(() => captionTimes(entry, render), [entry, render]); const [capText, setCapText] = useState(""); + const [slamText, setSlamText] = useState(""); + const stimes = useMemo(() => slamTimes(entry, render), [entry, render]); const narrated = isNarrated(entry); const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null; @@ -76,24 +79,26 @@ export default function PostZoomPanel({ return j.entry; }; - const zoomHere = async (kind: "word-zoom" | "caption" = "word-zoom") => { + const zoomHere = async (kind: "word-zoom" | "caption" | "slam" = "word-zoom") => { if (!sel) return; if (kind === "caption" && !capText.trim()) return setError("a caption needs its text"); + if (kind === "slam" && !slamText.trim()) return setError("a slam needs its glyphs"); 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, match, ...(kind === "caption" ? { text: capText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) }; + const add: Record<string, unknown> = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : kind === "slam" ? { text: slamText.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. // (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(`${kind === "caption" ? "caption" : "zoom"} added on "${match}"`); + setStatus(`${kind === "caption" ? "caption" : kind === "slam" ? "slam" : "zoom"} added on "${match}"`); setSel(null); if (kind === "caption") setCapText(""); + if (kind === "slam") setSlamText(""); } }; @@ -212,6 +217,17 @@ export default function PostZoomPanel({ <button type="button" className={btn} disabled={!sel || !capText.trim()} onClick={() => void zoomHere("caption")} data-post-caption-here=""> Caption here </button> + <input + value={slamText} + onChange={(e) => setSlamText(e.target.value)} + placeholder="slam glyphs (不動心)" + className="w-28 rounded border border-seam bg-ground px-1 py-0.5" + aria-label="slam glyphs" + data-post-slam-text="" + /> + <button type="button" className={btn} disabled={!sel || !slamText.trim()} onClick={() => void zoomHere("slam")} data-post-slam-here=""> + Slam here + </button> {sel && ( <span className="text-text-2" data-post-zoom-sel=""> “{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}” @@ -219,6 +235,30 @@ export default function PostZoomPanel({ )} </div> {list.map((fx0, i) => { + // A SLAM (post-slam.mjs): its glyphs, its word, its hits; go to it, remove it (its knobs: umtool posts fx … set). + if (fx0?.kind === "slam") { + const sl = resolveSlam(fx0); + const t = stimes[i] as { t?: number; end?: number | null; source?: string; error?: string }; + const hits = typeof t?.t === "number" ? slamLandings(fx0, { t: t.t, end: t.end ?? null }) : []; + const up = hits.length > 0 && s >= hits[0] - 0.2 && s < hits[hits.length - 1] + sl.hold + 0.35; + return ( + <div key={i} className={cn("flex flex-wrap items-center gap-2 rounded border p-2", up ? "border-yellow-300/80" : "border-seam")} data-post-slam-fx={i}> + <b> + #{i + 1} slam {sl.text} + </b> + <span className="text-text-2"> + {typeof fx0.match === "string" ? `on “${sl.match}” · ` : ""} + {t?.error ? `no time: ${t.error}` : `hits at ${hits.map((x) => x.toFixed(2)).join(", ")} s (${t.source === "words" ? "over the spoken word" : t.source === "at" ? "its at" : "the estimate"})`} + </span> + <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (hits[0] ?? 0) - 0.6))} disabled={!hits.length} data-post-slam-go={i}> + go + </button> + <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-slam-remove={i}> + remove + </button> + </div> + ); + } // Its clock (post-clock.mjs): a row of its own, its rewind knob. if (fx0?.kind === "clock") { return ( 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,11 @@ 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"; +import { TRAILER_AUDIO, trailerHitSamples } from "umtool-report-to-video/trailer-hits"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom"; // --------------------------------------------------------------------------- @@ -52,9 +57,14 @@ 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[] }; +/** A slam of the item, placed in its card page: its plan (span, units, its fx), each unit's centre, the words' box when placed. */ +type LiveSlam = { i: number; span: { t0: number; t2: number; t3: number; landings: number[] }; fx: Record<string, unknown> & { fromScale: number; volume: number }; scope: string | null; from: number; to: number; centers: Array<{ x: number; y: number }>; base: Rect | null; where: string }; 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. */ @@ -207,6 +217,59 @@ function mixGraph(el: HTMLMediaElement, lowpassHz: number) { } } +// --------------------------------------------------------------------------- +// A SLAM's HITS, LIVE (post-slam.mjs, trailer-hits.mjs): each hit's layers made +// by the build's own formulas (trailerHitSamples), filtered as its graph filters +// them (the punch band-passed, the rumble low-passed, a short echo), at the +// trailer's level -- started as Play's clock crosses a landing. No limiter: a +// close approximation of the render's mix, not its bytes. +// --------------------------------------------------------------------------- + +const hitBuffers = new Map<string, AudioBuffer[]>(); +function playTrailerHit(h: { gain: number; decay: number; f0: number; f1: number }, gain = 1) { + if (typeof window === "undefined" || typeof window.AudioContext === "undefined") return; + audioCtx ??= new window.AudioContext(); + const ctx = audioCtx; + if (ctx.state === "suspended") void ctx.resume().catch(() => {}); + const key = JSON.stringify([h, ctx.sampleRate]); + let bufs = hitBuffers.get(key); + if (!bufs) { + const smp = trailerHitSamples(h, ctx.sampleRate); + bufs = [smp.boom, smp.punch, smp.rumble].map((data) => { + const b = ctx.createBuffer(1, data.length, ctx.sampleRate); + b.copyToChannel(new Float32Array(data), 0); + return b; + }); + hitBuffers.set(key, bufs); + } + const out = ctx.createGain(); + out.gain.value = TRAILER_AUDIO.level * gain; + const lp = ctx.createBiquadFilter(); + lp.type = "lowpass"; + lp.frequency.value = 5000; + const echo = ctx.createDelay(0.5); + echo.delayTime.value = 0.09; + const echoGain = ctx.createGain(); + echoGain.gain.value = 0.18; + out.connect(lp).connect(ctx.destination); + out.connect(echo).connect(echoGain).connect(lp); + const chain = [[], [["highpass", 180], ["lowpass", 3200]], [["lowpass", 260], ["lowpass", 260]]] as Array<Array<[BiquadFilterType, number]>>; + const now = ctx.currentTime; + bufs.forEach((b, j) => { + const src = ctx.createBufferSource(); + src.buffer = b; + let node: AudioNode = src; + for (const [type, f] of chain[j]) { + const bq = ctx.createBiquadFilter(); + bq.type = type; + bq.frequency.value = f; + node = node.connect(bq); + } + node.connect(out); + src.start(now); + }); +} + type Censor = { strength: number; boxes: number[][]; band: number[] | null; label: string | null; style: "blur" | "black" | "pixelate" }; /** @@ -431,7 +494,7 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A type ClockPlan = { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean }; export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, + 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; @@ -455,6 +518,8 @@ export default function PostItemPlayer({ clock?: ClockPlan | null; /** THE JOIN (post-join.mjs): the item before (its entry, plan and clock) -- this one opens on it as it ended. */ joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan; clock?: ClockPlan | null } | null; + /** Its progress bar (post-progress.mjs progressPlan), or none. */ + progress?: ProgressPlan | null; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -570,6 +635,7 @@ export default function PostItemPlayer({ }, [joinFrom, box]); const [zooms, setZooms] = useState<LiveZoom[]>([]); const [caps, setCaps] = useState<LiveCaption[]>([]); + const [slams, setSlams] = useState<LiveSlam[]>([]); // The clock's box (and its badge's) where it is placed: a caption covers neither. const clockRect = useRef<Rect | null>(null); const boxes = useRef<Map<Element, Rect>>(new Map()); @@ -607,7 +673,9 @@ export default function PostItemPlayer({ if (!card || !list.length) { setZooms([]); setCaps([]); + setSlams([]); mountCaptions({ css: "", chips: [] }, doc); + mountSlams(null, doc); return true; } const rect = (el: Element): Rect => { @@ -639,14 +707,49 @@ 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. + const k = box.height / 1080; + const fxEnd = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total; + // Its slams (post-slam.mjs): planned, mounted and placed as the build places them -- as the card is at the first hit. + let splan: ReturnType<typeof slamPlan> = []; + try { + splan = slamPlan(entry, undefined, { zooms: out.map((z) => ({ ...z.span, i: z.i })), end: fxEnd, schedule: plan.narration as never }); + } catch { + splan = []; + } + const placedSlams: LiveSlam[] = []; + { + const inset0 = Math.round(12 * k); + const bounds0 = { x: inset0, y: inset0, width: box.width - 2 * inset0, height: box.height - 2 * inset0 }; + type Geo = { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; obstacles: Rect[] }; + const all: Array<{ i: number; k: number; text: string; size: number; face: string; vars: Record<string, string> }> = []; + const geos: Array<Geo | null> = []; + for (const p of splan) { + if (follow) applyFollowState(followStateAt(follow, route, p.span.landings[0]), doc); + const g = p.scope ? (measureCaptionWords({ scope: p.scope, from: p.from, to: p.to, avoid: p.avoid }, doc) as Geo) : null; + geos.push(g && !g.error ? g : null); + const line = g && !g.error ? g.lines.reduce((a, l) => (l.height > a.height ? l : a), g.lines[0]) : null; + const size = slamSize(p.fx, line, k); + p.units.forEach((text: string, kk: number) => all.push({ i: p.i, k: kk, text, size, face: SLAM_FACE_STACK[p.fx.face as keyof typeof SLAM_FACE_STACK] ?? SLAM_FACE_STACK.jp, vars: slamVars(p.fx, size) })); + } + const boxes = mountSlams(all.length ? { css: slamCss(), units: all, dust: [...SLAM_DUST] } : null, doc); + splan.forEach((p, pi) => { + const g = geos[pi]; + const cardEl = doc.querySelector("[data-post-card]"); + const cardBox = g ? g.card : cardEl ? rect(cardEl) : null; + if (!cardBox || (p.scope && !g)) return; + const units = boxes.filter((b) => b.i === p.i).sort((a, b) => a.k - b.k); + const lay = slamLayout({ word: g ? g.word : null, card: cardBox, bounds: bounds0, units, place: p.fx.place, gap: Math.round(6 * k), protect: g ? [...g.lines, ...g.avoid] : [], obstacles: g ? g.obstacles : [] }); + placedSlams.push({ i: p.i, span: p.span, fx: p.fx, scope: p.scope, from: p.from, to: p.to, centers: lay.centers, base: g ? g.word : null, where: lay.where }); + }); + } + setSlams(placedSlams); + // Its captions: planned as the build plans them (each waits for a zoom, and for a slam), 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 }); + cplan = captionPlan(entry, undefined, { zooms: [...out.map((z) => ({ ...z.span, i: z.i })), ...splan.map((p) => ({ t0: p.span.t0, t3: p.span.t3, i: p.i }))], end: fxEnd, schedule: plan.narration as never }); } catch { cplan = []; } - const k = box.height / 1080; const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }, doc); const inset = Math.round(12 * k); // Free space only (as the build places it): the whole box, never over a word, the card's furniture, an attachment or the clock. @@ -694,10 +797,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); }; @@ -788,6 +925,38 @@ export default function PostItemPlayer({ }); setCaptionState({ list, stroke: Math.max(2, Math.round(2.4 * k)) }, doc); }, [capsUp, s, follow, followNow, box.height]); + // The slams up now (post-slam.mjs): each unit's state on the item's clock, riding its words when the card pans; the + // frame's punch at each hit (the page's body moved, as the build moves the frame). + const slamsUp = slams.filter((p) => s >= p.span.t0 && s < p.span.t3); + useEffect(() => { + const doc = readFrame.current?.contentDocument; + if (!doc) return; + const k = box.height / 1080; + const list = slamsUp.flatMap((p) => { + let dx = 0; + let dy = 0; + if (follow && p.scope && p.base) { + const g = measureCaptionWords({ scope: p.scope, from: p.from, to: p.to, avoid: [] }, doc) as { error?: string; word: Rect }; + if (!g.error) [dx, dy] = [g.word.x - p.base.x, g.word.y - p.base.y]; + } + return slamListAt(p as never, s, dx, dy); + }); + const sh = slamShakeAt(slamsUp.flatMap((p) => p.span.landings), s); + const amp = SLAM_MOTION.shake.amp * k; + setSlamState({ list, shake: list.length ? { x: sh.x * amp, y: sh.y * amp } : null }, doc); + }, [slamsUp, s, follow, followNow, box.height]); + // Its hits, as Play's clock crosses each landing while playing (a seek over one is silent). + const lastS = useRef(s); + useEffect(() => { + const prev = lastS.current; + lastS.current = s; + if (!playing || s < prev || s - prev > 0.5) return; + for (const p of slams) { + for (const h of slamHits(p.fx, p.span)) { + if (h.kind === "hit" && h.at > prev && h.at <= s) playTrailerHit(h, Number(p.fx.volume ?? 1)); + } + } + }, [s, playing, slams]); const clockSt = useMemo(() => (clock ? clockStateAt(clock, s) : null), [clock, s]); useEffect(() => { const doc = readFrame.current?.contentDocument; @@ -799,6 +968,15 @@ export default function PostItemPlayer({ const at = clockAt && jc?.move ? { x: clockAt.x + jc.move.dx * left, y: clockAt.y + jc.move.dy * left } : clockAt; setClockState(clockSt && at && s < until ? { ...at, st: clockSt, ...(jc?.fadeIn ? { opacity: Math.max(0, s / joinSecs) } : {}) } : null, doc); }, [clockSt, clockAt, s, layout.mode, plan.steps, joinClock, joinSecs]); + // 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 ( @@ -819,6 +997,12 @@ export default function PostItemPlayer({ 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-slams={slams.length ? String(slams.length) : undefined} + 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/docs/cli.md b/umtool/docs/cli.md @@ -86,11 +86,15 @@ Inbox cannot disagree about what is wrong with one. | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | | `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\|off] [thread.map=auto\|on\|off\|map\|label\|both] [panel=auto\|side\|top\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\|@<file>\|off] [parent.<i>.media=<file>[,…]\|off] [link.add=<json ref>] [link.<i>=<json ref>\|off] [link.<i>.media=<file>\|off] [link.<i>.transcript="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit | | `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) | +| `posts reread <project> <item> --tempo-for "4-16=1.35,21-25=1.3" \| --tempo <x> --parts <runs> [--stretch atempo\|rubberband] [--dry-run] [--json]` | a narrated read's **parts re-timed**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled)): the parts named time-stretched (1–1.6, pitch kept), the rest untouched, joined with the read's pauses (each stretched part padded and trimmed to its length, sample-exact), its words scaled with their part, a derived take (`steps: [{op: "tempo", tempo, params: {stretch}}]`) picked in ONE write. A tempo is absolute: on a re-timed take it re-cuts from the take before. `posts set-item <p> <item> narration.tempo="4-16=1.35"` runs the same. A part outside the take, a tempo outside 1–1.6, nothing changed: **exit 1** | +| `posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run] [--json]` · `posts yell <project> --all \| <item …> [--yell-gain …] [--yell-style …] [--dry-run] [--json]` | a narrated read's **caps yelled**, no TTS ([report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled), `lib/report/postYell.mjs`): his ALL-CAPS words found in the take's word timings and raised (the lift measured, its loudness within 1 LU), acronyms and masked slurs left flat, a derived take (`steps: [{op: "yell", spans, params}]`) picked (one undo point per item). No word timings: **exit 1** naming `posts narrate --words`; `posts yell --dry-run` lists every item's caps, the flat ones and why, and which need word timings | +| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it | | `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | | `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) | | `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]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) | | `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times | +| `posts fx <project> <item> add slam --text "不動心" [--match "…" \| --at s] [--whole \| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\|center] [--size px] [--face jp\|sc\|tc\|kr] [--sfx trailer-hit\|off] [--volume x] [--swell \| --no-swell]` · `set <n> [those flags]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) | | `posts fx <project> <item> [ls]` · `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]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) | | `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is | | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -790,6 +790,36 @@ build's words (`clockErrors`, `validateClockRender`, `report-to-video/post-clock | one item's clock -- on (or `on: false`: not on this item though the cut's is) | post bench, the clock's row (**remove**) | `umtool posts fx <p> <item> add clock [--off]` · `remove <n>` | `fx: {add: {kind: "clock"}}` | | `rewind` `auto` (an earlier post rewinds) \| `on` (rewinds anyway) \| `off` (cuts straight to its time) | the clock's **rewind** | `umtool posts fx <p> <item> set <n> --rewind on\|off\|auto` | `fx: {set: <i>, patch: {rewind}}` | +## The progress bar (a long read's progress along its card's foot) + +`render.posts.progress` (the cut's default) and `progress` on a post item ([report-video.md](report-video.md#the-progress-bar)): +a thin bar along the card's foot that fills with the item's READ -- its real seconds, so a part read faster (a tempo +step) moves it faster and it never jumps -- ticked at each part's start. Refused in the build's words +(`progressErrors`, `validateProgressRender`, `report-to-video/post-progress.mjs`); in the segment key only for an item +that draws it. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| the cut's bar -- `auto` (a read of 60 s or more, as the item plays it), `on`, `off` (absent: off) | — | `umtool posts progress <p> auto\|on\|off\|default` (`updatePostProgressRender`); bare: which items draw it | — | +| one item's -- `on`, `off`, `auto` (absent: the cut's) | Play and the post bench draw it | `umtool posts set-item <p> <item> progress=on\|off\|auto\|default` | `POST /api/report/post-item {project, op: "set", id, patch: {progress}, token}` | + +## A slam (a trailer-style title slam over a word as it is read) + +`fx: [{kind: "slam", text, match, …}]` on a post item ([report-video.md](report-video.md#a-slam): the shape, the +time, the place, the one exemption, the sound, the render). One writer, `updatePostFx`, refused in the build's words +(`slamErrors`, `report-to-video/post-slam.mjs`, through `validatePostFx`; a row that would cover the words being read, +`slamCoverErrors`). Play and the bench draw the build's own glyphs, live, and Play sounds the hits. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| a slam -- `text` (≤ 12 characters; one glyph, one hit), `match` (a word or a phrase: "Baji Quan"), `occurrence`, `target`; `whole` (the text as one unit, one hit) | post bench: click a word (shift-click: a phrase), type the glyphs, **Slam here** | `umtool posts fx <p> <item> add slam --text "不動心" --match "Fudōshin" [--whole]` | `POST /api/report/post-item {project, op: "fx", id, fx: {add: {kind: "slam", text, match}}, token}` | +| WHEN -- the hits spread evenly over the matched words' spoken span (the first on its start, the last on its end); `gap` 0.12–2 s spaces them instead; `at` (item seconds) moves the first; no span: 0.45 s apart | the slam's row (its hits; **go**) | `set <n> --gap 0.4` · `set <n> --at 4.1` (`default` clears one) | `fx: {set: <i>, patch: {gap, at}}` | +| THE LOOK -- `hold` 0.3–4 s after the last hit (1.6), `fromScale` 1.5–8 (3.5), `color` (#f5c542) and `outline` (#000000), `outlineWidth` 0–30 px (at a 120 px glyph; default 11% of the glyph), `size` 40–320 px at 1080 (by the words' line), `face` `jp` \| `sc` \| `tc` \| `kr` (Noto Sans CJK Black; 八极拳 reads `sc`) | — | `set <n> --hold 2 --from-scale 4 --color #ffd700 --outline #000000 --outline-width 14 --size 130 --face sc` | `fx: {set: <i>, patch: {…}}` | +| WHERE -- `place` `over-match` (above the words' line; below it when above is out of the frame or over a word read at a hit) \| `center` (the card's middle) | — | `set <n> --place center` | `fx: {set: <i>, patch: {place}}` | +| THE SOUND -- `sfx` `trailer-hit` \| `off`, `volume` 0–3 × the hit's level (1), `swell` (the teaser's swell under the hold) | — | `set <n> --sfx off` · `--volume 0.7` · `--swell` / `--no-swell` | `fx: {set: <i>, patch: {sfx, volume, swell}}` | +| remove one | the slam's **remove** | `umtool posts fx <p> <item> remove <n>` | `fx: {remove: <i>}` | +| list them, each with its hits and where they came from | the block's rows; the plan strip marks each (yellow, a tick per hit) | `umtool posts fx <p> <item> [ls] [--json]` | — | + ## The pace (a burst played back to back) | Knob | In umtool | From a terminal | Route | @@ -854,6 +884,8 @@ gathers them). | `thread` on a post item — `{parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan?}` over the cut's (`parent` one mode, or a list, nearest parent first) | post bench, **thread read**: the post it answers / its parent / the quoted post (the cut's, or a mode), **carry**, **shrink**, **dim**, **over**, **pan**; the guard's refusals listed before Save | `umtool posts set-item <p> <item> thread.parent=excerpt` · `thread.parent.1=hidden` · `thread.quoted=context` · `thread.carry=off` · `thread.shrink=0.5` … · `thread=auto` (the cut's) | `POST /api/report/post-item {project, op: "set", id, patch: {thread}, token}` (an object merges; `null` clears) | | a part's role — the text it reads: `parent:<i>`, `quoted`, `post`, `media:<i>` (stored, else inferred) | post bench, **thread read**: the read piece by piece (click one: the playhead at its start; `·` marks an inferred role) | `umtool posts roles <p> [<item> …]` (list, with the guard's verdict and the warnings: a link said aloud, a text cut short) · `--write` (store the inferred roles) · `<item> --set 3=parent:0,4=post` (`off`: inferred again) | — (`updatePostNarration {partRoles: {take, roles}}`) | | a read RE-JOINED without a piece (no TTS) — the picked take's kept parts cut from its own file and joined with the read's pauses: a derived take (`steps: [{op: "rejoin", drop}]`), picked | post bench, **thread read**: **Read without it** on a context piece the take reads | `umtool posts reread <p> <item> --without parent:0` (`parent:1`, `quoted`) · `--drop-parts 3,4` · `--drop-urls` · `--dry-run`; `umtool posts set-item <p> <item> thread.parent.0=context` re-joins first when the take reads it (the knob alone when it does not; `--no-reread`: refused) | `POST /api/report/post-narration {project, op: "reread", id, without: ["parent:0"], dropParts?, dropUrls?}` | +| a read's PARTS RE-TIMED (no TTS) — the parts named read at a tempo of 1–1.6 (pitch kept: ffmpeg `atempo`, or `rubberband`), the rest untouched, joined with the read's pauses; the words scaled with their part (read-follow, zooms, captions, slams, beeps keep their place); a derived take (`steps: [{op: "tempo", tempo: {"4-16": 1.35}, params: {stretch}}]`, each part's `tempo` stored), picked. A tempo is ABSOLUTE: on a re-timed take it re-cuts from the take before (each part stretched once) | — | `umtool posts reread <p> <item> --tempo-for "4-16=1.35,21-25=1.3"` · `--tempo 1.3 --parts 4-16,21-25` · `--stretch rubberband` · `--dry-run`; `umtool posts set-item <p> <item> narration.tempo="4-16=1.35"` (the same) | `POST /api/report/post-narration {project, op: "reread", id, tempo: "4-16=1.35", stretch?}` | +| a read's CAPS YELLED (no TTS) — the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the take's word timings and raised: +5.5 dB measured over the spans, a presence lift, compressed, gently saturated, limited, 50 ms ramps; acronyms (`YELL_ACRONYMS`, any caps word with no vowel) and masked slurs left flat; timings kept; loudness within 1 LU of its source; a derived take (`steps: [{op: "yell", spans, params: {gain, style}}]`), picked. Needs the take's word timings (`posts narrate --words`) | — | `umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run]` · the cut's: `umtool posts yell <p> --all \| <item …> [--dry-run]` (the dry run lists each item's caps, the ones left flat and why, and the items with no word timings) | `POST /api/report/post-narration {project, op: "reread", id, yell: true, yellGain?, yellStyle?}` | | the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | — | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) | | a post item's `conversation` (the archive row's threadId) and `quoted.via: "link"` (a status link resolved to an archived post) | — | `umtool posts context <p> [--dry-run]` | — (`setPostItemsContext`) | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -702,6 +702,82 @@ chip with its notch; the underline apart) and laid over the card (`postSegmentAr bench mount the same markup in the card frame (`mountCaptions`, `setCaptionState`) on the same curve. The post record (`<id>.post.json`) keeps each caption's time, span, place and box. +### A slam + +A post item may carry a SLAM: a corny movie-trailer title slam over the card, a joke as +a word is read (`report-to-video/post-slam.mjs`; operator, 4 Nov: "the japanese characters +of 'fudoshin' (不動心) pop in with three trailer hits like a corny effect, … gold with a +black outline, starting large and shrinking before hitting the page like standard trailer +hits"; "three hits evenly spaced over the pronunciation of the word, one for each +character"; "do it above the word on the page"; "do the same with baji quan (八极拳)"). + +```jsonc +"fx": [{ + "kind": "slam", + "text": "不動心", // ≤ 12 characters: one unit (and one hit) per glyph; "whole": true -- the text as one + "match": "Fudōshin", // the word or phrase it lands over ("Baji Quan": both words), as a word zoom's + "target": "post", "occurrence": 1, + "at": 4.2, // the first hit; absent: the words' spoken start in the take's word timings + "gap": 0.45, // seconds between hits; absent: spread over the words' spoken span + "hold": 1.6, // held after the last hit (0.3–4), then a 0.35 s fade + "fromScale": 3.5, // how big a glyph comes in (1.5–8 × its size at rest) + "color": "#f5c542", "outline": "#000000", "outlineWidth": 13, // gold, a thick black outline (px at a 120 px glyph) + "place": "over-match", // "over-match" (default): above the words' line | "center": the card's middle + "size": 120, // px at 1080; absent: 2.5 × the words' line, 64–170 + "face": "jp", // Noto Sans CJK JP | SC | TC | KR, Black (八极拳: "sc") + "sfx": "trailer-hit", // | "off" + "volume": 1, "swell": false // × the hit's level; the teaser's low swell under the hold +}] +``` + +**When**: each glyph LANDS on a hit. With word timings the hits spread evenly over the +matched words' SPOKEN span -- the first on the first word's start, the last on the last +word's end ("Baji"'s start to "Quan"'s end), the rest evenly between; `gap` spaces them +instead; `at` moves the first hit (keeping the span's length when the words give one). With +no spoken span (an `at` alone, an un-narrated post: the reading estimate's start) they are +0.45 s apart, never closer than 0.12 s. A glyph comes in 0.2 s before its landing -- the +TEASER's slam (`TEASER_MOTION`: power3.in down past rest to 0.968, a power2.out settle over +0.5 s, its blur focusing), from `fromScale` × its size and smeared, with ghost copies +trailing the shrink -- and hits with a flash behind it, a shock ring, dust thrown up, and +the frame's PUNCH (9 px at 1080, dying over 0.3 s). After the last hit it holds `hold`, +then fades over 0.35 s; the hold is shortened to end by the item's last second (a stack +card's media phase). A slam up with a word zoom is refused, two slams of a post up at once +too, and a CAPTION up with it WAITS for it to be gone (the slam first, then the chip). + +**Where**: the units side by side, centred on the matched words and just ABOVE their line; +below it when there is no room above in the frame, or when the row would cover a word being +read as a glyph lands; `center`: the card's middle. Kept in the frame. It rides the card's +pan (read-follow): every frame is placed by where the words are drawn then. + +**The one exemption** (deliberate, the gag): the landed row may cover the line ABOVE the +word -- for the slam's own window only (its hits, its hold, its fade). It is drawn OVER the +card, never in it (no `data-w`, no `data-post-block`), so the read-follow geometry and +`readInViewErrors` are measured without it; what it may NOT cover is checked instead +(`slamCoverErrors`): the matched words themselves, and the words whose read starts within +0.25 s of a hit. When neither above nor below is clear the build refuses, in its own words. +The record (`<id>.post.json` `slams`) keeps its hits, its span, its place and how many other +things drawn it lay over (`covers`). + +**The sound**: one TRAILER HIT per glyph at its landing -- the teaser's own generator +(`report-to-video/trailer-hits.mjs`, factored out of the teaser card the ferret-rescue +finale plays: a pitch-dropping sine boom with its octave, a band-passed noise punch, a low +rumble, a short echo, under a −6 dBFS limiter), its title tier -- synthesised in ffmpeg, no +samples; with `swell` the teaser's low swell under the hold. Mixed into the segment's audio +after the item's own sound and the read (no duck), under a ceiling just below full scale. + +**The render**: on the card page as drawn at the first hit, the words measured, the units +mounted at their size in the slam's face and placed, then the layer shot alone on a clear +page at every frame of its span (each distinct state once) and laid over everything in the +segment; the punch is the frame padded in the card's ground and cropped back on `t`. Play +and the bench mount the same markup in the card frame (`mountSlams`, `setSlamState`) and +shake the page's body; Play sounds each hit as its clock crosses a landing (WebAudio, the +generator's own formulas through the graph's filters -- close to the render's mix, without +its limiter). The segment key carries the slam's fields (the entry) and `slam` (its drawing +version, its motion, its hit's tier and level): an item without one keeps its key. + +From a terminal: `umtool posts fx <p> <item> add slam --text "不動心" --match "Fudōshin"` +([knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)). + ### The clock A post item may show its CLOCK (`report-to-video/post-clock.mjs`; operator, 4 Nov: "show a @@ -734,6 +810,74 @@ stack card's, until its media phase); Play and the bench mount the same chip (`mountClock`, `setClockState`) from `clockPlan`, which needs the item before it (`playView` `postClock`; the bench's `before`). +### The progress bar + +A long read may draw a PROGRESS BAR (`report-to-video/post-progress.mjs`; 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, inset +from its rounded corners -- that fills with the item's READ, with a subtle tick where each +part of the read starts. + +```jsonc +"render": { "posts": { "progress": "auto" } }, // the cut's default: auto | on | off (absent: off) +"progress": "on" // one item's (absent: the cut's) +``` + +`auto` draws it for a read of 60 s or more as the item plays it (its `rate` counted). It +fills over the read's REAL seconds -- from the narrator's first word to the last, linear -- +so a part read faster by a tempo step (below) moves it faster and it never jumps at a part's +edge; an item with no read fills over its own length. It fades in over 0.35 s as the read +starts and is gone in a stack card's media phase. Its place is judged over the read (its +start, middle and end: the place over fewest words, the words as seen, clipped to their +window) and short of the clock when that sits on its line; over a word anywhere it moves just +under the card's edge. Drawn OVER the card, never in it (`readInViewErrors` never counts it). +The render shoots its track and its fill once each on a clear page and lays them over the +card, the fill clipped at its leading edge frame by frame (`geq` on the frame's time: +`progressFilters`); Play and the bench mount the same bar (`mountProgress`, +`measureProgressPlace`, `setProgressState`) from `progressPlan` (`playView` `postProgress`). +In the segment key only for an item that draws it (`progress`: its plan and drawing version). +`umtool posts progress <p> auto|on|off|default`; one item's: `posts set-item <p> <item> +progress=on|off|auto|default`. + +### A long read sped up, and its caps yelled + +Two edits of a read that is already there -- no TTS, nothing re-synthesized -- each a DERIVED +take (`source: {kind: "take", from}`), picked in one write (one undo point), chained in either +order (`lib/report/postReread.mjs`, `lib/report/postYell.mjs`): + +- **Per-part tempo** (operator, 4 Nov: "This one is really long, what if we sped it up ... + and then slowing back down here on the juicy persecution complex paragraph"; "dynamic speed + over boring parts of a long message ... nothing too crazy"): `umtool posts reread <p> <item> + --tempo-for "4-16=1.35,21-25=1.3"` (or `--tempo 1.3 --parts 4-16,21-25`; `posts set-item + <p> <item> narration.tempo="…"`). Each part named is time-stretched to that tempo (1–1.6, + its pitch kept: ffmpeg `atempo`, `--stretch rubberband` the alternative), padded and trimmed + to its length so the parts after it land sample-exact; the others are untouched; all are + joined with the read's pauses. Its parts are re-timed (each stretched one's `tempo` + stored) and its word timings scaled with their part, so read-follow, word zooms, captions, + slams and slur beeps keep their place. `steps: [{op: "tempo", tempo: {"4-16": 1.35, + "21-25": 1.3}, params: {stretch}}]`. A tempo is ABSOLUTE (against the part's first read): + on a re-timed take it re-cuts from the take before it, so a part is stretched once, never + twice, and the parts it does not name keep the tempo they had (`1` sets one back). The cut's + `rate` still plays over the whole read: a part at 1.35 in a cut at 1.08 plays at 1.46. +- **The caps yelled** (operator, 4 Nov: "I feel like allcaps needs to be yelled more"): the + scripts are drafted with his ALL-CAPS words lowercased (a stock voice spells a caps word out + letter by letter), so the read said them flat. `umtool posts reread <p> <item> --yell-caps + [--yell-gain 5.5] [--yell-style raise|shout|loud]`, or the cut's `umtool posts yell <p> --all + | <item …>`: the words whose SOURCE word -- his post, or the piece a part reads (the post he + answers, the quote, a linked post: looked for only in the words that read it) -- is ALL CAPS + of two letters or more, found in the take's word timings (aligned like a word zoom's), and + raised over each run of them (spans padded, a run merged): louder by the lift MEASURED over + the spans (+5.5 dB), a presence lift (~3.2 kHz) and some body, compressed, a gentle tanh + saturation, limited under 0 dBFS, crossfaded in and out over 50 ms -- a voice raised, not + turned up. Left flat: acronyms and initialisms (`YELL_ACRONYMS`: FBI, DM, KF, TV, OK …; any + caps word with no vowel reads as letters) and a slur the cut masks (beeped anyway). The take's + loudness stays within 1 LU of its source (over it, the lift is lowered: an all-caps post + keeps the timbre, not the level); its length and its timings are the source's. + `steps: [{op: "yell", spans, params: {gain, style, trim?}}]`. It needs the take's word + timings (`umtool posts narrate <p> <item> --words`) and says so; `posts yell <p> --dry-run` + lists each item's caps, the ones left flat and why, and the items with no word timings. A + yell on a yelled take re-yells the take before it; one further up the chain is refused. + ### The pace `pace: "fast"` on a narrated post's narration (or `render.postNarration.pace`, the cut's) @@ -750,7 +894,8 @@ caption's text and knobs, the clock fx, the narration's `pace`, the item's id (a segment) -- and `postFxKeyFields` (`post-render.mjs`) APPENDS what the entry does not carry: `captionV` and `clockV` (the chip's and the clock's drawing, bumped when their look changes), `clock` (the plan: this post's time, the time it runs from -- the item before's, when that one is a clock item -- the mode, a forced rewind, -the zone) and `pace` (the gap knobs a cut-level pace resolved to). An item with none of these adds nothing, so +the zone), `pace` (the gap knobs a cut-level pace resolved to) and `progress` (the progress bar's plan and its +drawing version, only for an item that draws it). An item with none of these adds nothing, so its key is the one it had before they existed and a take `--from` an earlier one reuses its segment. A take `--from` another hard-links a post item's record (`.post.json`) and its combo pass's files (`.combo.json`, `.plain.mp4`) with its segment (`SEGMENT_FILE_SUFFIXES`), and a post item's files are no longer detached before @@ -1895,6 +2040,17 @@ pruning them, where a `--from` twin finds them. The blur is in the segments' pic twin rebuilds the blurred clips, their crossfade batches and the final overlay pass, and reuses the rest. +**A small fix is a few minutes, not a whole render.** A take renders hard cuts (`--no-xfade`, unless it sets a transition), and +its final picture is encoded in keyed CHUNKS, one segment's run each (report-to-video +`chunked-encode.mjs`): a chunk is encoded again only when its segment or the deck frames over it +changed. A post that grew or shrank moves every later chunk without changing it -- the deck's frames +after it are the same frames, later -- so `--from` the take before re-encodes only the touched +post's chunks. The deck's frames themselves are keyed by what they draw, and a take draws only the +ones its chunks to encode read: a twin of a pruned take captures the touched post's frames, not the +whole cut's again (about 90 s for a 31-minute cut). `UMTOOL_CHROME_LAZY=0` draws them all. The cut's sound +is one pass (about 90 s, begun beside the capture), reused when no segment's sound changed (a +caption or a knob that moves no word keeps it). + A layer whose page changed reuses its frames FRAME BY FRAME (report-to-video `frame-keys.mjs`, each module's `frameKeys`: the deck, the stamps, the feed, the finale, the thread rail, the flips, the stats, the effects and a teaser): every frame's key is the page's static part and what is on screen @@ -1966,6 +2122,51 @@ auto-picked over it (`--unpin`, or picking another, lets go). The gate this remo takes and none picked, Re-render the take had no target and the only way on was to pick one. +### The render pool + +Every unit a build makes is filed in ONE pool shared by every take of every project, under the hash +of its full input key, and every build looks there when its own `out/` misses (report-to-video +`render-pool.mjs`; operator, 4 Nov: "every clip that could be inserted into a video is put into a +shared cached clip pool by all input params by default"): + +| kind | the unit | its key | +| --- | --- | --- | +| `post` | a post item's segment and its `.post.json` | `postSegmentKeyOf` (post-render.mjs): the entry, its plan, the box, the encode, its files' stamps, the narration | +| `clip` | a clip segment and its `.cut.json` | `segmentKey` (segment-cache.mjs): the ffmpeg argv, every input by its identity, the cut record | +| `chunk` | a chunk of the final encode | `chunkKey` (chunked-encode.mjs): its inputs' contents, its graph in its own clock -- position-free | +| `sound` | the cut's sound | the pins' and the encode's argv, each segment's sound | +| `frame` | one chrome frame | its frame key (frame-keys.mjs): what it draws | + +A hit is HARD-LINKED into the take; a miss, once built, is linked into the pool through a tmp +directory renamed into place. A link, never a copy: while a take holds an object the pool costs no +disk, and since a build replaces its files rather than writing through them, neither side can change +the other's bytes. Each kind carries a renderer salt (`POOL_KINDS`), bumped when code changes what a +unit is for the same inputs; the build's own key versions are in the keys too. +`render-pool.test.mjs` mutates every field of a fixture post, chunk, sound and clip and fails if one +leaves its key as it was. + +So `--from` keeps working but is no longer needed: a take finds any unit any take built. A unit a +build reuses from its own `out/` that the pool has not got (built before the pool, or linked in by +`--from`) is filed then, so the first build after the pool fills it. A take +stopped mid-render and run again finds every chunk it finished, in its own `out/` or in the pool. + +- **Where:** `UMTOOL_RENDER_POOL` (a directory), else `<media root>/.render-pool` (`UMTOOL_MEDIA_DIR`'s, + else the reports root's) -- for an `out/` under that root only, so a test's or a scratch copy's + build never writes the operator's pool; another filesystem (no hard link) is no pool. + `UMTOOL_RENDER_POOL=0` turns it off. +- **Disk:** `UMTOOL_RENDER_POOL_MAX_GB` (default 30) caps the bytes only the pool holds -- objects no + take links. Over it, the least recently used go first, at the end of a build (at most hourly) or by + `umtool pool prune`; an object a take links -- a pinned or picked take's, a running build's -- is + never evicted. The disk guard before a render, still under its threshold after pruning takes' + work files, has the pool give back what only it holds, by the deficit. +- **`umtool pool [stats|prune|verify] [--json]`:** what it holds by kind, its hits and misses + (`--since 7d`), the biggest objects; an eviction down to the cap (`--max-gb`, `--dry-run`); a check + of a sample (`--sample N`, `--all`) against the sha256 each file was put in with. +- **Not yet pooled:** image, card, narrated card, teaser and intro segments (each cheap, or cached by + a key of its own in the take), the combo badge's pass. A post item's key names its files by path + (its stamps, the avatars), so it is shared by every take of a project but not across two projects + that hold the same files at different paths. + ### Render mode: giving a render the machine A render you are waiting for is slowed by what else the machine does — the transcription diff --git a/umtool/e2e/long-reads.spec.ts b/umtool/e2e/long-reads.spec.ts @@ -0,0 +1,184 @@ +import { test, expect, type Page } from "@playwright/test"; +import { spawnSync } from "node:child_process"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// LONG READS (operator, 4 Nov, a 6.5-minute post): a read's parts RE-TIMED with +// no TTS (lib/report/postReread.mjs tempoPlan: the parts named faster, pitch +// kept, the words scaled with them), its caps YELLED (lib/report/postYell.mjs), +// and the PROGRESS BAR along the card's foot (report-to-video/post-progress.mjs) +// that fills over the read's real seconds -- in the bench and in Play. +// Fixture: e2e/fixtures/post-narration-fixture.mjs -- p-11, given here a take +// of three timed parts (6.6 s of tone, its words timed) and progress "on". +// +// LONG_READS_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.LONG_READS_SHOTS ?? null; +const TAKE = "narration/posts/11/take-7.parts-zac.wav"; +const TEXT = "The video speaks for ITSELF.\n\nThen it says it AGAIN, louder.\n\nAnd that is all."; + +type Part = { n: number; para: number; text: string; start: number; seconds: number; tempo?: number }; +type Take = { file: string; seconds: number; parts?: Part[]; words?: Array<{ w: string; start: number; end: number }>; steps?: Array<Record<string, unknown>>; source?: { kind: string; from?: string } }; +type Entry = { id: string; progress?: string; text?: string; narration?: { takes: Take[]; pick?: number; script?: string } }; +const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record<string, unknown> }; +const p11 = () => manifest().timeline.find((e) => e.id === "p-11")!; +const picked = () => { + const n = p11().narration!; + return n.takes[n.pick ?? 0]; +}; + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); + // A take of three parts: 2 s, 2 s, 1.4 s of tone with the read's pauses (0.6 s), every word timed. + const file = path.join(DIR, ...TAKE.split("/")); + const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='0.2*sin(2*PI*220*t)*(0.6+0.4*sin(2*PI*4*t))*(lt(t,2)+between(t,2.6,4.6)+between(t,5.2,6.6))':s=24000:d=6.6", file]); + if (r.status !== 0) throw new Error(String(r.stderr)); + const script = TEXT.replace("ITSELF", "itself").replace("AGAIN", "again"); + const words: Array<{ w: string; start: number; end: number }> = []; + const parts: Part[] = script.split("\n\n").map((text, i) => ({ n: i + 1, para: i, text, start: [0, 2.6, 5.2][i], seconds: [2, 2, 1.4][i] })); + for (const p of parts) { + const ws = p.text.split(/\s+/); + ws.forEach((w, j) => words.push({ w, start: Math.round((p.start + (j * p.seconds) / ws.length) * 1000) / 1000, end: Math.round((p.start + ((j + 0.8) * p.seconds) / ws.length) * 1000) / 1000 })); + } + const m = manifest(); + const e = m.timeline.find((x) => x.id === "p-11")!; + e.text = TEXT; + e.progress = "on"; + e.narration = { ...e.narration!, script, takes: [...e.narration!.takes, { file: TAKE, engine: "orpheus", voice: "zac", seconds: 6.6, script, words, parts } as Take], pick: e.narration!.takes.length }; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); +}); + +/** In the card frame: the bar's box and its fill's clip, the counts row's box, the card words' boxes. */ +const barBoxes = (page: Page) => + page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body) => { + const doc = body.ownerDocument; + const r = (el: Element | null) => { + if (!el) return null; + const b = el.getBoundingClientRect(); + return { x: b.left, y: b.top, width: b.width, height: b.height }; + }; + const bar = doc.querySelector("[data-post-progress]") as HTMLElement | null; + return { + bar: r(bar), + opacity: bar ? Number(bar.style.opacity) : null, + frac: bar ? Number(bar.getAttribute("data-frac")) : null, + ticks: doc.querySelectorAll(".pprog-tick").length, + inCard: !!bar?.closest("[data-post-card]"), + counts: r(doc.querySelector("[data-post-counts]")), + card: r(doc.querySelector("[data-post-card]")), + words: Array.from(doc.querySelectorAll("[data-w]")).map((w) => r(w)!), + }; + }); +const overlap = (a: { x: number; y: number; width: number; height: number }, b: { x: number; y: number; width: number; height: number }) => + 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)); + +test("PER-PART TEMPO, no TTS: the route's reread with tempo \"2=1.5\" makes a derived take -- part 2 shorter by 1.5, its words scaled, the rest untouched -- picked; a re-tune cuts from the first read", async ({ page }) => { + const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.5" } }); + expect(res.ok(), await res.text()).toBeTruthy(); + const t = picked(); + expect(t.file).toMatch(/take-\d+\.tempo-orpheus\.wav$/); + expect(t.steps?.[0]).toMatchObject({ op: "tempo", tempo: { 2: 1.5 }, params: { stretch: "atempo" } }); + expect(t.parts!.map((p) => [p.start, p.seconds, p.tempo ?? 1])).toEqual([[0, 2, 1], [2.6, 1.333, 1.5], [4.533, 1.4, 1]]); + expect(Math.abs(t.seconds - 5.933)).toBeLessThan(0.02); + // The words of part 2 scaled from its start; part 3's moved up by what part 2 lost. + const then = t.words!.find((w) => w.w === "Then")!; + const again = t.words!.find((w) => w.w === "again,")!; + const and = t.words!.find((w) => w.w === "And")!; + expect([then.start, and.start]).toEqual([2.6, 4.533]); + // "again," began 1.333 s into part 2: 0.889 s into it now. + expect(again.start - 2.6).toBeCloseTo(1.333 / 1.5, 2); + // A re-tune: 2=1.2 is cut from the three-part take, not the re-timed one. + const res2 = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.2" } }); + expect(res2.ok(), await res2.text()).toBeTruthy(); + expect(picked().source).toEqual({ kind: "take", from: "take-7.parts-zac" }); + expect(picked().parts!.map((p) => p.tempo ?? 1)).toEqual([1, 1.2, 1]); + // Out of range: refused in the tool's words. + const bad = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.9" } }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error).toMatch(/a tempo is 1–1\.6/); +}); + +test("THE CAPS YELLED: the route's reread with yell makes a derived take of the same length and timings, its spans over ITSELF and AGAIN, picked", async ({ page }) => { + const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", yell: true } }); + expect(res.ok(), await res.text()).toBeTruthy(); + const t = picked(); + expect(t.file).toMatch(/take-\d+\.yell-orpheus\.wav$/); + expect(t.steps?.[0]).toMatchObject({ op: "yell", params: { style: "raise" } }); + const spans = t.steps![0].spans as number[][]; + expect(spans).toHaveLength(2); + const itself = t.words!.find((w) => w.w === "itself.")!; + const again = t.words!.find((w) => w.w === "again,")!; + expect(spans[0][0]).toBeLessThanOrEqual(itself.start); + expect(spans[1][0]).toBeLessThanOrEqual(again.start); + expect(Math.abs(t.seconds - 6.6)).toBeLessThan(0.02); + expect(t.parts!.map((p) => p.start)).toEqual([0, 2.6, 5.2]); +}); + +test("THE PROGRESS BAR on the bench: along the card's foot under its counts row, over no word, ticked at the parts, filling linearly with the read -- and after a tempo, no jump", async ({ page }) => { + await page.setViewportSize({ width: 1500, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-progress", "0", { timeout: 15_000 }); + await expect(player).toHaveAttribute("data-post-progress-place", /\d+,\d+,\d+/); + let g = await barBoxes(page); + expect(g.bar).not.toBeNull(); + expect(g.inCard, "drawn over the card, never in it").toBe(false); + expect(g.ticks).toBe(2); + expect(g.bar!.y).toBeGreaterThanOrEqual(g.counts!.y + g.counts!.height); + expect(g.bar!.y + g.bar!.height).toBeLessThanOrEqual(g.card!.y + g.card!.height + 1); + for (const w of g.words) expect(overlap(g.bar!, w)).toBe(0); + // Play it: the fill follows the read. + await page.locator("[data-post-bench-play]").click(); + await expect.poll(async () => Number(await player.getAttribute("data-post-progress")), { timeout: 15_000 }).toBeGreaterThan(0.3); + await page.locator("[data-post-bench-play]").click(); + g = await barBoxes(page); + expect(g.opacity).toBe(1); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "long-reads-bench-progress.png") }); + // Its fill is real time over the read: at a second of the item, (s - lead) / read. + const s = Number(await player.getAttribute("data-post-s")); + const frac = Number(await player.getAttribute("data-post-progress")); + const lead = 0.4; + expect(Math.abs(frac - Math.min(1, Math.max(0, (s - lead) / 6.6)))).toBeLessThan(0.02); +}); + +test("THE PROGRESS BAR in Play, with the read re-timed: it fills over the new read's seconds, monotonic across the faster part", async ({ page }) => { + const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.5" } }); + expect(res.ok(), await res.text()).toBeTruthy(); + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-progress", "0", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + const seen: Array<[number, number]> = []; + await expect + .poll(async () => { + const s = Number(await player.getAttribute("data-post-s")); + const f = Number(await player.getAttribute("data-post-progress")); + seen.push([s, f]); + return f; + }, { timeout: 20_000, intervals: [150] }) + .toBeGreaterThan(0.95); + await page.locator("[data-play-toggle]").click(); + // Monotonic, and never a jump: each step of the fill is the step of the clock over the read's 5.933 s. + for (let i = 1; i < seen.length; i += 1) { + const [s0, f0] = seen[i - 1]; + const [s1, f1] = seen[i]; + expect(f1).toBeGreaterThanOrEqual(f0); + if (f0 > 0 && f1 < 1) expect(Math.abs(f1 - f0 - (s1 - s0) / 5.933)).toBeLessThan(0.03); + } + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "long-reads-play-progress.png") }); +}); diff --git a/umtool/e2e/post-slam.spec.ts b/umtool/e2e/post-slam.spec.ts @@ -0,0 +1,119 @@ +import { test, expect, type Page } from "@playwright/test"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// A POST ITEM's SLAM (report-to-video/post-slam.mjs; knobs.md, "A slam"): a +// trailer-style title slam -- each glyph huge, shrinking onto the card just +// above the matched words and hitting, one trailer hit per glyph. Fixture: +// e2e/fixtures/post-narration-fixture.mjs -- p-11 "The video speaks for +// itself." narrated by a 2 s take (no word timings: the reading estimate), +// p-13 words only. +// +// POST_SLAM_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.POST_SLAM_SHOTS ?? null; + +type Entry = { id: string; fx?: Array<Record<string, unknown>> }; +const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record<string, unknown> }; +const timeline = () => manifest().timeline; + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); +}); + +type Box = { x: number; y: number; width: number; height: number }; +const overlap = (a: Box, b: Box) => 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)); +/** In the card frame: each slam unit's glyph box, and the card words'. */ +const slamBoxes = (page: Page) => + page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body) => { + const r = (el: Element) => { + const b = el.getBoundingClientRect(); + return { x: b.left, y: b.top, width: b.width, height: b.height }; + }; + const doc = body.ownerDocument; + return { + units: Array.from(doc.querySelectorAll(".pslam")).map((el) => ({ id: el.getAttribute("data-post-fx-slam"), opacity: Number((el as HTMLElement).style.opacity), text: el.querySelector(".pslam-front")?.textContent ?? "", ...r(el.querySelector(".pslam-front")!) })), + words: Array.from(doc.querySelectorAll("[data-w]")).map((w) => ({ id: w.getAttribute("data-w"), ...r(w) })), + inCard: Array.from(doc.querySelectorAll(".pslam")).some((el) => el.closest("[data-post-card]") !== null || !!el.querySelector("[data-w], [data-post-block]")), + }; + }); + +/** Play the item until every glyph has landed, then pause. */ +async function playUntilLanded(page: Page, id: string, n: number) { + const player = page.locator(`[data-post-play="${id}"]`); + await expect(player).toHaveAttribute("data-post-slams", "1", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + await expect(player).toHaveAttribute("data-post-slam-landed", String(n), { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + return player; +} + +test("A SLAM (operator, 4 Nov: 不動心 on \"Fudōshin\"): click a word -> type the glyphs -> Slam here -> saved; the bench marks its hits; Play lands three gold glyphs in a row just ABOVE the word, over no word of it, drawn over the card", async ({ page }) => { + await page.setViewportSize({ width: 1500, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const panel = page.locator('[data-post-zoom-panel="p-11"]'); + await panel.locator('[data-post-zoom-word="2"]').click(); + await expect(panel.locator("[data-post-slam-here]")).toBeDisabled(); + await panel.locator("[data-post-slam-text]").fill("不動心"); + await panel.locator("[data-post-slam-here]").click(); + await expect(panel.locator('[data-post-slam-fx="0"]')).toBeVisible(); + expect(timeline().find((e) => e.id === "p-11")!.fx).toEqual([{ kind: "slam", match: "speaks", text: "不動心" }]); + // No word timings: three hits from the reading estimate's start, SLAM_GAP apart. + await expect(panel.locator('[data-post-slam-fx="0"]')).toContainText("the estimate"); + await expect(page.locator('[data-post-bench-slam-mark="0"]')).toBeVisible(); + await expect(page.locator('[data-post-bench-slam-mark="0"] [data-post-bench-slam-hit]')).toHaveCount(3); + await expect(page.locator('[data-post-play="p-11"]')).toHaveAttribute("data-post-slams", "1", { timeout: 15_000 }); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-slam-bench.png") }); + + // Play the cut: the three glyphs land, left to right, above the word. + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); + const player = await playUntilLanded(page, "p-11", 3); + await expect(player).toHaveAttribute("data-post-slam-where", "above"); + const { units, words, inCard } = await slamBoxes(page); + expect(units.map((u) => u.text)).toEqual(["不", "動", "心"]); + expect(units.every((u) => u.opacity > 0)).toBe(true); + expect(units[0].x).toBeLessThan(units[1].x); + expect(units[1].x).toBeLessThan(units[2].x); + // Never over the word it lands on; sitting above its line; never in the card's words. + const word = words.find((w) => w.id === "post:2")!; + for (const u of units) { + expect(overlap(u, word)).toBe(0); + expect(u.y + u.height).toBeLessThanOrEqual(word.y + 2); + } + const mid = (units[0].x + units[2].x + units[2].width) / 2; + expect(Math.abs(mid - (word.x + word.width / 2))).toBeLessThan(word.width); + expect(inCard).toBe(false); + // The CJK is drawn by a face this machine has, at its Black weight. + expect(await page.frameLocator('[data-post-card-frame="read"]').locator(".pslam").first().evaluate((el) => el.ownerDocument.fonts.check("900 100px 'Noto Sans CJK JP'", "不動心"))).toBe(true); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-slam-play.png") }); +}); + +test("A PHRASE (operator, 4 Nov: 八极拳 on \"Baji Quan\"): a two-word match, the SC face, three glyphs over the phrase; an at and no word span: the hits SLAM_GAP apart from it", async ({ page }) => { + const m = manifest(); + Object.assign(m.timeline.find((e) => e.id === "p-13")!, { fx: [{ kind: "slam", text: "八极拳", match: "waiting for", face: "sc", at: 0.5 }] }); + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); + await page.setViewportSize({ width: 1500, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-13" })); + await playUntilLanded(page, "p-13", 3); + const { units, words } = await slamBoxes(page); + expect(units.map((u) => u.text)).toEqual(["八", "极", "拳"]); + const phrase = words.filter((w) => w.id === "post:2" || w.id === "post:3"); + expect(phrase).toHaveLength(2); + for (const u of units) for (const w of phrase) expect(overlap(u, w)).toBe(0); + expect(await page.frameLocator('[data-post-card-frame="read"]').locator(".pslam").first().evaluate((el) => el.ownerDocument.fonts.check("900 100px 'Noto Sans CJK SC'", "八极拳"))).toBe(true); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-slam-phrase.png") }); +}); 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/poolCli.mjs b/umtool/lib/report/poolCli.mjs @@ -0,0 +1,74 @@ +// `umtool pool [stats|prune|verify] [--json]` -- the render pool +// (report-to-video render-pool.mjs): what it holds, its hits and misses per +// kind, the biggest objects; an eviction down to its cap; a check of a sample. +// +// umtool pool [stats] [--since 7d] [--json] +// umtool pool prune [--max-gb N] [--dry-run] [--json] +// umtool pool verify [--sample N | --all] [--json] +// +// `--pool <dir>` (or UMTOOL_RENDER_POOL) names another pool. +import { MEDIA_ROOT } from "../paths.mjs"; +import { POOL_KINDS, poolFor, poolMaxBytes, poolPrune, poolStats, poolVerify } from "umtool-report-to-video/render-pool"; + +const USAGE = "usage: umtool pool [stats|prune|verify] [--pool DIR] [--since 7d] [--max-gb N] [--dry-run] [--sample N | --all] [--json]"; +const mib = (b) => `${(b / (1 << 20)).toFixed(0)} MiB`; + +/** `7d`, `12h`, `30m` -> ms; null when absent. */ +function sinceMs(v) { + const m = /^(\d+(?:\.\d+)?)([dhm])$/.exec(String(v ?? "")); + if (!m) return null; + return Number(m[1]) * { d: 86_400_000, h: 3_600_000, m: 60_000 }[m[2]]; +} + +/** @param {string[]} args @returns {Promise<number>} the exit code */ +export async function poolCommand(args, { log = console.log, env = process.env } = {}) { + const flag = (n) => { + const i = args.indexOf(n); + return i >= 0 ? args[i + 1] : undefined; + }; + const json = args.includes("--json"); + const sub = args[0] && !args[0].startsWith("--") ? args[0] : "stats"; + const pool = flag("--pool") ?? (await poolFor(MEDIA_ROOT, env)); + if (!pool) { + log("the render pool is off (UMTOOL_RENDER_POOL=0)"); + return 0; + } + if (sub === "stats") { + const since = sinceMs(flag("--since")); + const s = await poolStats(pool, { since: since ? Date.now() - since : 0 }); + if (json) log(JSON.stringify(s, null, 2)); + else { + log(`render pool ${pool}: ${s.objects} object(s), ${mib(s.bytes)}; ${mib(s.onlyPool)} held by the pool alone (cap ${mib(s.maxOnlyPool)})`); + for (const [k, v] of Object.entries(s.kinds)) { + const all = v.hits + v.misses; + log(` ${k.padEnd(6)} ${String(v.objects).padStart(7)} ${POOL_KINDS[k].noun.padEnd(20)} ${mib(v.bytes).padStart(10)} ${v.hits} hit(s), ${v.misses} miss(es)${all ? ` (${Math.round((100 * v.hits) / all)} %)` : ""}`); + } + if (s.biggest.length) log(" biggest:"); + for (const b of s.biggest) log(` ${mib(b.bytes).padStart(9)} ${b.kind} ${b.path}${b.linked ? " (a take links it)" : ""}`); + } + return 0; + } + if (sub === "prune") { + const gb = flag("--max-gb"); + const maxBytes = gb !== undefined ? Number(gb) * 1024 ** 3 : poolMaxBytes(env); + if (!Number.isFinite(maxBytes) || maxBytes < 0) { + log(USAGE); + return 2; + } + const r = await poolPrune(pool, { maxBytes, dryRun: args.includes("--dry-run") }); + if (json) log(JSON.stringify(r, null, 2)); + else log(`render pool: ${args.includes("--dry-run") ? "would evict" : "evicted"} ${r.evicted} object(s), ${mib(r.bytes)}; held by the pool alone ${mib(r.before)} -> ${mib(r.after)} (cap ${mib(r.maxBytes)}; an object a take links is never evicted)`); + return 0; + } + if (sub === "verify") { + const r = await poolVerify(pool, { sample: Number(flag("--sample") ?? 50), all: args.includes("--all") }); + if (json) log(JSON.stringify(r, null, 2)); + else { + log(`render pool: checked ${r.checked} of ${r.of} object(s): ${r.problems.length ? `${r.problems.length} problem(s)` : "all as put in"}`); + for (const p of r.problems) log(` ${p}`); + } + return r.problems.length ? 1 : 0; + } + log(USAGE); + return 2; +} diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs @@ -111,3 +111,31 @@ test("posts fx add caption: the chip's text kept (CJK too), timed by the reading r = await cli(["fx", "cap", "p-1", "ls", "--json"]); assert.deepEqual(JSON.parse(r.out).times, [{ i: 0, t: 1.5, source: "at" }]); }); + +test("posts fx add slam: its glyphs and word kept, its hits listed (the estimate's start, 0.45 s apart), its knobs set -- a zoom's refused on it, its own on a zoom", async () => { + const p = await project("slam", [item("1")]); + let r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "不動心", "--match", "barbecue"]); + assert.equal(r.code, 0, r.err); + // "barbecue" is word 7: 1 + 7/3. + assert.match(r.out, /#1 slam "不動心" on "barbecue" \(post, 1st\) hits at 3\.33, 3\.78, 4\.23 s \(the reading estimate\), gone by 6\.18 s · per glyph, 3\.5× in, held 1\.6 s, over-match, #f5c542\/#000000, face jp, sfx trailer-hit/); + r = await cli(["fx", "slam", "p-1", "set", "1", "--gap", "0.3", "--face", "sc", "--from-scale", "4", "--whole", "--swell", "--volume", "0.8"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).timeline[0].fx, [{ kind: "slam", text: "不動心", match: "barbecue", gap: 0.3, face: "sc", fromScale: 4, whole: true, swell: true, volume: 0.8 }]); + r = await cli(["fx", "slam", "p-1", "set", "1", "--per-glyph", "--no-swell", "--gap", "default"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).timeline[0].fx[0], { kind: "slam", text: "不動心", match: "barbecue", face: "sc", fromScale: 4, volume: 0.8 }); + r = await cli(["fx", "slam", "p-1", "ls", "--json"]); + assert.deepEqual(JSON.parse(r.out).times[0].landings, [3.33, 3.78, 4.23]); + r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "心", "--match", "barbecue", "--scale", "2"]); + assert.equal(r.code, 2); + assert.match(r.err, /--scale is not a slam's knob/); + r = await cli(["fx", "slam", "p-1", "add", "word-zoom", "--match", "myself", "--at", "1", "--from-scale", "2"]); + assert.equal(r.code, 2); + assert.match(r.err, /--from-scale is a slam's knob/); + r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "心", "--match", "nowhere"]); + assert.equal(r.code, 1); + assert.match(r.err, /match "nowhere" is not in the post's words/); + r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "心"]); + assert.equal(r.code, 2); + assert.match(r.err, /add slam needs --match/); +}); diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs @@ -10,6 +10,10 @@ // [--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> add slam --text "不動心" [--match "…" | --at s] [--whole | --per-glyph] [--gap s] +// [--hold s] [--from-scale x] [--color #] [--outline #] [--outline-width px] +// [--place over-match|center] [--size px] [--face jp|sc|tc|kr] [--sfx trailer-hit|off] +// [--volume x] [--swell | --no-swell] (post-slam.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>] @@ -23,6 +27,7 @@ import { } from "umtool-report-to-video/word-zoom"; import { CAPTION_DEFAULTS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; import { CLOCK_REWINDS, CLOCK_ZONE, clockFace, clockOn, clockZoneOf } from "umtool-report-to-video/post-clock"; +import { SLAM_DEFAULTS, SLAM_FACES, SLAM_GAP, SLAM_PLACES, SLAM_SFX, resolveSlam, slamLandings, slamSpan, slamTimes } from "umtool-report-to-video/post-slam"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostClock, updatePostFx, updatePostNarration } from "./manifest.mjs"; @@ -35,6 +40,9 @@ export const FX_USAGE = [ " 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> add clock [--rewind auto|on|off] [--off]", + " umtool posts fx <project> <item> add slam --text \"不動心\" [--match \"…\" | --at s] [--whole | --per-glyph] [--gap s] [--hold s]", + " [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match|center]", + " [--size px] [--face jp|sc|tc|kr] [--sfx trailer-hit|off] [--volume x] [--swell | --no-swell] [--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", @@ -53,14 +61,27 @@ export const FX_USAGE = [ " before it in its first 0.8 s -- forward with the gap flashing (\"+38 min\"), or REWOUND when this post is earlier", " (⟲ rewind). --rewind off cuts straight to it, on rewinds anyway; --off: no clock on this item though the cut's is", " on (umtool posts clock <p> on).", + " A SLAM: a corny movie-trailer title slam -- each glyph of --text (--whole: the text as one) comes in huge", + ` (--from-scale, ${SLAM_DEFAULTS.fromScale}×) and blurred, shrinks onto the card and HITS (a flash, dust, the frame's punch, a trailer`, + " hit's boom), gold with a black outline, in a row just above --match's line (--place center: the card's middle).", + " WHEN: the hits spread evenly over the matched words' spoken span in the take's word timings (the first on its", + ` first word's start, the last on its last word's end); --gap s spaces them instead; --at moves the first hit (no span:`, + ` ${SLAM_GAP} s apart). Held --hold s after the last (${SLAM_DEFAULTS.hold}), then gone; a caption up with it waits for it.`, + ` --size px at 1080 (default: by the word's line), --face ${SLAM_FACES.join("|")} (the CJK forms, ${SLAM_DEFAULTS.face}), --sfx ${SLAM_SFX.join("|")},`, + " --volume × the hit's level (1), --swell the teaser's low swell under the hold.", ].join("\n"); export class FxError extends Error {} -const NUM_KEYS = { "--at": "at", "--scale": "scale", "--hold": "hold", "--lead": "lead", "--occurrence": "occurrence" }; +const NUM_KEYS = { + "--at": "at", "--scale": "scale", "--hold": "hold", "--lead": "lead", "--occurrence": "occurrence", + "--gap": "gap", "--from-scale": "fromScale", "--outline-width": "outlineWidth", "--size": "size", "--volume": "volume", +}; +/** A slam's own knobs (the CLI refuses them on another kind, and another kind's on a slam). */ +const SLAM_ONLY = ["gap", "fromScale", "outlineWidth", "size", "volume", "color", "outline", "face", "sfx", "whole", "swell"]; -/** The flags as an effect patch (null: back to the default). */ -export function fxPatchOf(str) { +/** The flags as an effect patch (null: back to the default). `has`: a bare flag's presence (--whole, --swell). */ +export function fxPatchOf(str, has = () => false) { const out = {}; const m = str("--match"); if (m !== null) out.match = m; @@ -84,6 +105,14 @@ export function fxPatchOf(str) { if (pl !== null) out.place = pl === "default" ? null : pl; const e = str("--ease"); if (e !== null) out.ease = e === "default" ? null : e; + for (const [flag, key] of [["--color", "color"], ["--outline", "outline"], ["--face", "face"], ["--sfx", "sfx"]]) { + const v = str(flag); + if (v !== null) out[key] = v === "default" ? null : v; + } + if (has("--whole")) out.whole = true; + if (has("--per-glyph")) out.whole = null; + if (has("--swell")) out.swell = true; + if (has("--no-swell")) out.swell = null; const h = str("--highlight"); if (h !== null) out.highlight = h === "default" ? null : ["off", "none", "false", "no"].includes(h.toLowerCase()) ? false : h; return out; @@ -99,10 +128,24 @@ export function fxLines(e, render) { const ctimes = captionTimes(e, render); const nz = list.filter((f) => f?.kind === "word-zoom").length; const nc = list.filter((f) => f?.kind === "caption").length; + const ns = list.filter((f) => f?.kind === "slam").length; const clk = list.some((f) => f?.kind === "clock"); + const stimes = ns ? slamTimes(e, render) : []; return [ - `${e.id}: ${nz} word zoom(s), ${nc} caption(s)${clk ? ", its clock" : ""}${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`, + `${e.id}: ${nz} word zoom(s), ${nc} caption(s)${ns ? `, ${ns} slam(s)` : ""}${clk ? ", its clock" : ""}${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`, ...list.map((fx0, i) => { + if (fx0?.kind === "slam") { + const sl = resolveSlam(fx0); + const t = stimes[i]; + let when; + if (t.error) when = `NO TIME -- ${t.error}`; + else { + const L = slamLandings(fx0, { t: t.t, end: t.end ?? null }); + const sp = slamSpan(fx0, L); + when = `hits at ${L.map((x) => x.toFixed(2)).join(", ")} s (${t.source === "words" ? "spread over the words' spoken span" : t.source === "at" ? "from its at" : "the reading estimate"}), gone by ${sp.t3 ?? "?"} s`; + } + return ` #${i + 1} slam "${sl.text}"${typeof fx0.match === "string" ? ` on "${sl.match}" (${sl.target}, ${nth(sl.occurrence)})` : ""} ${when} · ${sl.whole ? "whole" : "per glyph"}, ${sl.fromScale}× in, held ${sl.hold} s, ${sl.place}, ${sl.color}/${sl.outline}, face ${sl.face}, sfx ${sl.sfx}${sl.volume !== 1 ? ` ×${sl.volume}` : ""}${sl.swell ? ", swell" : ""}${sl.size ? `, ${sl.size} px` : ""}`; + } if (fx0?.kind === "clock") { const on = fx0.on !== false; return ` #${i + 1} clock ${on ? `on -- ${clockFace(Date.parse(e.date), clockZoneOf(render)).time} ${clockFace(Date.parse(e.date), clockZoneOf(render)).date}, rewind ${fx0.rewind ?? "auto"}` : "off (the cut's clock not shown here)"}`; @@ -122,7 +165,7 @@ export function fxLines(e, render) { } /** `umtool posts fx …` (postsCli.mjs routes it here). */ -export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str, off = false }) { +export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str, off = false, has = () => false }) { const manifest = await readManifest(project.dir); if (!manifest) throw new FxError(`${project.id} has no manifest`); const render = manifest.render ?? {}; @@ -133,7 +176,12 @@ export async function fxCommand(project, words, { json = false, out = (s) => con const say = (entry, extra = {}) => { 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)); + const st = slamTimes(entry, render).map((t, i) => { + if (entry.fx?.[i]?.kind !== "slam" || t.error) return t; + const landings = slamLandings(entry.fx[i], { t: t.t, end: t.end ?? null }); + return { ...t, landings, span: slamSpan(entry.fx[i], landings) }; + }); + 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] : entry.fx?.[i]?.kind === "slam" ? st[i] : t)), ...extra }, null, 2)); } else out(fxLines(entry, render).join("\n")); }; @@ -147,8 +195,18 @@ export async function fxCommand(project, words, { json = false, out = (s) => con return 0; } if (verb === "add") { - if (arg !== "word-zoom" && arg !== "caption" && arg !== "clock") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\" | add clock"); - const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null)); + if (arg !== "word-zoom" && arg !== "caption" && arg !== "clock" && arg !== "slam") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\" | add clock | add slam --text \"…\" --match \"…\""); + const patch = Object.fromEntries(Object.entries(fxPatchOf(str, has)).filter(([, v]) => v !== null)); + if (arg === "slam") { + for (const k of ["scale", "ease", "highlight", "lead", "rewind"]) if (k in patch) throw new FxError(`--${k} is not a slam's knob`); + if (typeof patch.text !== "string" || !patch.text.trim()) throw new FxError("add slam needs --text \"<the glyphs that slam in>\""); + if ((typeof patch.match !== "string" || !patch.match.trim()) && patch.at === undefined) throw new FxError("add slam needs --match \"<the word it lands on>\" (or --at s with --place center)"); + if (patch.place !== undefined && !SLAM_PLACES.includes(patch.place)) throw new FxError(`--place is ${SLAM_PLACES.join(" or ")} for a slam`); + const { result } = await write({ add: { kind: "slam", ...patch } }); + say(result.entry, { index: result.index }); + return 0; + } + for (const k of SLAM_ONLY) if (k in patch) throw new FxError(`--${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} is a slam's knob (add slam …)`); if (arg === "clock") { const extra = Object.keys(patch).filter((k) => k !== "rewind"); if (extra.length) throw new FxError(`--${extra[0]} is not a clock's knob (--rewind ${CLOCK_REWINDS.join("|")}, --off)`); @@ -183,8 +241,8 @@ 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, --hold, --lead, --occurrence, --target; a zoom's --scale, --ease, --highlight; a caption's --text, --place"); + const patch = fxPatchOf(str, has); + 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; a slam's --text, --gap, --from-scale, --color, --outline, --outline-width, --place, --size, --face, --sfx, --volume, --whole/--per-glyph, --swell/--no-swell"); const { result } = await write({ set: i, patch }); say(result.entry); return 0; diff --git a/umtool/lib/report/postReread.mjs b/umtool/lib/report/postReread.mjs @@ -23,7 +23,7 @@ import { execFile } from "node:child_process"; import { mkdir, readdir, rm, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; -import { POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { POST_NARRATION_LIMITS, POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takeSourceOf, takesDirOf } from "umtool-report-to-video/post-narration"; import { partRoles } from "umtool-report-to-video/post-thread"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -37,6 +37,8 @@ const r3 = (v) => Math.round(v * 1000) / 1000; export const REREAD_USAGE = [ " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", + " umtool posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" | --tempo 1.3 --parts 4-16,21-25 [--stretch atempo|rubberband] [--dry-run] [--json]", + " umtool posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", " A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with", " the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without", " drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;", @@ -54,6 +56,69 @@ export class RereadError extends Error { const PIECE_RE = /^(parent:\d|quoted)$/; /** + * THE JOIN of a take's parts, pure: `keep` -- `[{ k, factor }]` in order, `k` + * the part's index in `t.parts`, `factor` the time-stretch it is read at + * (1: untouched) -- cut from `t`'s file and joined with the read's pauses + * (POST_PART_GAP: between paragraphs, inside one). Returns `{ spans, parts, + * words, script, seconds }`: `spans` in the source take's seconds (`at` the + * part's start in the new one, `len` its length there), the parts re-timed + * (roles stored, a stretched part's `tempo` its reading speed against its + * first read), the words moved -- a stretched part's scaled by its factor -- + * and a word in no kept part dropped. + * + * @param {Record<string, any>} t the source take + * @param {Array<{ k: number, factor: number, tempo?: number }>} keep + * @param {Array<{ role?: string | null }>} roles partRoles of the entry + */ +export function joinParts(t, keep, roles = []) { + const parts = t.parts; + const spans = []; + let cur = 0; + keep.forEach(({ k, factor, tempo }, j) => { + const p = parts[k]; + const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1].k].para ? POST_PART_GAP.para : POST_PART_GAP.inside; + const at = r3(cur + gap); + const f = fin(factor) && factor > 0 ? factor : 1; + const len = r3(p.seconds / f); + spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap, ...(Math.abs(f - 1) > 1e-6 ? { factor: Math.round(f * 1e6) / 1e6 } : {}), len, tempo: fin(tempo) ? tempo : fin(p.tempo) ? p.tempo : 1 }); + cur = at + len; + }); + const newParts = spans.map((s, j) => { + const p = parts[s.k]; + const { gapBefore: _g, role: _r, tempo: _t, ...rest } = p; + const role = roles[s.k]?.role ?? p.role ?? null; + const tempo = Math.round(s.tempo * 1000) / 1000; + return { ...rest, n: j + 1, start: s.at, seconds: s.len, ...(role ? { role } : {}), ...(Math.abs(tempo - 1) > 1e-6 ? { tempo } : {}) }; + }); + // Its words moved with their parts (a word is its part's when it starts inside the part's span), scaled with a stretched one. + const words = Array.isArray(t.words) + ? t.words.flatMap((w) => { + const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05); + if (!s) return []; + const f = s.factor ?? 1; + const at = (v) => r3(Math.min(s.at + s.len + 0.05, Math.max(0, s.at + (v - s.from) / f))); + return [{ w: w.w, start: at(w.start), end: Math.max(at(w.start), at(w.end)) }]; + }) + : null; + const script = spans.reduce((acc, s, j) => { + const p = parts[s.k]; + const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " "; + return acc + sep + String(p.text ?? "").trim(); + }, ""); + return { spans, parts: newParts, words, script, seconds: r3(cur) }; +} + +/** The picked take's parts, all timed -- or a RereadError (a take read in one go has none). */ +function timedParts(entry, t, what = "re-join") { + if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to ${what}`); + const parts = Array.isArray(t.parts) ? t.parts : []; + if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) { + throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate <p> ${entry.id} --take)`); + } + return parts; +} + +/** * THE RE-JOIN's PLAN, pure: which parts of `entry`'s picked take are kept and * where each lands in the new take -- `{ take, keep: [k…], drop: [{ k, why }], * spans: [{ k, from, to, at }], parts, words, script, seconds, steps }`. @@ -66,11 +131,7 @@ const PIECE_RE = /^(parent:\d|quoted)$/; */ export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = false } = {}) { const t = pickedTake(entry); - if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to re-join`); - const parts = Array.isArray(t.parts) ? t.parts : []; - if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) { - throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate <p> ${entry.id} --take)`); - } + const parts = timedParts(entry, t); for (const w of without) if (!PIECE_RE.test(w)) throw new RereadError(`--without ${w}: a piece is parent:0, parent:1 or quoted`); for (const n of dropParts) if (!(Number.isInteger(n) && n >= 1 && n <= parts.length)) throw new RereadError(`--drop-parts ${n}: ${entry.id}'s take has parts 1-${parts.length}`); const roles = partRoles(entry); @@ -85,41 +146,122 @@ export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = fal const dropped = new Set(drop.map((d) => d.k)); const keep = parts.map((_, k) => k).filter((k) => !dropped.has(k)); if (!keep.length) throw new RereadError(`${entry.id}: that drops every part of its take -- nothing would be read`); - // The kept parts, joined with the read's pauses (a new paragraph's, a part inside one's). - const spans = []; - let cur = 0; - keep.forEach((k, j) => { - const p = parts[k]; - const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1]].para ? POST_PART_GAP.para : POST_PART_GAP.inside; - const at = r3(cur + gap); - spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap }); - cur = at + p.seconds; - }); - const newParts = spans.map((s, j) => { - const p = parts[s.k]; - const { gapBefore: _g, role: _r, ...rest } = p; - const role = roles[s.k]?.role ?? null; - return { ...rest, n: j + 1, start: s.at, seconds: r3(p.seconds), ...(role ? { role } : {}) }; - }); - // Its words moved with their parts (a word is its part's when it starts inside the part's span). - const words = Array.isArray(t.words) - ? t.words.flatMap((w) => { - const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05); - if (!s) return []; - const d = s.at - s.from; - return [{ w: w.w, start: r3(Math.max(0, w.start + d)), end: r3(Math.max(0, w.end + d)) }]; - }) - : null; - const script = spans.reduce((acc, s, j) => { - const p = parts[s.k]; - const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " "; - return acc + sep + String(p.text ?? "").trim(); - }, ""); - return { take: t, keep, drop, spans, parts: newParts, words, script, seconds: r3(cur), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] }; + const j = joinParts(t, keep.map((k) => ({ k, factor: 1 })), roles); + return { take: t, keep, drop, ...j, spans: j.spans.map(({ k, from, to, at, gap }) => ({ k, from, to, at, gap })), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] }; +} + +// --------------------------------------------------------------------------- +// PER-PART TEMPO (operator, 4 Nov, a 6.5-minute post: "what if we sped it up ... and then slowing back down here on the +// juicy persecution complex paragraph"; "dynamic speed over boring parts of a long message ... nothing too crazy"). +// --------------------------------------------------------------------------- + +/** The stretchers a tempo step may use: ffmpeg's atempo (the default, as the read's `rate` is played) or rubberband. */ +export const TEMPO_STRETCHERS = Object.freeze(["atempo", "rubberband"]); + +/** + * A TEMPO SPEC as the CLI writes it, pure: `"4-16=1.35,21-25=1.3"` (each run of + * parts and its tempo), or `{ tempo: 1.3, parts: "4-16,21-25" }` (one tempo for + * the runs named) -- `{ <part n>: tempo }` (1-based). Refused: a part outside + * 1-`count`, a tempo outside POST_NARRATION_LIMITS.tempo, a part named twice. + * + * @param {{ spec?: string | null, tempo?: number | string | null, parts?: string | null, count: number }} o + * @returns {Record<string, number>} + */ +export function parseTempoSpec({ spec = null, tempo = null, parts = null, count }) { + const [lo, hi] = POST_NARRATION_LIMITS.tempo; + /** @type {Record<string, number>} */ + const out = {}; + const runs = (list, where) => + String(list).split(",").map((x) => x.trim()).filter(Boolean).flatMap((r) => { + const m = /^(\d+)(?:-(\d+))?$/.exec(r); + if (!m) throw new RereadError(`${where} ${r}: a part (4) or a run of them (4-16)`); + const a = Number(m[1]); + const b = m[2] === undefined ? a : Number(m[2]); + if (!(a >= 1 && b >= a && b <= count)) throw new RereadError(`${where} ${r}: the take has parts 1-${count}`); + return Array.from({ length: b - a + 1 }, (_, i) => a + i); + }); + const put = (n, v, where) => { + if (!(fin(v) && v >= lo && v <= hi)) throw new RereadError(`${where}: a tempo is ${lo}–${hi} (1.3 reads 30% faster, its pitch kept)`); + if (out[n] !== undefined && out[n] !== v) throw new RereadError(`${where}: part ${n} is named twice`); + out[n] = v; + }; + if (tempo !== null && tempo !== undefined) { + if (parts === null || parts === undefined) throw new RereadError("--tempo needs --parts (the runs it reads faster: 4-16,21-25)"); + for (const n of runs(parts, "--parts")) put(n, Number(tempo), `--tempo ${tempo}`); + } + if (spec !== null && spec !== undefined) { + for (const item of String(spec).split(/[,;](?=\s*\d+(?:-\d+)?\s*=)/)) { + const m = /^\s*([\d,\s-]+?)\s*=\s*([\d.]+)\s*$/.exec(item); + if (!m) throw new RereadError(`--tempo-for ${item.trim()}: <parts>=<tempo>, e.g. 4-16=1.35,21-25=1.3`); + for (const n of runs(m[1], "--tempo-for")) { + delete out[n]; + put(n, Number(m[2]), `--tempo-for ${item.trim()}`); + } + } + } + if (!Object.keys(out).length) throw new RereadError("name the parts and their tempo: --tempo-for \"4-16=1.35,21-25=1.3\" (or --tempo 1.3 --parts 4-16,21-25)"); + return out; +} + +/** Parts' tempos as runs, pure: `[1, 1.35, 1.35, 1]` → `{ "2-3": 1.35 }` (a part at 1 left out). */ +export function tempoRanges(tempos) { + const out = {}; + let i = 0; + while (i < tempos.length) { + const v = tempos[i] ?? 1; + let j = i; + while (j + 1 < tempos.length && (tempos[j + 1] ?? 1) === v) j += 1; + if (Math.abs(v - 1) > 1e-6) out[i === j ? String(i + 1) : `${i + 1}-${j + 1}`] = v; + i = j + 1; + } + return out; +} + +/** A take's last step, when it is one of `ops`; and the take it was made from, when that is in `takes`. */ +export function lastLocalStep(takes, t, ops) { + const st = Array.isArray(t?.steps) ? t.steps[t.steps.length - 1] : null; + if (!st || !ops.includes(st.op)) return null; + const src = takeSourceOf(t); + const from = src.kind === "take" ? takes.find((x) => takeIdOf(x) === src.from) ?? null : null; + return { step: st, from }; +} + +/** + * THE TEMPO's PLAN, pure: `tempo` `{ <part n>: target }` (parseTempoSpec's) -- + * each part named READ AT that tempo against its first read, the rest as they + * are. A tempo is absolute: on a take made by a tempo step (a re-tune) the plan + * starts from the take that one was made from (each part stretched once, never + * twice), the parts it does not name keeping the tempo they had. Every part is + * kept, joined with the read's pauses; the words scaled with their part. + * Returns rereadPlan's shape plus `base` (the take it cuts), `tempos` (each + * part's, after) and `was` (before). + * + * @param {Record<string, any>} entry + * @param {{ tempo: Record<string, number>, stretch?: string }} o + */ +export function tempoPlan(entry, { tempo, stretch = "atempo" }) { + const t = pickedTake(entry); + const parts = timedParts(entry, t, "re-time"); + if (!TEMPO_STRETCHERS.includes(stretch)) throw new RereadError(`--stretch ${stretch}: ${TEMPO_STRETCHERS.join(" or ")}`); + const takes = entry.narration.takes; + const was = parts.map((p) => (fin(p.tempo) ? p.tempo : 1)); + // A re-tune: the take before the tempo step, when it is there and has the same parts. + const up = lastLocalStep(takes, t, ["tempo"]); + const base = up?.from && Array.isArray(up.from.parts) && up.from.parts.length === parts.length && up.from.parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0) ? { ...up.from, index: takes.indexOf(up.from) } : t; + for (const n of Object.keys(tempo)) if (!(Number(n) >= 1 && Number(n) <= parts.length)) throw new RereadError(`part ${n}: ${entry.id}'s take has parts 1-${parts.length}`); + const tempos = parts.map((_, k) => (tempo[k + 1] !== undefined ? tempo[k + 1] : was[k])); + if (tempos.every((v, k) => Math.abs(v - was[k]) < 1e-6)) throw new RereadError(`${entry.id}'s picked take reads those parts at that tempo already: nothing to change`); + const baseTempo = base.parts.map((p) => (fin(p.tempo) ? p.tempo : 1)); + const roles = partRoles(entry); + const j = joinParts(base, base.parts.map((_, k) => ({ k, factor: tempos[k] / baseTempo[k], tempo: tempos[k] })), roles); + return { + take: base, picked: t, base, keep: parts.map((_, k) => k), drop: [], was, tempos, ...j, stretch, + steps: [{ op: "tempo", tempo: tempoRanges(tempos), params: { stretch }, ranAt: new Date().toISOString() }], + }; } -/** The ffmpeg arguments that cut the plan's spans out of `src` and join them with silence into `out`. */ -export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { +/** The ffmpeg arguments that cut the plan's spans out of `src` (each stretched by its factor, its length exact) and join them with silence into `out`. */ +export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono", stretch = plan.stretch ?? "atempo" } = {}) { const chains = []; const labels = []; plan.spans.forEach((s, j) => { @@ -127,7 +269,13 @@ export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono" } = { chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=duration=${s.gap}[g${j}]`); labels.push(`[g${j}]`); } - chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}[a${j}]`); + // A stretched part: its pitch kept, then padded and trimmed to its length in the plan (sample-exact: the parts after + // it land where their word timings say). + const f = s.factor ?? 1; + const stretched = Math.abs(f - 1) > 1e-6 + ? `,${stretch === "rubberband" ? `rubberband=tempo=${f}:transients=mixed:pitchq=quality` : `atempo=${f}`},apad,atrim=end_sample=${Math.round(s.len * rate)},asetpts=PTS-STARTPTS` + : ""; + chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}${stretched}[a${j}]`); labels.push(`[a${j}]`); }); chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`); @@ -143,33 +291,35 @@ async function audioFormat(file) { } /** - * RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan - * takes them): the file written, measured, the take added and picked in one - * write. `dryRun`: the plan only. Returns `{ plan, take?, result? }`. + * WRITE A DERIVED TAKE of post item `e` from `plan` (rereadPlan's, tempoPlan's, postYell.mjs yellPlan's): `plan.take`'s + * file through `argsOf(src, out, fmt)` (ffmpeg) into take-<n>.<op>-<engine>.wav, measured, added with the plan's + * parts, words, script and steps -- and picked, in ONE write (updatePostNarration: one undo point). Returns `{ take, + * result }`. The source take is never touched. * * @param {{ id: string, dir: string }} project * @param {Record<string, any>} e - * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o] + * @param {Record<string, any>} plan + * @param {{ op: string, argsOf: (src: string, out: string, fmt: { rate: number, layout: string }) => string[], measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }>, verb?: string, after?: (abs: string, m: { seconds: number|null, lufs: number|null }) => Promise<{ seconds: number|null, lufs: number|null }> }} o */ -export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, dryRun = false, measure = undefined } = {}) { - const plan = rereadPlan(e, { without, dropParts, dropUrls }); - if (dryRun) return { plan }; +export async function writeDerivedTake(project, e, plan, { op, argsOf, measure = undefined, verb = "re-join", after = undefined }) { const t = plan.take; const pid = postIdOf(e); const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); await mkdir(dir, { recursive: true }); - const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), "rejoin", t.engine === "derived" ? "take" : t.engine ?? "take"); + const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), op, t.engine === "derived" ? "take" : t.engine ?? "take"); const abs = (r) => path.join(project.dir, ...String(r).split("/")); const src = abs(t.file); - if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s picked take is not on disk: ${t.file}`); + if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s take is not on disk: ${t.file}`); const fmt = await audioFormat(src); try { - await execFileP(FFMPEG(), rejoinArgs(src, abs(rel), plan, fmt), { maxBuffer: 1 << 24 }); + await execFileP(FFMPEG(), argsOf(src, abs(rel), fmt), { maxBuffer: 1 << 24 }); } catch (err) { await rm(abs(rel), { force: true }); - throw new RereadError(`ffmpeg could not re-join ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`); + throw new RereadError(`ffmpeg could not ${verb} ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`); } - const m = await (measure ?? (await import("./postNarrationCli.mjs")).measureTake)(abs(rel)); + const measureOf = measure ?? (await import("./postNarrationCli.mjs")).measureTake; + let m = await measureOf(abs(rel)); + if (after) m = await after(abs(rel), m); const take = { file: rel, engine: "derived", @@ -185,6 +335,24 @@ export async function rereadTake(project, e, { without = [], dropParts = [], dro parts: plan.parts, }; const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + return { take, result }; +} + +/** + * RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan + * takes them), or with its parts RE-TIMED (`tempo`, tempoPlan's): the file + * written, measured, the take added and picked in one write. `dryRun`: the + * plan only. Returns `{ plan, take?, result? }`. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, tempo?: Record<string, number> | null, stretch?: string, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o] + */ +export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, tempo = null, stretch = "atempo", dryRun = false, measure = undefined } = {}) { + if (tempo && (without.length || dropParts.length || dropUrls)) throw new RereadError("a tempo goes alone: re-join without the piece first, then re-time that take (it is picked)"); + const plan = tempo ? tempoPlan(e, { tempo, stretch }) : rereadPlan(e, { without, dropParts, dropUrls }); + if (dryRun) return { plan }; + const { take, result } = await writeDerivedTake(project, e, plan, { op: tempo ? "tempo" : "rejoin", argsOf: (src, out, fmt) => rejoinArgs(src, out, plan, fmt), measure, verb: tempo ? "re-time" : "re-join" }); return { plan, take, result }; } @@ -200,19 +368,34 @@ export function piecesHidden(e, thread) { return out; } -/** `umtool posts reread <p> <item> …`. */ -export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { +/** `umtool posts reread <p> <item> …`: a re-join without a piece, a tempo (`tempoSpec`, tempoPlan's), or a yell (`yell`: postYell.mjs). */ +export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, tempoSpec = null, tempo = null, parts = null, stretch = "atempo", yell = null, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new RereadError(`${project.id} has no manifest`); const e = (manifest.timeline ?? []).find((x) => x?.type === "post" && (x.id === ref || postIdOf(x) === ref || x.id === `p-${ref}`)); if (!e) throw new RereadError(`no post item ${ref} in ${project.id}`); - const r = await rereadTake(project, e, { without, dropParts, dropUrls, dryRun }); - const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", "); + if (yell) { + if (tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--yell-caps goes alone: re-join or re-time first, then yell that take (it is picked) -- or the other way round"); + const { yellCommand } = await import("./postYell.mjs"); + return yellCommand(project, manifest, [e], { ...yell, dryRun, json, out }); + } + const timed = tempoSpec !== null || tempo !== null; + const t0 = pickedTake(e); + const spec = timed ? parseTempoSpec({ spec: tempoSpec, tempo, parts, count: Array.isArray(t0?.parts) ? t0.parts.length : 0 }) : null; + const r = await rereadTake(project, e, { without, dropParts, dropUrls, tempo: spec, stretch, dryRun }); + const secs = (r.take?.seconds ?? r.plan.seconds).toFixed(2); + const was = Number((r.plan.picked ?? r.plan.take).seconds).toFixed(2); if (json) { - out(JSON.stringify({ ok: true, id: e.id, dryRun, drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1), seconds: r.take?.seconds ?? r.plan.seconds, take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); + out(JSON.stringify({ ok: true, id: e.id, dryRun, ...(timed ? { tempo: r.plan.steps[0].tempo, stretch: r.plan.stretch, from: takeIdOf(r.plan.take) } : { drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1) }), seconds: r.take?.seconds ?? r.plan.seconds, was: Number(was), take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); return 0; } - out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${(r.take?.seconds ?? r.plan.seconds).toFixed(2)} s (was ${Number(r.plan.take.seconds).toFixed(2)} s)`); + if (timed) { + const runs = Object.entries(r.plan.steps[0].tempo).map(([k, v]) => `${k} at ${v}x`).join(", ") || "every part at 1x"; + out(`${dryRun ? "would re-time" : "re-timed"} ${e.id}'s take (${r.plan.stretch}, pitch kept): parts ${runs} -- ${secs} s (was ${was} s)${r.plan.take !== r.plan.picked ? `, cut from ${takeIdOf(r.plan.take)} (each part stretched once)` : ""}`); + } else { + const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", "); + out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${secs} s (was ${was} s)`); + } if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`); return 0; } diff --git a/umtool/lib/report/postReread.test.mjs b/umtool/lib/report/postReread.test.mjs @@ -130,3 +130,74 @@ test("set-item thread.parent.0=context on a piece the take reads RE-JOINS first const dry = await cli(["reread", "setitem", "p-1", "--drop-parts", "1", "--dry-run"]); assert.match(dry.err + dry.out, /only part|drops every part/); }); + +// ---- PER-PART TEMPO (operator, 4 Nov: "sped it up ... and then slowing back down here on the juicy persecution +// complex paragraph"): the parts named stretched (pitch kept), the rest untouched, the words scaled with their part. +import { parseTempoSpec, rereadCommand, tempoPlan, tempoRanges } from "./postReread.mjs"; + +test("THE TEMPO SPEC: runs and their tempo, one tempo for --parts, the refusals; runs back from per-part tempos", () => { + assert.deepEqual(parseTempoSpec({ spec: "4-6=1.35,8=1.3", count: 9 }), { 4: 1.35, 5: 1.35, 6: 1.35, 8: 1.3 }); + assert.deepEqual(parseTempoSpec({ tempo: "1.3", parts: "1-2,4", count: 4 }), { 1: 1.3, 2: 1.3, 4: 1.3 }); + // --tempo-for wins over --tempo for a part both name. + assert.deepEqual(parseTempoSpec({ tempo: 1.2, parts: "1-3", spec: "2=1.4", count: 3 }), { 1: 1.2, 2: 1.4, 3: 1.2 }); + assert.throws(() => parseTempoSpec({ spec: "4-16=1.35", count: 10 }), /the take has parts 1-10/); + assert.throws(() => parseTempoSpec({ spec: "1=1.7", count: 3 }), /a tempo is 1–1\.6/); + assert.throws(() => parseTempoSpec({ spec: "1=0.9", count: 3 }), /a tempo is 1–1\.6/); + assert.throws(() => parseTempoSpec({ tempo: 1.3, count: 3 }), /--tempo needs --parts/); + assert.throws(() => parseTempoSpec({ count: 3 }), /name the parts/); + assert.deepEqual(tempoRanges([1, 1.35, 1.35, 1, 1.3]), { "2-3": 1.35, 5: 1.3 }); +}); + +test("THE TEMPO's PLAN: a stretched part shorter by its factor, the parts after it moved up, its words scaled; every part kept, the gaps the read's", () => { + const p = tempoPlan(item(), { tempo: { 1: 1.5, 3: 1.2 } }); + assert.deepEqual(p.spans.map((s) => [s.k, s.at, s.len, s.factor ?? 1]), [[0, 0, 2.4, 1.5], [1, 3, 3.2, 1], [2, 6.8, 2.583, 1.2]]); + assert.deepEqual(p.parts.map((x) => [x.n, x.start, x.seconds, x.tempo ?? 1]), [[1, 0, 2.4, 1.5], [2, 3, 3.2, 1], [3, 6.8, 2.583, 1.2]]); + // Words: in a stretched part scaled by its factor from the part's start; in an untouched one moved with it. + assert.deepEqual(p.words, [{ w: "The", start: 0.067, end: 0.2 }, { w: "Then", start: 3.1, end: 3.4 }, { w: "That", start: 6.883, end: 7.05 }, { w: "morning", start: 9.05, end: 9.3 }]); + assert.equal(p.seconds, 9.383); + assert.deepEqual(p.steps.map((s) => [s.op, s.tempo, s.params]), [["tempo", { 1: 1.5, 3: 1.2 }, { stretch: "atempo" }]]); + assert.throws(() => tempoPlan(item(), { tempo: { 1: 1 } }), /at that tempo already/); + // The ffmpeg: atempo on the stretched part, padded and trimmed to its length (sample-exact); the untouched as before. + const fc = rejoinArgs("/in.wav", "/o.wav", p, { rate: 24000, layout: "mono" })[8]; + assert.match(fc, /\[0:a\]atrim=start=0:end=3\.6,asetpts=PTS-STARTPTS,aformat=sample_rates=24000:channel_layouts=mono,atempo=1\.5,apad,atrim=end_sample=57600,asetpts=PTS-STARTPTS\[a0\]/); + assert.match(fc, /\[0:a\]atrim=start=4\.2:end=7\.4,asetpts=PTS-STARTPTS,aformat=sample_rates=24000:channel_layouts=mono\[a1\]/); + assert.match(rejoinArgs("/in.wav", "/o.wav", { ...p, stretch: "rubberband" }, { rate: 24000 })[8], /rubberband=tempo=1\.5:transients=mixed:pitchq=quality/); +}); + +test("A RE-TUNE: a tempo on a re-timed take is cut from the take before it (each part stretched once), the parts it does not name keeping theirs", () => { + const e = item(); + const p1 = tempoPlan(e, { tempo: { 1: 1.5, 3: 1.2 } }); + const t1 = { file: "narration/posts/1/take-3.tempo-orpheus.wav", engine: "derived", voice: "leo+zac", seconds: p1.seconds, source: { kind: "take", from: "take-2.orpheus-thread" }, steps: p1.steps, words: p1.words, parts: p1.parts }; + const e2 = { ...e, narration: { ...e.narration, takes: [...e.narration.takes, t1], pick: 1 } }; + assert.deepEqual(validatePostItem(e2), []); + const p2 = tempoPlan(e2, { tempo: { 1: 1.25 } }); + assert.equal(p2.take.file, "narration/posts/1/take-2.orpheus-thread.wav", "cut from the first read"); + assert.deepEqual(p2.spans.map((s) => s.factor ?? 1), [1.25, 1, 1.2]); + assert.deepEqual(p2.tempos, [1.25, 1, 1.2]); + assert.deepEqual(p2.steps[0].tempo, { 1: 1.25, 3: 1.2 }); + // The validator: a part's tempo inside 1-1.6, a step's runs. + const bad = { ...e2, narration: { ...e2.narration, takes: [e2.narration.takes[0], { ...t1, parts: [{ ...t1.parts[0], tempo: 2 }], steps: [{ op: "tempo", tempo: { "1-x": 1.2 } }] }] } }; + assert.deepEqual(validatePostItem(bad).filter((x) => /tempo/.test(x)).length, 2); +}); + +test("RE-TIMED: the file's length the plan's (sample-exact), the derived take picked in ONE write with its parts' tempo and the words scaled; set-item narration.tempo= runs it", async () => { + const p = await project("tempo", [item()]); + const lines = []; + assert.equal(await rereadCommand(p, "p-1", { tempoSpec: "1=1.5,3=1.2", out: (s) => lines.push(s) }), 0); + assert.match(lines.join("\n"), /re-timed p-1's take \(atempo, pitch kept\): parts 1 at 1\.5x, 3 at 1\.2x -- 9\.38 s \(was 11\.30 s\)/); + let e = (await manifest(p)).timeline[0]; + const t = e.narration.takes[1]; + assert.equal(e.narration.pick, 1); + assert.match(t.file, /take-3\.tempo-orpheus\.wav$/); + assert.ok(Math.abs(t.seconds - 9.383) < 0.01, `measured ${t.seconds}`); + assert.deepEqual([t.source.from, t.steps[0].op, t.parts.map((x) => x.tempo ?? 1)], ["take-2.orpheus-thread", "tempo", [1.5, 1, 1.2]]); + assert.deepEqual(validatePostItem(e), []); + // set-item: a re-tune, cut from the first read again. + const out = []; + const code = await postsCommand(["set-item", "tempo", "p-1", "narration.tempo=1-3=1.1"], { root: REPORTS, out: (s) => out.push(s), err: (s) => out.push(s) }); + assert.equal(code, 0, out.join("\n")); + e = (await manifest(p)).timeline[0]; + assert.deepEqual([e.narration.pick, e.narration.takes[2].source.from, e.narration.takes[2].parts.map((x) => x.tempo)], [2, "take-2.orpheus-thread", [1.1, 1.1, 1.1]]); + await undoStructural(p.dir); + assert.ok((await manifest(p)).timeline[0].narration.takes.length < 3, "undone"); +}); diff --git a/umtool/lib/report/postYell.mjs b/umtool/lib/report/postYell.mjs @@ -0,0 +1,393 @@ +// THE CAPS YELLED (operator, 4 Nov: "I feel like allcaps needs to be yelled more"; p-2116771656329019498, "the moment +// that THEY have your Dox ITS ALREADY TOO LATE"): a read's scripts are drafted with his ALL-CAPS words lowercased (a +// stock voice spells a caps word out letter by letter), so the read says them flat. This raises them on the read +// that is there -- no TTS: the words he wrote in caps found in the read's word timings, and the voice over each +// run of them lifted the way a voice is raised, not turned up: louder (+5.5 dB), a presence lift (~3.2 kHz), +// compressed and gently saturated, crossfaded in and out over 50 ms. Its timings are untouched (the yell changes +// no length), so beeps, captions, zooms and slams keep their place. +// +// umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json] +// umtool posts yell <p> [--all | <item…>] [--yell-gain …] [--yell-style …] [--dry-run] [--json] +// +// WHICH WORDS: a word of the read whose SOURCE word -- in his post, or in the piece a part reads (the post he +// answers, the quote, a linked post) -- is ALL CAPS with two letters or more, its script word aligned to it +// (word-zoom.mjs alignWords). Left flat: an acronym or initialism (YELL_ACRONYMS; any caps word with no vowel reads +// as letters: DM, KF, TV, BS), and a slur the cut masks (post-slurs.mjs: beeped anyway). A run of caps words is one +// span (a gap under YELL_MERGE between two merges them). +// +// LOUDNESS: the raised voice is limited (nothing clips) and the take's loudness kept within YELL_LUFS_MAX of the one +// it came from -- over it, the lift is lowered until it fits (an all-caps post keeps the timbre, not the level). +// +// STORED: a derived take, `source: {kind: "take", from}`, `steps: [{op: "yell", spans, params: {gain, style}}]`, +// picked in one write (undoable). It chains with the tempo and the re-join (postReread.mjs) in either order; a yell +// on a yelled take re-yells the take before it (never twice). +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { isNarrated, pickedTake, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration"; +import { partRoles } from "umtool-report-to-video/post-thread"; +import { cutSlurs } from "umtool-report-to-video/post-redact-files"; +import { scriptTokens, slurMatches } from "umtool-report-to-video/post-slurs"; +import { alignWords, normWord } from "umtool-report-to-video/word-zoom"; +import { readManifest } from "../projects/report.mjs"; +import { RereadError, lastLocalStep, writeDerivedTake } from "./postReread.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +export class YellError extends Error { + constructor(message) { + super(message); + this.name = "YellError"; + } +} + +export const YELL_USAGE = [ + "usage: umtool posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", + " umtool posts yell <project> [--all | <item> …] [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", + " THE CAPS YELLED (no TTS): the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the read's", + " word timings and raised -- louder, a presence lift, compressed and gently saturated, 50 ms in and out -- as a new", + " take, picked (one undo point per item). Acronyms (FBI, DM, KF, TV, … and any caps word with no vowel) and slurs the", + " cut masks are left flat. Its timings are kept (beeps, captions, zooms, slams stay right); its loudness within 1 LU", + " of the take it came from. Needs the take's word timings (umtool posts narrate <p> <item> --words). --dry-run lists", + " each item's caps words, those it skips and why, and the items with no word timings. Chains with --tempo-for.", +].join("\n"); + +/** Caps words left flat: acronyms and initialisms (a caps word with no vowel is one by rule: YELL_LETTERS). */ +export const YELL_ACRONYMS = Object.freeze(new Set([ + "FBI", "CIA", "NSA", "DOJ", "IRS", "TOS", "TOU", "USA", "US", "UK", "EU", "UN", "NYC", "LA", "DC", "DM", "DMS", "PM", "PMS", "KF", "OK", "OKAY", "LOL", + "LMAO", "LMFAO", "ROFL", "OMG", "WTF", "IDK", "IIRC", "IMO", "IMHO", "TBH", "BTW", "FYI", "ATM", "ASAP", "ETA", "AKA", "FAQ", "ID", "IDS", "IQ", "AI", + "TV", "IRL", "VR", "AR", "PC", "BS", "CEO", "CEOS", "YT", "TTS", "ASMR", "NSFW", "SFW", "POV", "RIP", "MR", "MRS", "MS", "DR", "ST", "JR", "SR", "PR", + "HR", "PS", "PSA", "OP", "GG", "FPS", "RPG", "MMO", "NPC", "NPCS", "AMA", "URL", "TIL", "LGBT", "LGBTQ", "TLDR", "DIY", "VPN", "IP", "ISP", "API", + "AM", "ET", "PST", "EST", "UTC", "GMT", "OBS", "VOD", "VODS", "DLC", "NFT", "NFTS", "VTUBER", "VTUBERS", "VTUBING", "EN", "JP", "ENVTUBER", "MOD", + "MODS", "QRT", "RT", "QT", "OG", "GOAT", "NGL", "SMH", "JK", "TFW", "MFW", "AFAIK", "ICYMI", "IG", "FB", "X", "XD", "UWU", "OWO", "ADHD", "OCD", + "PTSD", "HIV", "AIDS", "COVID", "NASA", "NATO", "DNA", "GPS", "USB", "CD", "DVD", "HD", "UHD", "PDF", "JPG", "PNG", "GIF", "HTML", "IOS", "MAGA", + "GOP", "POTUS", "SCOTUS", "BLM", "ACAB", "AOC", "DEI", "ESG", "CRT", "SJW", "SJWS", "TERF", "TERFS", "IRA", "LLC", "INC", "LTD", "CO", +])); +/** The ramp in and out of a raised span, seconds (≥ 40 ms: never a click). */ +export const YELL_RAMP = 0.05; +/** Two caps spans closer than this are one (a run read as one). */ +export const YELL_MERGE = 0.35; +/** A span starts this much before its first word's timing (the transcription's starts run late). */ +export const YELL_PAD = Object.freeze({ before: 0.03, after: 0.04 }); +/** The take's loudness may rise at most this much over the take it came from, LU. */ +export const YELL_LUFS_MAX = 1; +/** The styles: the lift (dB) and how the raised voice is shaped. */ +export const YELL_STYLES = Object.freeze({ + // presence/body: EQ lifts (dB) at ~3.2 kHz and ~1.1 kHz; ratio: the compressor's; drive: dB pushed into a tanh + // saturation (and taken back after it). The lift (`gain`) is MEASURED: the raised spans come out that much louder. + raise: Object.freeze({ gain: 5.5, presence: 3, body: 1.5, ratio: 2.5, drive: 3 }), + shout: Object.freeze({ gain: 7, presence: 4.5, body: 2, ratio: 4, drive: 6 }), + loud: Object.freeze({ gain: 5.5, presence: 0, body: 0, ratio: 1, drive: 0 }), +}); +export const YELL_GAIN = Object.freeze([1, 9]); + +const VOWEL_RE = /[AEIOUY]/; +const letters = (w) => String(w ?? "").replace(/['’]S$/i, "").replace(/[^\p{L}]/gu, ""); + +/** Is a source word ALL CAPS, two letters or more (I'LL, ISN'T count; "I" and "10X" do not)? */ +export function isCapsWord(raw) { + const L = letters(raw); + return L.length >= 2 && L === L.toUpperCase() && L !== L.toLowerCase(); +} + +/** Why a caps word is left flat (acronym / letters), or null when it is yelled. */ +export function acronymWhy(raw) { + const L = letters(raw).toUpperCase(); + if (YELL_ACRONYMS.has(L)) return "acronym"; + if (!VOWEL_RE.test(L)) return "letters"; + return null; +} + +/** The source texts a read's words come from: his post, the posts it answers, the quote, a linked post. */ +export function sourcePieces(entry) { + const out = []; + const add = (where, v) => typeof v === "string" && v.trim() && out.push({ where, text: v }); + add("post", entry?.text); + (Array.isArray(entry?.parents) ? entry.parents : []).forEach((p, i) => add(`parent:${i}`, p?.text)); + if (isObj(entry?.quoted)) add("quoted", entry.quoted.text); + (Array.isArray(entry?.links) ? entry.links : []).forEach((l, i) => add(`linked:${i}`, l?.text)); + return out; +} + +/** + * THE CAPS of a read, pure: `{ yell: [{ k, w, src, where }], skip: [{ k, w, src, where, why }], words: boolean, + * error? }` -- `k` the script token's index (= the take's word index), `src` the source word in caps. `slurs` the + * cut's resolved slur filter (post-redact-files.mjs cutSlurs): a slur's word is skipped (it is beeped anyway). + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} take + * @param {Record<string, any> | null} [slurs] + */ +export function capsOfRead(entry, take, slurs = null) { + const script = typeof take?.script === "string" ? take.script : String(entry?.narration?.script ?? ""); + const toks = scriptTokens(script); + const hits = slurs ? slurMatches(script, slurs) : []; + // Each script word's piece (the role of the part reading it: post-thread.mjs partRoles), when the parts tile the + // script: a piece's caps are looked for only in the words that read it -- never a word of his own that happens to + // match a caps word of the post he answers. + const roles = partRoles(entry, take); + const partTexts = Array.isArray(take?.parts) && take.parts.length ? take.parts.map((x) => x?.text) : scriptParts(script).map((x) => x.text); + const counts = partTexts.map((x) => scriptTokens(String(x ?? "")).length); + const roleOfTok = counts.reduce((a, b) => a + b, 0) === toks.length && roles.length === counts.length ? counts.flatMap((n, i) => Array(n).fill(roles[i]?.role ?? null)) : null; + const found = new Map(); + for (const piece of sourcePieces(entry)) { + const src = (piece.text.match(/\S+/g) ?? []).filter((w) => normWord(w)); + if (!src.some(isCapsWord)) continue; + const idx = toks.map((_, k) => k).filter((k) => !roleOfTok || roleOfTok[k] === piece.where || (roleOfTok[k] === null && piece.where === "post")); + if (!idx.length) continue; + const map = alignWords(idx.map((k) => toks[k].w), src); + map.forEach((j, i) => { + const k = idx[i]; + if (j < 0 || !isCapsWord(src[j]) || found.has(k)) return; + // Read in place: a neighbour aligned to its neighbour too (a lone match across unrelated words is not one). + if (!(map[i - 1] === j - 1 || map[i + 1] === j + 1 || src.length === 1)) return; + found.set(k, { k, w: toks[k].w, src: src[j].replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""), where: piece.where }); + }); + } + const yell = []; + const skip = []; + for (const c of [...found.values()].sort((a, b) => a.k - b.k)) { + const t = toks[c.k]; + const why = hits.some((h) => t.end > h.start && t.start < h.end) ? "slur" : acronymWhy(c.src); + (why ? skip : yell).push(why ? { ...c, why } : c); + } + const words = Array.isArray(take?.words) ? take.words : []; + const out = { yell, skip, words: words.length > 0, tokens: toks.length }; + if (yell.length && !words.length) return { ...out, error: `its take ${take?.file ?? ""} has no word timings to find its caps by (umtool posts narrate <p> ${entry?.id ?? "<item>"} --words)` }; + if (yell.length && words.length !== toks.length) return { ...out, error: `its take ${take?.file ?? ""}'s word timings are not of its script (${words.length} timed, ${toks.length} in the script)` }; + return out; +} + +/** The take seconds a read's caps are raised over, pure: each yelled word's timing padded, runs merged. */ +export function yellSpans(words, ks, { merge = YELL_MERGE } = {}) { + const spans = ks + .map((k) => words[k]) + .filter((w) => w && fin(w.start) && fin(w.end)) + .map((w) => [Math.max(0, w.start - YELL_PAD.before), Math.max(w.start, w.end) + YELL_PAD.after]) + .sort((a, b) => a[0] - b[0]); + const out = []; + for (const s of spans) { + const last = out[out.length - 1]; + if (last && s[0] - last[1] < merge) last[1] = Math.max(last[1], s[1]); + else out.push([...s]); + } + return out.map(([a, b]) => [r3(a), r3(b)]); +} + +/** + * THE YELL's PLAN, pure: the take it raises (`take`: the picked one; on a take made by a yell, the one before it), + * its caps and spans, the steps -- the parts, words and script unchanged. Throws YellError when there is nothing to + * yell, no timings to find them by, or a yell further up the chain. + * + * @param {Record<string, any>} entry + * @param {{ slurs?: Record<string, any> | null, gain?: number, style?: string }} [o] + */ +export function yellPlan(entry, { slurs = null, gain = undefined, style = "raise" } = {}) { + const picked = pickedTake(entry); + if (!picked) throw new YellError(`${entry?.id ?? "?"} has no take to yell`); + if (!YELL_STYLES[style]) throw new YellError(`--yell-style ${style}: ${Object.keys(YELL_STYLES).join(", ")}`); + const g = gain === undefined || gain === null ? YELL_STYLES[style].gain : Number(gain); + if (!(fin(g) && g >= YELL_GAIN[0] && g <= YELL_GAIN[1])) throw new YellError(`--yell-gain ${gain}: ${YELL_GAIN.join("–")} dB`); + const takes = entry.narration.takes; + const up = lastLocalStep(takes, picked, ["yell"]); + let take = picked; + if (up) { + if (!up.from) throw new YellError(`${entry.id}'s picked take is yelled already, and the take it came from is gone`); + take = { ...up.from, index: takes.indexOf(up.from) }; + } + // A yell further up its chain (yelled, then re-timed): never raised twice. + for (let cur = take, i = 0; cur && i < 20; i += 1) { + if ((cur.steps ?? []).some((st) => st?.op === "yell")) throw new YellError(`${entry.id}'s picked take was made from a yelled one (${takeIdOf(cur)}): pick the take before the yell, then yell and re-time again`); + const src = takeSourceOf(cur); + cur = src.kind === "take" ? takes.find((x) => takeIdOf(x) === src.from) : null; + } + const caps = capsOfRead(entry, take, slurs); + if (caps.error) throw new YellError(`${entry.id}: ${caps.error}`); + if (!caps.yell.length) throw new YellError(`${entry.id}: no word of its read is in caps in what it reads${caps.skip.length ? ` (left flat: ${caps.skip.map((s) => `${s.src} (${s.why})`).join(", ")})` : ""}`); + const spans = yellSpans(take.words, caps.yell.map((c) => c.k)); + return { + take, picked, caps, spans, style, gain: g, + parts: take.parts, words: take.words, script: typeof take.script === "string" ? take.script : entry.narration.script, seconds: take.seconds, + steps: [{ op: "yell", spans, params: { gain: g, style }, ranAt: new Date().toISOString() }], + }; +} + +/** The envelope over the spans at time t (an ffmpeg expression): 0 outside, 1 inside, YELL_RAMP in and out. */ +export function yellEnvelope(spans, ramp = YELL_RAMP) { + const r = ramp.toFixed(3); + const one = ([a, b]) => `clip(min((t-${(a - ramp).toFixed(3)})/${r},(${(b + ramp).toFixed(3)}-t)/${r}),0,1)`; + // Sums of disjoint trapezoids, each term gated to its own window. + return `clip(${spans.map((s) => `between(t,${(s[0] - ramp).toFixed(3)},${(s[1] + ramp).toFixed(3)})*${one(s)}`).join("+")},0,1)`; +} + +/** The envelope's step: the voice is gained in frames this many samples long (2.7 ms at 24 kHz: a 50 ms ramp is ~18 steps). */ +export const YELL_FRAME = 64; + +/** + * The ffmpeg arguments that raise `plan.spans` of `src` into `out`: the voice split, one branch shaped as a raised + * voice (presence, body, compression, the lift with its measured make-up `plan.trim`, a gentle tanh saturation, + * limited under 0 dBFS -- its latency compensated), the two crossfaded by the spans' envelope (gained in + * YELL_FRAME-sample frames). Its length is the source's. + */ +export function yellArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { + const st = YELL_STYLES[plan.style] ?? YELL_STYLES.raise; + const E = yellEnvelope(plan.spans); + const lift = Math.round((plan.gain + (fin(plan.trim) ? plan.trim : 0)) * 100) / 100; + const shape = [ + st.presence ? `equalizer=f=3200:t=o:w=1.3:g=${st.presence}` : null, + st.body ? `equalizer=f=1100:t=o:w=1:g=${st.body}` : null, + st.ratio > 1 ? `acompressor=threshold=0.063:ratio=${st.ratio}:attack=5:release=90:makeup=1` : null, + `volume=${lift + (st.drive || 0)}dB`, + st.drive ? `asoftclip=type=tanh,volume=-${st.drive}dB` : null, + "alimiter=limit=0.94:attack=2:release=40:level=false:latency=1", + ].filter(Boolean).join(","); + const fc = [ + `[0:a]aformat=sample_fmts=fltp:sample_rates=${rate}:channel_layouts=${layout},asetnsamples=n=${YELL_FRAME}:p=0,asplit=2[yd][yw]`, + `[yw]${shape},asetnsamples=n=${YELL_FRAME}:p=0,volume=volume='${E}':eval=frame[ywet]`, + `[yd]volume=volume='1-(${E})':eval=frame[ydry]`, + `[ydry][ywet]amix=inputs=2:normalize=0:duration=first,atrim=end_sample=${Math.round(Number(plan.seconds) * rate)}[out]`, + ].join(";"); + return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", fc, "-map", "[out]", "-c:a", "pcm_s16le", out]; +} + +/** The RMS (dB) of a file over `spans` joined (ffmpeg astats), or null. */ +export async function spansRms(file, spans) { + const cut = spans.map(([a, b], i) => `[0:a]atrim=start=${a}:end=${b},asetpts=PTS-STARTPTS[s${i}]`); + const fc = `${cut.join(";")};${spans.map((_, i) => `[s${i}]`).join("")}concat=n=${spans.length}:v=0:a=1,astats=measure_perchannel=none:measure_overall=RMS_level[o]`; + try { + const { stderr } = await execFileP(FFMPEG(), ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-filter_complex", fc, "-map", "[o]", "-f", "null", "-"], { maxBuffer: 1 << 24 }); + const v = Number(/RMS level dB:\s*(-?[\d.]+)/.exec(String(stderr))?.[1]); + return fin(v) ? v : null; + } catch { + return null; + } +} + +/** + * @typedef {{ slurs?: Record<string, any> | null, gain?: number, style?: string, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} YellOpts + */ +/** + * YELL post item `e`'s caps (yellPlan's options): the file written, its lift MEASURED over the spans and the make-up + * set so they come out `gain` dB louder (made again once), its loudness held within YELL_LUFS_MAX of the take it came + * from (the lift lowered and the file re-made when over), the take added and picked in one write. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {YellOpts} [o] + */ +export async function yellTake(project, e, { slurs = null, gain = undefined, style = "raise", dryRun = false, measure = undefined } = {}) { + const plan = yellPlan(e, { slurs, gain, style }); + if (dryRun) return { plan }; + const measureOf = measure ?? (await import("./postNarrationCli.mjs")).measureTake; + const path = await import("node:path"); + const srcFile = path.join(project.dir, ...String(plan.take.file).split("/")); + const baseLufs = fin(plan.take.lufs) ? plan.take.lufs : (await measureOf(srcFile)).lufs; + const before = await spansRms(srcFile, plan.spans); + const { take, result } = await writeDerivedTake(project, e, plan, { + op: "yell", verb: "yell", measure: measureOf, + argsOf: (src, out, fmt) => { + plan.fmt = fmt; + plan.src = src; + return yellArgs(src, out, plan, fmt); + }, + after: async (abs, m) => { + const remake = async () => { + await execFileP(FFMPEG(), yellArgs(plan.src, abs, plan, plan.fmt), { maxBuffer: 1 << 24 }); + return measureOf(abs); + }; + let cur = m; + // The lift as heard: the compressor and the saturation take some back -- made up once, by what was measured. + let lifted = fin(before) ? await spansRms(abs, plan.spans) : null; + if (fin(before) && fin(lifted) && Math.abs(lifted - before - plan.gain) > 0.4) { + plan.trim = Math.round(Math.min(12, Math.max(-6, plan.gain - (lifted - before))) * 10) / 10; + cur = await remake(); + lifted = await spansRms(abs, plan.spans); + } + // Over the loudness: the lift lowered by the excess (three times at most), the file made again. + for (let i = 0; i < 3 && fin(cur.lufs) && fin(baseLufs) && cur.lufs - baseLufs > YELL_LUFS_MAX && plan.gain > YELL_GAIN[0]; i += 1) { + plan.gain = Math.max(YELL_GAIN[0], Math.round((plan.gain - 1.6 * (cur.lufs - baseLufs - YELL_LUFS_MAX + 0.15)) * 10) / 10); + cur = await remake(); + lifted = fin(before) ? await spansRms(abs, plan.spans) : null; + } + plan.steps[0].params = { gain: plan.gain, style: plan.style, ...(fin(plan.trim) ? { trim: plan.trim } : {}) }; + plan.lufs = { base: baseLufs, after: cur.lufs }; + plan.lift = fin(before) && fin(lifted) ? Math.round((lifted - before) * 10) / 10 : null; + return cur; + }, + }); + return { plan, take, result }; +} + +const capsLine = (c) => c.yell.map((x) => x.src).join(" "); +const skipLine = (c) => c.skip.map((x) => `${x.src} (${x.why})`).join(", "); + +/** One item's dry-run row, pure: `{ id, yell, skip, needsWords, error? }`, or null for an item with no caps read. */ +export function yellRow(e, slurs) { + if (e?.type !== "post" || !isNarrated(e)) return null; + const t = pickedTake(e); + const caps = capsOfRead(e, t, slurs); + if (!caps.yell.length && !caps.skip.length) return null; + return { id: e.id, take: takeIdOf(t), yell: caps.yell.map((x) => x.src), skip: caps.skip.map((x) => ({ w: x.src, why: x.why })), needsWords: !!caps.yell.length && !caps.words, ...(caps.error ? { error: caps.error } : {}), spans: !caps.error && caps.yell.length ? yellSpans(t.words, caps.yell.map((x) => x.k)).length : 0 }; +} + +/** `umtool posts reread <p> <item> --yell-caps` (and each item of `posts yell`). */ +export async function yellCommand(project, manifest, items, { gain = undefined, style = "raise", dryRun = false, json = false, out = (s) => console.log(s) } = {}) { + const slurs = cutSlurs(manifest); + const rows = []; + for (const e of items) { + if (dryRun) { + const row = yellRow(e, slurs) ?? { id: e.id, yell: [], skip: [], needsWords: false }; + rows.push(row); + continue; + } + try { + const r = await yellTake(project, e, { slurs, gain, style }); + rows.push({ id: e.id, yell: r.plan.caps.yell.map((x) => x.src), skip: r.plan.caps.skip.map((x) => ({ w: x.src, why: x.why })), spans: r.plan.spans, gain: r.plan.gain, lift: r.plan.lift ?? null, lufs: r.plan.lufs ?? null, take: r.take.file, from: takeIdOf(r.plan.take), token: r.result?.token ?? null }); + } catch (err) { + if (items.length === 1 || !(err instanceof YellError || err instanceof RereadError)) throw err; + rows.push({ id: e.id, error: err.message }); + } + } + if (json) { + out(JSON.stringify({ ok: true, dryRun, items: rows }, null, 2)); + return 0; + } + for (const r of rows) { + if (r.error && !r.yell?.length) out(`${r.id}: ${r.error}`); + else if (dryRun) out(`${r.id}: ${r.yell.length ? `would yell ${r.yell.join(" ")}` : "nothing to yell"}${r.skip.length ? `; flat: ${r.skip.map((s) => `${s.w} (${s.why})`).join(", ")}` : ""}${r.needsWords ? " -- NEEDS WORD TIMINGS (posts narrate --words)" : r.error ? ` -- ${r.error}` : ""}`); + else out(`${r.id}: yelled ${r.yell.join(" ")} (${r.spans.length} span(s), +${r.gain} dB asked${r.lift !== null && r.lift !== undefined ? `, +${r.lift} dB measured` : ""}${r.lufs ? `, ${r.lufs.base} → ${r.lufs.after} LUFS` : ""})${r.skip.length ? `; flat: ${r.skip.map((s) => `${s.w} (${s.why})`).join(", ")}` : ""}\n ${r.take} -- picked, from ${r.from} (one undo point: umtool timeline ${project.id} undo)`); + } + return 0; +} + +/** `umtool posts yell <p> [--all | <ids…>]`. */ +export async function yellBatchCommand(project, { ids = [], all = false, gain = undefined, style = "raise", dryRun = false, json = false, out = (s) => console.log(s) } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new YellError(`${project.id} has no manifest`); + const tl = (manifest.timeline ?? []).filter((x) => x?.type === "post"); + let items; + if (ids.length) { + items = ids.map((ref) => tl.find((x) => x.id === ref || x.id === `p-${ref}` || String(x.post ?? "").split("/")[1] === ref) ?? (() => { + throw new YellError(`no post item ${ref} in ${project.id}`); + })()); + } else if (all || dryRun) { + // Every narrated item whose read has a caps word to yell (a dry run lists the ones it would skip too). + const slurs = cutSlurs(manifest); + items = tl.filter((e) => { + const row = yellRow(e, slurs); + return !!row && (dryRun || row.yell.length > 0); + }); + } else throw new YellError("name the items, or --all (every narrated item with a caps word); --dry-run lists them"); + if (!items.length) { + out(json ? JSON.stringify({ ok: true, dryRun, items: [] }) : "no narrated item reads a caps word"); + return 0; + } + return yellCommand(project, manifest, items, { gain, style, dryRun, json, out }); +} + +export { capsLine, skipLine }; diff --git a/umtool/lib/report/postYell.test.mjs b/umtool/lib/report/postYell.test.mjs @@ -0,0 +1,126 @@ +// postYell.mjs: THE CAPS YELLED -- which words (his caps found in the read's word timings, acronyms and slurs left +// flat, a piece's caps only in the words that read it), the spans (padded, a run merged), the plan's refusals and +// chain rules, and the file: its length the source's, the spans louder by the lift (measured), the rest untouched, +// its loudness within 1 LU, a derived take picked in one write; chained with the tempo either way. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { validatePostItem } from "umtool-report-to-video/post-item"; +import { acronymWhy, capsOfRead, isCapsWord, spansRms, yellArgs, yellPlan, yellSpans, yellTake } from "./postYell.mjs"; +import { rereadTake } from "./postReread.mjs"; +import { postsCommand } from "./postsCli.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-yell-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const TEXT = "The moment THEY have your Dox ITS ALREADY TOO LATE, the FBI will not help.\n\nYou can HIDE all you want."; +const SCRIPT = "The moment they have your Dox its already too late, the FBI will not help.\n\nYou can hide all you want."; +// One word a 0.4 s slot from 0.2 s; the second paragraph from 6.2 s. +const words = () => { + const ws = SCRIPT.split(/\s+/); + return ws.map((w, i) => { + const at = i < 15 ? 0.2 + i * 0.4 : 6.2 + (i - 15) * 0.4; + return { w, start: Math.round(at * 1000) / 1000, end: Math.round((at + 0.32) * 1000) / 1000 }; + }); +}; +const item = (o = {}) => ({ + type: "post", id: "p-7", post: "subj-x/7", platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: TEXT, + narration: { script: SCRIPT, takes: [{ file: "narration/posts/7/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 9, script: SCRIPT, words: words(), parts: [{ n: 1, para: 0, text: SCRIPT.split("\n\n")[0], start: 0.2, seconds: 5.8 }, { n: 2, para: 1, text: SCRIPT.split("\n\n")[1], start: 6.2, seconds: 2.4 }] }], pick: 0 }, + ...o, +}); + +test("WHICH WORDS: caps of two letters or more; acronyms and letter-runs left flat; his caps found in the read's words", () => { + assert.deepEqual(["ITS", "I'LL", "ISN'T", "I", "10x", "Dox", "FBI's"].map(isCapsWord), [true, true, true, false, false, false, true]); + assert.deepEqual(["FBI", "DM", "KF", "TV", "BS", "NEVER", "OMG", "PST"].map(acronymWhy), ["acronym", "acronym", "acronym", "acronym", "acronym", null, "acronym", "acronym"]); + assert.equal(acronymWhy("KDR"), "letters"); + const c = capsOfRead(item(), item().narration.takes[0]); + assert.deepEqual(c.yell.map((x) => [x.k, x.src]), [[2, "THEY"], [6, "ITS"], [7, "ALREADY"], [8, "TOO"], [9, "LATE"], [17, "HIDE"]]); + assert.deepEqual(c.skip.map((x) => [x.src, x.why]), [["FBI", "acronym"]]); + // Spans: padded, a run of caps one span. + assert.deepEqual(yellSpans(words(), c.yell.map((x) => x.k)), [[0.97, 1.36], [2.57, 4.16], [6.97, 7.36]]); + // No word timings: refused in the plan's words (the --words pass named). + const bare = item(); + delete bare.narration.takes[0].words; + assert.throws(() => yellPlan(bare), /no word timings to find its caps by \(umtool posts narrate <p> p-7 --words\)/); + assert.throws(() => yellPlan(item({ text: SCRIPT })), /no word of its read is in caps/); +}); + +test("A PIECE's caps are looked for only in the words that read it: a caps word of the post he answers is never his", () => { + const e = item({ text: "you can hide all you want.", parents: [{ id: "9", author: "Other", handle: "other", text: "The moment THEY have your Dox ITS ALREADY TOO LATE, the FBI will not help." }] }); + const t = e.narration.takes[0]; + t.parts[0].role = "parent:0"; + t.parts[1].role = "post"; + const c = capsOfRead(e, t); + assert.deepEqual(c.yell.map((x) => [x.src, x.where]), [["THEY", "parent:0"], ["ITS", "parent:0"], ["ALREADY", "parent:0"], ["TOO", "parent:0"], ["LATE", "parent:0"]]); +}); + +test("the ffmpeg: the voice split, the raised branch shaped and limited, the two crossfaded by the spans' envelope in frames", () => { + const p = yellPlan(item()); + const fc = yellArgs("/in.wav", "/o.wav", p, { rate: 24000, layout: "mono" })[8]; + assert.match(fc, /asetnsamples=n=64:p=0,asplit=2\[yd\]\[yw\]/); + assert.match(fc, /equalizer=f=3200:t=o:w=1\.3:g=3,equalizer=f=1100:t=o:w=1:g=1\.5,acompressor=threshold=0\.063:ratio=2\.5/); + assert.match(fc, /alimiter=limit=0\.94:attack=2:release=40:level=false:latency=1/); + assert.match(fc, /between\(t,0\.920,1\.410\)\*clip\(min\(\(t-0\.920\)\/0\.050,\(1\.410-t\)\/0\.050\),0,1\)/); + assert.match(fc, /amix=inputs=2:normalize=0:duration=first,atrim=end_sample=216000\[out\]/); + assert.deepEqual(p.steps[0].spans, p.spans); +}); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(path.join(dir, "narration", "posts", "7"), { recursive: true }); + // A voice-like read: a 180 Hz buzz with harmonics, syllable-pulsed, at about -21 LUFS. + execFileSync("ffmpeg", ["-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='0.12*(sin(2*PI*180*t)+0.5*sin(2*PI*360*t)+0.3*sin(2*PI*2900*t))*(0.55+0.45*sin(2*PI*4*t))':s=24000:d=9", path.join(dir, "narration", "posts", "7", "take-1.orpheus-zac.wav")]); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +test("YELLED: the file as long as its source, its spans louder by the lift (measured), outside them untouched, loudness within 1 LU; picked; re-yelled from the take before; chained with a tempo either way", async () => { + const p = await project("yell", [item()]); + let e = (await manifest(p)).timeline[0]; + const r = await yellTake(p, e, {}); + const t = r.take; + assert.match(t.file, /take-2\.yell-orpheus\.wav$/); + assert.ok(Math.abs(t.seconds - 9) < 0.01, `length ${t.seconds}`); + assert.deepEqual([t.source.from, t.steps[0].op, t.steps[0].params.style], ["take-1.orpheus-zac", "yell", "raise"]); + assert.deepEqual(t.words, words(), "its timings kept"); + const src = path.join(p.dir, "narration/posts/7/take-1.orpheus-zac.wav"); + const out = path.join(p.dir, t.file); + const lift = (await spansRms(out, r.plan.spans)) - (await spansRms(src, r.plan.spans)); + // A third of this read is caps: the loudness rule (≤ 1 LU over its source) lowers the lift asked for, and says so. + assert.ok(lift > 1.5 && lift < 7 && (r.plan.gain < 5.5 || lift > 3.5), `the spans' lift ${lift} dB at ${r.plan.gain} dB asked`); + assert.equal(t.steps[0].params.gain, r.plan.gain); + const flat = (await spansRms(out, [[4.6, 6.6]])) - (await spansRms(src, [[4.6, 6.6]])); + assert.ok(Math.abs(flat) < 0.2, `outside the spans: ${flat} dB`); + assert.ok(r.plan.lufs.after - r.plan.lufs.base <= 1.05, `loudness ${r.plan.lufs.base} → ${r.plan.lufs.after}`); + e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.pick, 1); + assert.deepEqual(validatePostItem(e), []); + // Yelled again: from the take before (never raised twice). + assert.equal(yellPlan(e).take.file, "narration/posts/7/take-1.orpheus-zac.wav"); + // Then re-timed: the yell's take is cut, the yell kept, the words scaled. + const rt = await rereadTake(p, e, { tempo: { 1: 1.3 } }); + assert.equal(rt.take.source.from, "take-2.yell-orpheus"); + e = (await manifest(p)).timeline[0]; + // A yell further up the chain: refused (pick the take before it). + assert.throws(() => yellPlan(e), /made from a yelled one/); + // The other order: re-timed first, then yelled (posts yell): its spans on the tempo's word timings. + const q = await project("yell2", [item()]); + let e2 = (await manifest(q)).timeline[0]; + await rereadTake(q, e2, { tempo: { 1: 1.3 } }); + const lines = []; + const code = await postsCommand(["yell", "yell2", "p-7"], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + assert.equal(code, 0, lines.join("\n")); + assert.match(lines.join("\n"), /p-7: yelled THEY ITS ALREADY TOO LATE HIDE \(3 span\(s\)/); + e2 = (await manifest(q)).timeline[0]; + const y = e2.narration.takes[e2.narration.pick]; + assert.equal(y.steps[0].op, "yell"); + assert.ok(y.steps[0].spans[1][1] < 4.16 / 1.0 && y.steps[0].spans[1][0] < 2.57, "the spans are the re-timed words'"); + // posts yell --dry-run: the list. + const dry = []; + await postsCommand(["yell", "yell2", "--dry-run"], { root: REPORTS, out: (s) => dry.push(s), err: (s) => dry.push(s) }); + assert.match(dry.join("\n"), /p-7: would yell THEY ITS ALREADY TOO LATE HIDE; flat: FBI \(acronym\)/); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -51,6 +51,10 @@ const REREAD_LINES = [ " a READ RE-JOINED without a piece (no TTS): the picked take's kept parts cut from its own file and joined again, a new", " take that is picked (one undo point) -- the post it answers or quotes left unread, a part by number, a part that is", " only a link. set-item thread.parent.<i>|quoted=context|hidden on a piece the take reads runs it first (--no-reread: refused).", + " umtool posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" [--stretch atempo|rubberband] PER-PART TEMPO (no", + " TTS): the parts named read faster (1-1.6, pitch kept), the rest as they were, the words scaled with them; a new take", + " picked. set-item <item> narration.tempo=\"4-16=1.35\" runs it. --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud]:", + " the words he wrote in ALL CAPS raised (acronyms and slurs left), timings kept. umtool posts yell <p> --all|<ids…>: the cut's.", ]; // `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block. @@ -129,8 +133,10 @@ export const POSTS_USAGE = [ " 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] … | 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,", - " or its CLOCK (add clock [--rewind auto|on|off] [--off]) (umtool posts fx --help)", + " 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.", @@ -154,7 +160,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", "--text", "--place", "--rewind", "--zone"]); +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", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -437,8 +443,24 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con } const list = (v) => (v === null ? [] : String(v).split(",").map((x) => x.trim()).filter(Boolean)); const dropParts = list(flags.has("--drop-parts") ? str("--drop-parts") : null).map(Number); - return await rereadCommand(await projectOf(projectArg, root), ref, { without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), dryRun, json, out }).catch((e) => { - throw e?.name === "RereadError" ? new CliError(e.message) : e; + const yell = flags.has("--yell-caps") ? { gain: flags.has("--yell-gain") ? Number(str("--yell-gain")) : undefined, style: flags.has("--yell-style") ? str("--yell-style") : undefined } : null; + return await rereadCommand(await projectOf(projectArg, root), ref, { + without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), + tempoSpec: flags.has("--tempo-for") ? str("--tempo-for") : null, tempo: flags.has("--tempo") ? str("--tempo") : null, parts: flags.has("--parts") ? str("--parts") : null, + stretch: flags.has("--stretch") ? str("--stretch") : "atempo", yell, dryRun, json, out, + }).catch((e) => { + throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; + }); + } + if (verb === "yell") { + // THE CAPS YELLED, cut-wide (postYell.mjs): each item's picked take, no TTS, a new take picked per item. + const { YELL_USAGE, yellBatchCommand } = await import("./postYell.mjs"); + if (!projectArg || flags.has("--help")) { + err(YELL_USAGE); + return 2; + } + return await yellBatchCommand(await projectOf(projectArg, root), { ids: words.slice(2), all: flags.has("--all"), gain: flags.has("--yell-gain") ? Number(str("--yell-gain")) : undefined, style: flags.has("--yell-style") ? str("--yell-style") : undefined, dryRun, json, out }).catch((e) => { + throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; }); } if (verb === "narrate") { @@ -455,7 +477,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con err(FX_USAGE); return 2; } - return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str, off: flags.has("--off") }); + 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"); @@ -710,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"); @@ -920,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)); @@ -930,6 +993,15 @@ async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread const { fitCommand } = await import("./postNarrationCli.mjs"); return fitCommand(await projectOf(projectArg, root), [ref], { linger: m[1] !== undefined ? Number(m[1]) : null, json, out }); } + // narration.tempo="4-16=1.35,21-25=1.3": the picked take's parts RE-TIMED (postReread.mjs tempoPlan, no TTS), a new take picked. + const tempoPair = pairs.find((p) => p.startsWith("narration.tempo=")); + if (tempoPair) { + if (pairs.length > 1) throw new CliError("narration.tempo= goes alone (it is posts reread --tempo-for on this item)"); + const { rereadCommand } = await import("./postReread.mjs"); + return rereadCommand(await projectOf(projectArg, root), ref, { tempoSpec: tempoPair.slice("narration.tempo=".length).replace(/^"|"$/g, ""), json, out }).catch((e) => { + throw e?.name === "RereadError" ? new CliError(e.message) : e; + }); + } // narration.<knob>=…: this post's narration mix (rate, lead, wet …), through the narration's own writer. const narr = pairs.filter((p) => p.startsWith("narration.")); if (narr.length) { diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -199,14 +199,17 @@ async function linkVariant({ src, dst, kept, from }) { for (const f of ownFiles) if (!theirs.includes(f)) await rm(path.join(segOut, f), { force: true }); } - // The keyed renders: chrome/<layer>-frames, with its .key, else the one kept aside. + // The keyed renders: chrome/<layer>-frames, with its .key (or, a sparse + // one -- only the frames its build's chunks read -- its .sparse), else the + // one kept aside. + const marker = async (d) => (await lstat(path.join(d, ".key")).catch(() => null)) ?? (await lstat(path.join(d, ".sparse")).catch(() => null)); const chrome = path.join(src, "chrome"); // Both there: the one whose .key was written last (the other is an older cut's). const layers = new Map(); for (const dir of [chrome, kept]) { for (const f of await names(dir)) { if (!f.endsWith("-frames")) continue; - const key = await lstat(path.join(dir, f, ".key")).catch(() => null); + const key = await marker(path.join(dir, f)); if (!key?.isFile()) continue; const had = layers.get(f); if (!had || key.mtimeMs > had.at) layers.set(f, { dir: path.join(dir, f), at: key.mtimeMs }); @@ -215,8 +218,8 @@ async function linkVariant({ src, dst, kept, from }) { if (layers.size) await mkdir(path.join(dst, "chrome"), { recursive: true }); for (const [name, { dir, at }] of [...layers].sort((x, y) => x[0].localeCompare(y[0]))) { const mine = path.join(dst, "chrome", name); - const ownKey = await lstat(path.join(mine, ".key")).catch(() => null); - const theirKey = await lstat(path.join(dir, ".key")).catch(() => null); + const ownKey = await marker(mine); + const theirKey = await marker(dir); const same = ownKey && theirKey && ownKey.ino === theirKey.ino && ownKey.dev === theirKey.dev; if (ownKey?.isFile() && !same && ownKey.mtimeMs > at) { // This take's own render is the newer: kept; theirs beside it for frame reuse. diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs @@ -1045,7 +1045,7 @@ export class DiskGuardRefused extends Error {} * free?: (dir: string) => Promise<number | null>, pruneAll?: () => Promise<{ freedBytes: number, results: any[] }> }} o * @returns {Promise<{ checked: boolean, freeBefore: number | null, freeAfter: number | null, freedBytes: number }>} */ -export async function diskGuard({ dirs, env = process.env, say = () => {}, free = freeBytesAt, pruneAll = () => pruneAllProjects({ by: "disk-guard" }) }) { +export async function diskGuard({ dirs, env = process.env, say = () => {}, free = freeBytesAt, pruneAll = () => pruneAllProjects({ by: "disk-guard" }), prunePool = poolDeficitPrune }) { const s = guardSettings(env); if (!s.enabled) return { checked: false, freeBefore: null, freeAfter: null, freedBytes: 0 }; const least = async () => { @@ -1069,7 +1069,16 @@ export async function diskGuard({ dirs, env = process.env, say = () => {}, free } catch (err) { say(`disk guard: the prune failed — ${err instanceof Error ? err.message : err}`); } - const after = await least(); + let after = await least(); + // Still under: the render pool gives back what only it holds, least recently used first. + if (after.min !== null && after.min < s.thresholdBytes) { + const r = await prunePool({ dirs, env, deficit: s.thresholdBytes - after.min }).catch(() => null); + if (r?.evicted) { + say(`disk guard: the render pool evicted ${r.evicted} object(s), ${fmtBytes(r.bytes)}`); + freedBytes += r.bytes; + after = await least(); + } + } if (after.min !== null && after.min < s.floorBytes) { throw new DiskGuardRefused( `disk guard: only ${fmtBytes(after.min)} free under ${after.at}, under the ${fmtBytes(s.floorBytes)} a render needs — nothing was rendered. ` + @@ -1080,6 +1089,21 @@ export async function diskGuard({ dirs, env = process.env, say = () => {}, free return { checked: true, freeBefore: before.min, freeAfter: after.min, freedBytes }; } +/** + * The disk guard's last resort before refusing: the render pool (render-pool.mjs) + * of the first of `dirs` it serves, pruned by `deficit` bytes of what only it holds. + */ +async function poolDeficitPrune({ dirs, env, deficit }) { + const { poolFor, poolPrune, poolStats } = await import("umtool-report-to-video/render-pool"); + for (const d of dirs) { + const pool = d ? await poolFor(d, env) : null; + if (!pool) continue; + const st = await poolStats(pool); + return poolPrune(pool, { maxBytes: Math.max(0, st.onlyPool - deficit) }); + } + return null; +} + /** For build-video's CLI: the guard over its --out (or its manifest's directory) and the projects root. */ export async function guardBeforeRender({ out, manifestPath, env = process.env, say }) { const where = out ? path.resolve(/* turbopackIgnore: true */ out) : path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ manifestPath)); diff --git a/umtool/lib/report/takePrune.test.mjs b/umtool/lib/report/takePrune.test.mjs @@ -484,3 +484,22 @@ test("the names it prunes by are its writers' names", async () => { assert.equal(ce.CHUNKS_DIR, "chunks"); assert.equal(ce.HASH_MEMO_FILE, ".content-hashes.json"); }); + +test("the disk guard: still under the threshold after the takes' prune, the render pool gives back what only it holds", async () => { + const GB = 1024 ** 3; + const said = []; + let free = 8 * GB; + let asked = null; + const r = await diskGuard({ + dirs: ["/x"], env: {}, free: async () => free, say: (l) => said.push(l), + pruneAll: async () => ({ freedBytes: 0, results: [] }), + prunePool: async ({ deficit }) => { + asked = deficit; + free += 15 * GB; + return { evicted: 3, bytes: 15 * GB }; + }, + }); + assert.equal(asked, 22 * GB, "the deficit to the 30 GB threshold"); + assert.equal(r.freedBytes, 15 * GB); + assert.ok(said.some((l) => /the render pool evicted 3 object\(s\), 15\.0 GiB/.test(l)), said.join("\n")); +}); diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -1953,6 +1953,38 @@ parsing — wrapping the expression in single quotes is what protects them. 2) encodes that many at once; `REPORT_VIDEO_CHUNKED=0` or `render.chunkedEncode: false` goes back to the batched single pass. It needs no crossfade batches: no chunk opens more than a few segments. +- **A hard-cut deck build is chunked too** (lane fast-fix-render): a take's + `--no-xfade` render, and `--chrome-only` with `transition: 0`. Before, its + picture was the stream-copied concat and then ONE overlay pass over the whole + cut -- 12.6 minutes of mid-6's 30 -- on every take, however small the change. + Now each chunk is one segment's run (a long one cut every 1800 frames from its + first frame), its join chain on it, the deck over it; a post that grew MOVES + the chunks after it without changing their keys (the deck's frame keys are + the same frames, later: measured on mid-6, a post 3 s longer draws no frame + key the cut did not have), so a fix re-encodes the chunks of the segment it + touched. The picture is frame-exact, where the copied concat laid each next + segment at the longer of its picture and its sound (0.30 s, 9 frames, by the + end of mid-6, its last 9 frames cut off); the sound is pinned the same way + (`hardCutSoundArgs`: each segment's sound as PCM exactly as long as its + picture, end to end, encoded once -- begun beside the deck's capture, and + keyed by each segment's SOUND, its audio packets: a fix to a post's picture + alone keeps the cut's sound). +- **The deck is drawn only where a chunk to encode reads it** (`deckWant`, + compose-chrome's `want`): when the deck's shell is the cut's one overlay + layer and the encode is chunked, the build plans its chunks from the deck's + frame keys BEFORE the capture (`planChunks`, `framesNeeded`) and the capture + draws only the frames the chunks to encode read. A take `--from` one whose + frames were pruned no longer captures the whole cut again (mid-6: 11,996 + captures, 90 s) to re-encode one post's chunk. The sequence is then SPARSE: + its `.frame-keys` whole, a `.sparse` (`{ key, frames, absent }`) in place of + its `.key`, never "cached whole"; what it has is reused by key, verify-build + and the prune record read its length from `.sparse`, `take --from` links it + like any keyed layer. `UMTOOL_CHROME_LAZY=0` draws every frame. +- **A chunk's chrome layers key by their frame keys** when a sequence carries + `.frame-keys` (every keyed layer does): what its frames DRAW, not their bytes. + A layer captured again after a prune draws "a hair differently" per renderer + worker, which by bytes made every chunk of the cut new; by keys, a recaptured + deck is the deck it was. A sequence without them keys by its bytes. - **Chrome frames are reused by their keys** (`frame-keys.mjs`). The deck, the stamps, the feed and the finale are cue-interpreter pages, so what a frame draws is the page less its cue list plus every element's value at that frame @@ -2965,7 +2997,7 @@ container. It is encoded again 6 % lower while it lands over (x264 overshoots: 24.3 MiB at a 23.1 target, measured), four tries at most. **From the master's chunks** (`ladder-chunks.mjs`). When the cut is a chunked -build (`chunked-encode.mjs`, the default with a transition) whose chunks are +build (`chunked-encode.mjs`, the default with a transition or a deck) whose chunks are still in `out/sourced/chunks/`, and the master's video packets are those chunks' (checked by content: the sha256 of the master's packets against the chunks' as the build's mux writes them -- a few seconds, no decode, memoised diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -216,6 +216,7 @@ import { // The snap itself (a montage's window snaps with it too), re-exported for the tests. import { snap } from "./snap.mjs"; import { buildPostSegment } from "./post-render.mjs"; +import { TRAILER_AUDIO, trailerHitsGraph } from "./trailer-hits.mjs"; import { planContext, planContextOf } from "./post-conversation.mjs"; /** @@ -241,8 +242,9 @@ export { snap }; import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { keepFramesAsked, keptFramesDir, pruneChromeFrames } from "./prune-frames.mjs"; import { encodeSegmentCached, ffmpegIdentity } from "./segment-cache.mjs"; +import { poolFetch, poolFor, poolPruneThrottled, poolPut } from "./render-pool.mjs"; import { - CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, chunkKey, chunkSpans, framesRead, sequenceIdentity, spanSegments, whyRebuilt, + CHUNKS_DIR, CHUNKS_RECORD, HASH_MEMO_FILE, HashMemo, SPARSE_FILE, chunkKey, chunkSpans, frameFile, frameKeysIdentity, framesRead, readFrameKeys, sequenceIdentity, spanSegments, whyRebuilt, } from "./chunked-encode.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. @@ -2706,94 +2708,18 @@ async function buildNarratedCardSegment(card, render, outDir, nodes, framing, re export const teaserRecordPath = (seg) => seg.replace(/\.mp4$/, ".teaser.json"); /** The teaser sound's level and ceiling: `limit` is −6 dBFS; `level` is set against the ferret cut's loudness (README). */ -export const TEASER_AUDIO = Object.freeze({ level: 1.4, limit: 0.5 }); - -/** A number for an aevalsrc expression: 6 decimals, no trailing zeros. */ -const ev6 = (v) => { - const s = (Math.round(Number(v) * 1e6) / 1e6).toFixed(6).replace(/\.?0+$/, ""); - return s === "-0" ? "0" : s; -}; +export const TEASER_AUDIO = TRAILER_AUDIO; /** * The teaser's sound, as one filtergraph fragment from no inputs to `[ta]`: - * `hits` (`teaserHits`) synthesised in ffmpeg, no samples. - * - * A hit is three layers, each summed over every hit in one `aevalsrc` and - * gated to its own span, so each starts on the sample its time names: - * - the boom: a sine whose pitch drops from f0 to f1 (most of the way in - * ~0.4 s), with its octave for body, on an exponential decay (`decay` is - * the time constant; it is inaudible by ~7×) after a 3 ms attack; - * - the punch: a burst of noise (50 ms time constant), band-passed (180 Hz–3.2 kHz); - * - the tail: a low noise decay (low-passed at 260 Hz) under it. - * A swell is the boom's sine rising f0 → f1 under an envelope that peaks - * three quarters of the way through `dur` and settles, with a breath of the - * low noise. A riser (a dip's, under the black) is a sub whose pitch climbs - * f0 → f1 over `dur` and a noise swell -- its own layer, band-passed - * 400 Hz–6.5 kHz, present only when there is a riser -- both rising (the sub - * squared, the noise cubed) to their peak at the first hit and released over - * `decay`. The noise is a hash of the sample number, not `random()`, so it - * is the same whatever else is in the graph. The sum takes a short low-passed - * echo, then `level`, then a limiter at −6 dBFS (`limit`, no auto-level, - * latency compensated) so hits that overlap still sum cleanly; trimmed and - * padded to exactly `seconds`. No hits: digital silence. + * `hits` (`teaserHits`) synthesised in ffmpeg, no samples -- the trailer hits' + * generator (trailer-hits.mjs trailerHitsGraph, which a post item's slam plays + * too), its labels the teaser's own (`t`). The layers, the echo, the level and + * the limiter are described there; the graph is byte for byte what it was + * before the generator was factored out. */ export function teaserAudioGraph(hits, { seconds, render, level = TEASER_AUDIO.level, limit = TEASER_AUDIO.limit }) { - const rate = render.audioRate; - const layout = render.audioChannels === 1 ? "mono" : "stereo"; - const len = ev6(seconds); - const tail = `atrim=end=${len},apad=whole_dur=${len},asetpts=PTS-STARTPTS[ta]`; - if (!hits.length) return `anullsrc=channel_layout=${layout}:sample_rate=${rate},${tail}`; - const noise = "(2*(sin(n*12.9898+78.233)*43758.5453-floor(sin(n*12.9898+78.233)*43758.5453))-1)"; - const boom = []; - const punch = []; - const rumble = []; - const whoosh = []; - for (const h of hits) { - const a = ev6(h.at); - const u = `(t-${a})`; - const g = ev6(h.gain); - if (h.kind === "riser") { - const D = ev6(h.dur); - const v = `min(${u},${D})`; - const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * h.dur))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`; - const rel = `clip((${ev6(h.dur + h.decay)}-${u})/${ev6(h.decay)},0,1)`; - const span = ev6(h.dur + h.decay); - boom.push(`if(between(t,${a},${a}+${span}),${g}*0.5*pow(${v}/${D},2)*${rel}*sin(2*PI*${phase}),0)`); - whoosh.push(`if(between(t,${a},${a}+${span}),${g}*0.6*pow(${v}/${D},3)*${rel}*${noise},0)`); - continue; - } - if (h.kind === "swell") { - const D = h.dur; - const peak = ev6(D * 0.75); - const v = `min(${u},${ev6(D)})`; - const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * D))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`; - const env = `pow(sin(PI/2*min(1,${u}/${peak})),2)*exp(-max(0,${u}-${peak})/${ev6(h.decay)})`; - const span = ev6(D * 0.75 + h.decay * 7); - boom.push(`if(between(t,${a},${a}+${span}),${g}*0.42*${env}*sin(2*PI*${phase}),0)`); - rumble.push(`if(between(t,${a},${a}+${span}),${g}*0.5*${env}*${noise},0)`); - continue; - } - const k = 0.13; // the pitch drop's time constant - const phase = `(${ev6(h.f1)}*${u}+${ev6((h.f0 - h.f1) * k)}*(1-exp(-${u}/${k})))`; - const span = ev6(h.decay * 7); - boom.push( - `if(between(t,${a},${a}+${span}),${g}*0.3*min(1,${u}/0.003)*exp(-${u}/${ev6(h.decay)})*` + - `(sin(2*PI*${phase})+0.6*exp(-${u}/${ev6(h.decay * 0.6)})*sin(4*PI*${phase})),0)`, - ); - punch.push(`if(between(t,${a},${a}+0.25),${g}*0.5*exp(-${u}/0.05)*${noise},0)`); - rumble.push(`if(between(t,${a},${a}+${ev6(Math.min(2.6, h.decay * 6))}),${g}*0.32*min(1,${u}/0.02)*exp(-${u}/${ev6(h.decay * 1.3)})*${noise},0)`); - } - const src = (terms) => `aevalsrc=exprs='${terms.length ? terms.join("+") : "0"}':s=${rate}:c=${layout}:d=${len}`; - // The riser's layer only when there is one: a teaser without a dip writes the graph it always did. - const w = whoosh.length ? [`${src(whoosh)},highpass=f=400,lowpass=f=6500[tw]`] : []; - return [ - `${src(boom)}[tb]`, - `${src(punch)},highpass=f=180,lowpass=f=3200[tp]`, - `${src(rumble)},lowpass=f=260,lowpass=f=260[tr]`, - ...w, - `[tb][tp][tr]${w.length ? "[tw]" : ""}amix=inputs=${3 + w.length}:normalize=0,aecho=1:1:90|190:0.18|0.09,lowpass=f=5000,` + - `volume=${ev6(level)},alimiter=limit=${ev6(limit)}:level=0:latency=1:attack=2:release=80,${tail}`, - ].join(";"); + return trailerHitsGraph(hits, { seconds, rate: render.audioRate, layout: render.audioChannels === 1 ? "mono" : "stereo", level, limit, prefix: "t" }); } /** The teaser segment's encode: its frames, its sound, the shared parameters. */ @@ -4568,7 +4494,7 @@ export async function concatWithXfade(segments, render, outPath, railPlan, chrom const D = render.transition ?? 0.5; // The cut itself (dips drawn, no rail): in keyed chunks (chunked-encode.mjs). if (!railPlan && dip && D > 0 && chunkedEncodeOn(render)) { - await chunkedXfadeConcat({ segments, render, outPath, chrome, joins, workDir }); + await chunkedConcat({ segments, render, outPath, chrome, joins, workDir }); return; } const { durs } = await cutOffsets(segments, D, render.fps, joins); @@ -4904,7 +4830,9 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins const { a, b } = span; const { first, last } = spanSegments(span, starts, durs, fps); const segs = segments.slice(first, last + 1); - const g = xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, { + // A hard-cut cut (D = 0, a take's): the run joined as hardCutFilterArgs + // joins the whole cut -- each input's join chain, then `concat`. + const g = D === 0 ? hardCutVideoGraph(segs.length, joins ? joins.slice(first, last + 1) : null, render) : xfadeGraph(durs.slice(first, last + 1), D, joins ? joins.slice(first, last + 1) : null, render, { audio: false, ctx: { hasPrev: first > 0, prevJoin: joins?.[first - 1] ?? null, hasNext: last < segments.length - 1 }, // Offsets to the microsecond: one rounded UP past its frame's timestamp @@ -4980,6 +4908,170 @@ export function chunkVideoArgs({ segments, durs, starts, span, D, render, joins } /** + * A run of a hard-cut cut's segments as one picture: each input's join chain + * (its picture half), then `concat` -- hardCutFilterArgs' video side, for a + * chunk of the final encode. One input is its own chain. Pure. + * + * @returns {{ parts: string[], vlab: string }} + */ +export function hardCutVideoGraph(n, joins, render) { + const parts = []; + const vs = []; + for (let i = 0; i < n; i += 1) { + const c = joinInputChain(i, joins?.[i] ?? null, render, { only: "v" }); + parts.push(...c.parts); + vs.push(c.v); + } + if (n === 1) return { parts, vlab: vs[0] }; + parts.push(`${vs.join("")}concat=n=${n}:v=1:a=0[hcv]`); + return { parts, vlab: "[hcv]" }; +} + +/** + * A hard-cut cut's sound (D = 0), as two kinds of ffmpeg run. Pure. + * + * pin(i, seg, out) segment i's sound alone (`-vn`), its join's sound on + * it, laid on its own clock (AUDIO_ON_CLOCK) and PINNED + * to its picture's length in the cut (`durs[i]`, frames + * ÷ fps, hold included) -- as the crossfade's graph pins + * it -- as PCM: an exact number of samples + * encode(list, out) the pins end to end (the concat demuxer: every pin is + * exactly as long as its picture, so each starts on its + * segment's first frame), encoded once + * + * Pinned because a segment's sound routinely ends a few ms off its picture + * (AAC frames do not end on video frames), and the stream-copied concat the + * hard-cut build used to make laid each next segment at the LONGER of the + * two: 34 of mid-6's 84 segments, 0.30 s (9 frames) by the end of its cut, + * the footage and its sound that much behind the deck and its last 9 frames + * cut off. The chunks lay every picture frame-exact; the sound is laid the same. + * + * In pins rather than one graph over every segment: one ffmpeg holding the + * 84 segments open took 241 s for mid-6's sound; the pins, a few at a time, + * and one encode of their PCM take the encode's time (~75 s, native aac). + */ +export function hardCutSoundArgs({ durs, joins = null, render }) { + const head = ["-nostdin", "-v", "error", "-y"]; + const pcm = ["-c:a", "pcm_s16le", "-ar", String(render.audioRate), "-ac", String(render.audioChannels)]; + return { + pin: (i, seg, out) => { + const c = joinInputChain(0, joins?.[i] ?? null, render, { only: "a" }); + const len = durs[i].toFixed(6); + const graph = [...c.parts, `${c.a}${AUDIO_ON_CLOCK},apad=whole_dur=${len},atrim=end=${len},asetpts=PTS-STARTPTS[pa]`].join(";"); + return [...head, "-vn", "-i", seg, "-filter_complex", graph, "-map", "[pa]", ...pcm, "-f", "wav", out]; + }, + encode: (list, out) => [ + ...head, "-f", "concat", "-safe", "0", "-i", list, "-map", "0:a", ...cutAudioEncodeArgs(render), out, + ], + }; +} + +/** The hard-cut sound passes in flight, by their file: the early start and the encode share one. */ +const SOUND_IN_FLIGHT = new Map(); + +/** The content-hash memo of a work dir, one per process (the early sound and the encode share it). */ +const MEMOS = new Map(); +function memoAt(workDir) { + const file = path.join(workDir, HASH_MEMO_FILE); + if (!MEMOS.has(file)) MEMOS.set(file, HashMemo.open(file)); + return MEMOS.get(file); +} + +/** + * A segment's SOUND, as an identity: the sha1 of its audio packets with + * their timestamps (ffmpeg's framehash, stream-copied: no decode, ~0.1 s). + * A post whose picture changed and whose words did not (a caption, a knob) + * has the same sound, and the cut's sound is not encoded again for it. + */ +export async function soundIdentity(file) { + const { stdout } = await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-i", file, "-map", "0:a:0", "-c", "copy", "-f", "framehash", "-hash", "sha256", "-"], { maxBuffer: 1 << 28 }); + const body = String(stdout).split("\n").filter((l) => !l.startsWith("#software")).join("\n"); + return createHash("sha1").update(body).digest("hex"); +} + +/** Each segment's sound identity (soundIdentity), memoised by inode in `memo`, 8 at a time. */ +async function soundIdentities(memo, segments) { + const out = new Array(segments.length); + await runPool(segments.map((s, i) => async () => { + out[i] = await memo.derived(s, "sound", soundIdentity); + if (!out[i]) throw new Error(`the cut's sound: segment ${s} is not a file`); + }), 8); + return out; +} + +/** + * Make (or find) a hard-cut cut's sound: `<dir>/audio-<key>.m4a`, keyed by + * the segments' contents and every argv that makes it (hardCutSoundArgs). + * Started by the build as soon as the segments and joins are known -- beside + * the deck's capture -- and awaited by the chunked encode, which calls it + * again with the same arguments (one pass, shared). Resolves to the file. + * + * @param {{ segments: string[], durs: number[], joins?: Array<object|null>|null, render: object, dir: string, workDir: string, ffmpeg?: string|null }} job + */ +export function hardCutSound(job) { + const run = (async () => { + const { segments, durs, joins = null, render, dir, workDir } = job; + // Keyed by each segment's SOUND, not its file: a fix to a post's picture + // alone leaves the cut's sound as it was. + const sounds = await soundIdentities(await memoAt(workDir), segments); + const ffmpeg = job.ffmpeg ?? (await ffmpegIdentity(FFMPEG)); + const a = hardCutSoundArgs({ durs, joins, render }); + const keyArgv = [...segments.map((_, i) => a.pin(i, `<in:${i}>`, "<pin>")), a.encode("<list>", "<out>")]; + return path.join(dir, `audio-${chunkKey({ keyArgv: keyArgv.flat(), inputs: sounds.map((h) => ({ sound: h })), ffmpeg })}.m4a`); + })(); + return run.then((audio) => { + if (!SOUND_IN_FLIGHT.has(audio)) { + const made = makeHardCutSound(job, audio).finally(() => SOUND_IN_FLIGHT.delete(audio)); + SOUND_IN_FLIGHT.set(audio, made); + } + return SOUND_IN_FLIGHT.get(audio); + }); +} + +/** + * Begin a hard-cut build's sound (hardCutSound) without waiting for it: its + * failure is the chunked encode's to report, when it asks for the same sound. + */ +export async function startHardCutSound({ segments, render, joins = null, outDir }) { + const { durs } = await cutOffsets(segments, 0, render.fps, joins); + hardCutSound({ segments, durs, joins, render, dir: path.join(outDir, CHUNKS_DIR), workDir: outDir }).catch(() => {}); +} + +async function makeHardCutSound({ segments, durs, joins = null, render, dir, workDir }, audio) { + const pool = await poolFor(workDir); + if (await exists(audio)) { + EMIT("note", { message: "final encode: the cut's sound unchanged — reused" }); + await poolPut(pool, "sound", path.basename(audio), { "sound.m4a": audio }); + return { audio, reused: true }; + } + await mkdir(dir, { recursive: true }); + if (await poolFetch(pool, "sound", path.basename(audio), { "sound.m4a": audio })) { + EMIT("note", { message: "final encode: the cut's sound from the render pool" }); + return { audio, reused: true }; + } + const t0 = Date.now(); + const a = hardCutSoundArgs({ durs, joins, render }); + const pins = path.join(workDir, `work-sound-${process.pid}`); + await rm(pins, { recursive: true, force: true }); + await mkdir(pins, { recursive: true }); + try { + const files = segments.map((_, i) => path.join(pins, `pin-${String(i).padStart(4, "0")}.wav`)); + await runPool(segments.map((seg, i) => () => execFileP(FFMPEG, a.pin(i, seg, files[i]), { maxBuffer: 1 << 26 })), 4); + const list = path.join(pins, "pins.txt"); + await writeFile(list, concatListText(files), "utf8"); + await mkdir(dir, { recursive: true }); + const tmp = audio.replace(/\.m4a$/, `.${process.pid}.partial.m4a`); + await execFileP(FFMPEG, a.encode(list, tmp), { maxBuffer: 1 << 26 }); + await rename(tmp, audio); + await poolPut(pool, "sound", path.basename(audio), { "sound.m4a": audio }); + } finally { + await rm(pins, { recursive: true, force: true }); + } + EMIT("note", { message: `final encode: the cut's sound encoded in ${((Date.now() - t0) / 1000).toFixed(1)}s` }); + return { audio, reused: false }; +} + +/** * The cut's sound in one pass: every segment's audio alone (`-vn`), joined * exactly as xfadeGraph joins it (each pinned to its picture's length, the * mutes, holds, fades and dips on their inputs, the acrossfades), encoded @@ -5046,15 +5138,30 @@ export async function logRebuild(workDir, entry) { } /** - * concatWithXfade's chunked encode (chunked-encode.mjs): plan the chunks, - * key each by its inputs' contents, encode only the ones whose key is not on - * disk (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when - * its key matches), and join them into `outPath`. Every chunk's frame count - * is checked, and so is the cut's. + * The chunked final encode (chunked-encode.mjs): plan the chunks, key each by + * its inputs' contents, encode only the ones whose key is not on disk + * (REPORT_VIDEO_CHUNK_JOBS at once), encode the sound once (reused when its + * key matches), and join them into `outPath`. Every chunk's frame count is + * checked, and so is the cut's. + * + * Two callers: concatWithXfade (the crossfaded cut, `D` its transition) and + * the hard-cut deck build (`hardCut`, a take's `--no-xfade`: D = 0, each chunk + * one segment's run, the sound the segments' own, stream-copied when nothing + * is joined) -- which before this re-encoded the whole cut in one overlay + * pass on every build, ~12 minutes for a 31-minute cut. */ -async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, joins = null, workDir }) { - const t0 = Date.now(); - const D = render.transition ?? 0.5; +/** Per chunks dir, the chunk keys this process took from the render pool. */ +const POOLED_CHUNKS = new Map(); + +/** + * The chunked encode's plan, without encoding a frame: every chunk's span, + * key, record and argv, and which of them are on disk (`reused`) and which + * are `todo`. chunkedConcat runs it; so does a build that asks, before the + * deck is captured, which deck frames its chunks to encode will read + * (`frameKeys`: a sequence's frame keys known before its frames are). + */ +export async function planChunks({ segments, render, chrome = null, joins = null, workDir, hardCut = false, frameKeys = null, quiet = false }) { + const D = hardCut ? 0 : render.transition ?? 0.5; const fps = render.fps; const { durs, starts, total } = await cutOffsets(segments, D, fps, joins); const N = Math.round(total * fps); @@ -5065,17 +5172,24 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo }); const dir = path.join(workDir, CHUNKS_DIR); await mkdir(dir, { recursive: true }); - const memo = await HashMemo.open(path.join(workDir, HASH_MEMO_FILE)); + const memo = await memoAt(workDir); const ffmpeg = await ffmpegIdentity(FFMPEG); const prev = await readFile(path.join(dir, CHUNKS_RECORD), "utf8").then((t) => JSON.parse(t), () => null); const prevChunks = Array.isArray(prev?.chunks) ? prev.chunks : []; - EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` }); + if (!quiet) EMIT("note", { message: `final encode: ${spans.length} chunk(s) over ${N} frames — hashing the inputs…` }); const segHash = await memo.hashAll(segments); segHash.forEach((h, i) => { if (!h) throw new Error(`chunked encode: segment ${segments[i]} is not a file`); }); + // Each chrome sequence's frame keys, when it carries them (chunked-encode.mjs): + // a chunk then keys by what its frames draw, not by their bytes. + const frameKeysByDir = new Map(frameKeys ?? []); + for (const r of chrome?.regions ?? []) { + const count = WINDOW_REGIONS.has(r.name) ? Number(r.frameCount) : N; + if (!frameKeysByDir.has(r.frames)) frameKeysByDir.set(r.frames, await readFrameKeys(r.frames, count)); + } const plan = []; for (const span of spans) { const proto = chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: "" }); @@ -5084,7 +5198,8 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo for (const inp of proto.inputs) { if (inp.kind === "seg") ids.push({ seg: segHash[inp.index] }); else { - const id = inp.range ? await sequenceIdentity(memo, inp.dir, inp.range) : "none"; + const fk = frameKeysByDir.get(inp.dir); + const id = !inp.range ? "none" : fk ? frameKeysIdentity(fk, inp.range) : await sequenceIdentity(memo, inp.dir, inp.range); ids.push({ seq: id }); layers[inp.region] = id; } @@ -5101,23 +5216,92 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo graph: createHash("sha1").update(JSON.stringify(proto.keyArgv)).digest("hex").slice(0, 16), }, }; - plan.push({ span, file, rec, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv }); + plan.push({ span, file, rec, inputs: proto.inputs, argv: chunkVideoArgs({ segments, durs, starts, span, D, render, joins, chrome, dips, totalFrames: N, outPath: file.replace(/\.mp4$/, ".partial.mp4") }).argv }); } await memo.save(); - // Reused: on disk with the frames it should have. + // Reused: on disk with the frames it should have -- this take's, or the + // render pool's (render-pool.mjs: the same chunk encoded by any take). + const pool = await poolFor(workDir); + // (The chunks this run took from the pool, said by the encode though the deck's plan took them.) + if (!POOLED_CHUNKS.has(dir)) POOLED_CHUNKS.set(dir, new Set()); + const pooled = POOLED_CHUNKS.get(dir); const todo = []; for (const p of plan) { - const got = (await exists(p.file)) ? await videoFrames(p.file) : null; + let got = (await exists(p.file)) ? await videoFrames(p.file) : null; + if (got !== p.span.b - p.span.a && pool && (await poolFetch(pool, "chunk", p.rec.key, { "chunk.mp4": p.file }))) { + got = await videoFrames(p.file); + if (got === p.span.b - p.span.a) pooled.add(p.rec.key); + } + if (pooled.has(p.rec.key)) p.pooled = true; + // (A chunk of its own the pool has not got -- encoded before it, or linked in by --from -- is filed.) + else if (got === p.span.b - p.span.a && pool) await poolPut(pool, "chunk", p.rec.key, { "chunk.mp4": p.file }); if (got === p.span.b - p.span.a) p.reused = true; else todo.push(p); } + return { D, fps, durs, starts, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash, pool }; +} + +/** + * The deck's `want` (compose-chrome): draw only the frames the chunked + * encode will read -- a fix `--from` a take whose frames were pruned captures + * the touched post's frames, not the whole cut's (mid-6: 11,996 captures, + * 90 s). Only when the deck's shell is the cut's one overlay layer (another + * layer's frames are in the same chunks' keys, and are captured beside it), + * and the encode is chunked. `UMTOOL_CHROME_LAZY=0` draws every frame. + */ +export function deckWant({ schedule, render, outDir, segments, joins = null, hardCut, env = process.env }) { + if (env.UMTOOL_CHROME_LAZY === "0" || !chunkedEncodeOn(render, env)) return null; + const on = deckOverlays().filter((m) => m.on(schedule, render)); + if (on.length !== 1 || on[0].region !== "deck" || on[0].kind !== "overlay-whole") return null; + const regions = on[0].regions(schedule, { render, outDir }); + const framesDir = regions[0].frames; + return (fk) => framesNeeded({ framesDir, fk, segments, render, chrome: { regions, outLabel: "[hfout]" }, joins, workDir: outDir, hardCut }); +} + +/** + * The frames of chrome sequence `framesDir` the chunks to encode read + * (0-based), when its frame keys are `fk`: what a build asks the capture to + * draw (compose-chrome `want`). Every other frame is in a chunk on disk. + */ +export async function framesNeeded({ framesDir, fk, ...job }) { + const { todo, plan } = await planChunks({ ...job, frameKeys: new Map([[framesDir, fk]]), quiet: true }); + const need = new Set(); + for (const p of todo) { + for (const inp of p.inputs) { + if (inp.kind !== "seq" || inp.dir !== framesDir || !inp.range) continue; + for (let n = inp.range[0]; n <= inp.range[1]; n += 1) need.add(n - 1); + } + } + EMIT("note", { message: `chrome: ${todo.length} of ${plan.length} chunk(s) to encode read ${need.size} of ${fk.length} ${path.basename(framesDir)} frames — only those are drawn` }); + return need; +} + +export async function chunkedConcat({ segments, render, outPath, chrome = null, joins = null, workDir, hardCut = false }) { + const t0 = Date.now(); + const { D, fps, durs, N, dir, memo, ffmpeg, prevChunks, plan, todo, segHash, pool } = await planChunks({ segments, render, chrome, joins, workDir, hardCut }); + // A chunk to encode reads every frame it lays: a sparse sequence's absent + // frames are only ever in chunks on disk (framesNeeded), checked here. + const sparse = new Map(); + for (const p of todo) { + for (const inp of p.inputs) { + if (inp.kind !== "seq" || !inp.range) continue; + if (!sparse.has(inp.dir)) sparse.set(inp.dir, await exists(path.join(inp.dir, SPARSE_FILE))); + if (!sparse.get(inp.dir)) continue; + for (let n = inp.range[0]; n <= inp.range[1]; n += 1) { + if (!(await exists(frameFile(inp.dir, n)))) { + throw new Error(`chunked encode: chunk ${p.rec.anchor} reads ${frameFile(inp.dir, n)}, which was not drawn (a sparse ${inp.region} sequence)`); + } + } + } + } const why = new Map(); for (const p of todo) why.set(p, whyRebuilt(p.rec, prevChunks)); const reusedFrames = plan.filter((p) => p.reused).reduce((n, p) => n + (p.span.b - p.span.a), 0); const hms = (f) => `${(f / fps / 60).toFixed(1)} min`; EMIT("note", { - message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused), ` + + message: `final encode: ${plan.length - todo.length}/${plan.length} chunk(s) unchanged (${hms(reusedFrames)} reused` + + `${plan.some((p) => p.pooled) ? `, ${plan.filter((p) => p.pooled).length} from the render pool` : ""}), ` + `${todo.length} to encode (${hms(N - reusedFrames)}, ${chunkJobs()} at a time)`, }); // Why, grouped, so a line says what changed rather than listing 80 chunks. @@ -5128,19 +5312,26 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo EMIT("note", { message: ` encode ${ps.length} chunk(s) — ${w} (at ${at})` }); } - // The sound: one pass, keyed by the segments' contents and its argv. - const audioProto = cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1); - const audioKey = chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg }); - const audio = path.join(dir, `audio-${audioKey}.m4a`); - const audioJob = async () => { + // The sound: one pass, keyed by the segments' contents and its argv (a + // hard cut's pinned end to end, hardCutSound -- perhaps begun already). + const audioProto = D === 0 ? null : cutAudioArgs({ segments: segments.map((_, i) => `<in:${i}>`), durs, D, render, joins, outPath: "" }).slice(0, -1); + let audio = D === 0 ? null : path.join(dir, `audio-${chunkKey({ keyArgv: audioProto, inputs: segHash.map((h) => ({ seg: h })), ffmpeg })}.m4a`); + const audioJob = D === 0 ? async () => { + audio = (await hardCutSound({ segments, durs, joins, render, dir, workDir, ffmpeg })).audio; + } : async () => { if (await exists(audio)) { EMIT("note", { message: "final encode: the cut's sound unchanged — reused" }); return; } + if (await poolFetch(pool, "sound", path.basename(audio), { "sound.m4a": audio })) { + EMIT("note", { message: "final encode: the cut's sound from the render pool" }); + return; + } const ta = Date.now(); const tmp = audio.replace(/\.m4a$/, ".partial.m4a"); await execFileP(FFMPEG, cutAudioArgs({ segments, durs, D, render, joins, outPath: tmp }), { maxBuffer: 1 << 26 }); await rename(tmp, audio); + await poolPut(pool, "sound", path.basename(audio), { "sound.m4a": audio }); EMIT("note", { message: `final encode: the cut's sound encoded in ${((Date.now() - ta) / 1000).toFixed(1)}s` }); }; @@ -5159,6 +5350,7 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo throw new Error(`chunk ${p.rec.anchor} (frames ${p.span.a}–${p.span.b}) encoded ${got} frames, expected ${p.span.b - p.span.a}`); } await rename(tmp, p.file); + await poolPut(pool, "chunk", p.rec.key, { "chunk.mp4": p.file }); done += 1; EMIT("note", { message: `final encode: chunk ${done}/${byKey.size} (${(p.span.a / fps).toFixed(1)}–${(p.span.b / fps).toFixed(1)}s) ` + @@ -5190,6 +5382,7 @@ async function chunkedXfadeConcat({ segments, render, outPath, chrome = null, jo // The memo keeps what this cut is made of: a frame or segment gone is forgotten. memo.pruneUnseen(); await memo.save(); + POOLED_CHUNKS.delete(dir); const keep = new Set([...plan.map((p) => path.basename(p.file)), path.basename(audio), CHUNKS_RECORD, "concat.txt"]); for (const name of await readdir(dir)) if (!keep.has(name)) await rm(path.join(dir, name), { force: true }); @@ -5374,7 +5567,7 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re * feed's, each posts window's, the stamps', the stats'. * Dynamic import: compose-chrome imports this file. */ -async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null }) { +async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null, drawOnly = null }) { const { composeChrome } = await import("./compose-chrome.mjs"); // Each layer's outcome, said and logged (rebuild.ndjson): cached whole, // frames reused, or rendered. @@ -5415,6 +5608,8 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro const r = await composeChrome({ manifestPath, outDir, variant, region: mod.region, doRender: true, fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence", ...win, + // The deck's frames the chunked encode will read, and only those (deckWant). + ...(mod.region === "deck" && drawOnly && duration == null ? { want: drawOnly } : {}), }); if (r.frameCount !== want) { throw new Error( @@ -5427,6 +5622,7 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro emitChrome({ phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", ...named, ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}), + ...(r.absent ? { absent: r.absent } : {}), frames: r.frameCount, key: r.key, dir: r.frames, seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), }); @@ -6498,6 +6694,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // umtool take --keep-frames) has them SET ASIDE in `<out>/.keep-frames/` // instead, for a later `take --from` (prune-frames.mjs). const pruneFrames = async () => { + // The render pool's cap (render-pool.mjs), at most once an hour: least recently used, never a linked object. + const pp = await poolPruneThrottled(await poolFor(outDir)); + if (pp?.evicted) EMIT("note", { message: `render pool: evicted ${pp.evicted} object(s), ${(pp.bytes / (1 << 20)).toFixed(0)} MiB, least recently used first (over its ${(pp.maxBytes / 1024 ** 3).toFixed(0)} GB cap)` }); if (opts.keepFrames || hyper || (deck && opts.noChrome)) return; const aside = (await keepFramesAsked(outRoot)) ? keptFramesDir(outRoot, variant) : null; const p = await pruneChromeFrames(outDir, { setAside: aside }); @@ -6705,6 +6904,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // inputs (null without any). const joins = await cutJoins({ schedule, entries, segments: segs, render }); const prerail = prerailPath(outDir, manifest.slug, D); + if (D === 0 && !opts.chromePreview && chunkedEncodeOn(render)) await startHardCutSound({ segments: segs, render, joins, outDir }); if (opts.chromePreview) { const at = Math.max(0, Math.min(opts.chromePreview.at, schedule.total - 1 / render.fps)); @@ -6727,10 +6927,15 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly return { out, failures: [] }; } - const plan = await renderDeck({ manifestPath, render, outDir, variant, schedule }); + const plan = await renderDeck({ + manifestPath, render, outDir, variant, schedule, drawOnly: deckWant({ schedule, render, outDir, segments: segs, joins, hardCut: D === 0 }), + }); EMIT("chrome", { phase: "overlay" }); EMIT("concat", { mode: D === 0 ? "hardcut" : "xfade", n: segs.length }); - if (D === 0) { + if (D === 0 && chunkedEncodeOn(render)) { + // In keyed chunks, as the full build's (chunkedConcat). + await chunkedConcat({ segments: segs, render, outPath: dirs.final, chrome: plan, joins, workDir: outDir, hardCut: true }); + } else if (D === 0) { // The hard-cut concat is a stream copy of these very segments; when // nothing changed since it was made it is reused, and the overlay is // the only encode. @@ -6831,6 +7036,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const joins = await cutJoins({ schedule: deck ? schedule : null, entries, segments, render }); const railPlan = opts.noRail ? null : await buildRailPlan(manifest, render, entries, segments, D, outDir); + // A hard-cut deck build's sound needs only the segments and the joins: it + // is begun now, beside the deck's capture, and the chunked encode awaits it. + if (D === 0 && deck && !opts.noChrome && !railPlan && chunkedEncodeOn(render)) await startHardCutSound({ segments, render, joins, outDir }); // The rendered chrome, if this manifest asks for it. Absent, `chromePlan` is // null and every line below behaves exactly as it did -- which is the claim @@ -6853,7 +7061,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // skips the render when its key and frame count match). `--no-chrome` keeps // the deck's framing and leaves the panel off -- a fast look at the picture. if (deck && !opts.noChrome) { - chromePlan = await renderDeck({ manifestPath, render, outDir, variant, schedule }); + // Lazily (deckWant) when the cut's chunked encode is the deck's only reader. + const want = !railPlan && (D === 0 || chunkedEncodeOn(render)) ? deckWant({ schedule, render, outDir, segments, joins, hardCut: D === 0 }) : null; + chromePlan = await renderDeck({ manifestPath, render, outDir, variant, schedule, drawOnly: want }); EMIT("chrome", { phase: "overlay" }); } @@ -6877,10 +7087,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly await concatHardCut(segments, outDir, prerail, { joins, render }); await assertConcatLength(prerail, railPlan.total, render.fps, "hard-cut concat"); await applyRail(prerail, final, render, railPlan, null, await cutDips(segments, joins)); - } else if (chromePlan) { + } else if (chromePlan && chunkedEncodeOn(render)) { // Only the deck reaches here (the band refused above, and the deck - // refuses a rail). Hard-cut concat to the prerail, then ONE overlay - // re-encode to the final. + // refuses a rail): in keyed chunks, each a segment's run with the deck + // over it, so a take re-encodes only the chunks whose segment or deck + // frames changed -- a post that grew moves the chunks after it, it does + // not change them (chunkedConcat). + await chunkedConcat({ segments, render, outPath: final, chrome: chromePlan, joins, workDir: outDir, hardCut: true }); + } else if (chromePlan) { + // REPORT_VIDEO_CHUNKED=0: hard-cut concat to the prerail, then ONE + // overlay re-encode to the final. await concatHardCut(segments, outDir, prerail, { record: true, joins, render }); await assertConcatLength(prerail, schedule.total, render.fps, "hard-cut concat"); await applyChrome(prerail, final, render, chromePlan, null, await cutDips(segments, joins)); diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs @@ -30,6 +30,16 @@ // different is a new key. Nothing is keyed by a name or a time that could // say "same" about different pixels. // +// A chrome sequence that carries its FRAME KEYS (`.frame-keys`, written by +// compose-chrome beside its `.key`: what each frame draws, frame-keys.mjs) is +// identified by the keys of the frames a chunk reads rather than by their +// bytes. Those keys are the contract the capture already reuses frames by; +// and a layer captured again (its frames pruned after the last mux) draws +// "a hair differently" per renderer worker -- a few pixels, a few levels -- +// which by bytes made every chunk of the cut new. By keys, a recaptured deck +// is the deck it was, and only a chunk whose frames DRAW something else is +// encoded again. A sequence without them is keyed by its bytes, as before. +// // Plain node; every path is a parameter. import { createHash } from "node:crypto"; @@ -174,6 +184,28 @@ export class HashMemo { return h; } + /** + * Something computed from a file's contents (`compute(file)`, a string), + * memoised beside its hash by the same identity under `tag` -- a segment's + * SOUND, say, which a build keys apart from its picture. null when it is + * not a regular file. + */ + async derived(file, tag, compute) { + const st = await stat(file).catch(() => null); + if (!st?.isFile()) return null; + const id = `${tag}:${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}`; + this.seen.add(id); + const had = this.map.get(id); + if (had) return had; + const h = await compute(file); + const after = await stat(file).catch(() => null); + if (after && `${tag}:${after.dev}:${after.ino}:${after.size}:${after.mtimeMs}` === id) { + this.map.set(id, h); + this.dirty = true; + } + return h; + } + /** Hash many files, `width` at a time; the hashes in order. */ async hashAll(files, width = 8) { const out = new Array(files.length); @@ -206,13 +238,46 @@ export class HashMemo { async save() { if (!this.file || !this.dirty) return; - const tmp = `${this.file}.${process.pid}.tmp`; + // A tmp of its own per save: a build may save while another save of the same memo is in flight. + HashMemo.saves = (HashMemo.saves ?? 0) + 1; + const tmp = `${this.file}.${process.pid}.${HashMemo.saves}.tmp`; await writeFile(tmp, JSON.stringify({ v: 1, h: Object.fromEntries(this.map) }), "utf8"); await rename(tmp, this.file); this.dirty = false; } } +/** Beside a chrome sequence's `.key`: each frame's key, frame 1 on line 1 (compose-chrome writes it). */ +export const FRAME_KEYS_FILE = ".frame-keys"; + +/** + * Beside a SPARSE chrome sequence's `.frame-keys`, in place of its `.key`: + * `{ key, frames, absent }`. compose-chrome writes one when a build asked it + * to capture only the frames its chunks to encode read (`want`): the other + * frames' keys are known and their chunks are on disk, so they are not drawn. + * A sparse sequence is never "cached whole"; what it has is reused by key. + */ +export const SPARSE_FILE = ".sparse"; + +/** + * A sequence's frame keys, when it has them for exactly `count` frames and is + * finished (its `.key` -- or a sparse one's `.sparse` -- is written last); + * else null, and it is keyed by bytes. + */ +export async function readFrameKeys(dir, count) { + const done = async (f) => (await stat(path.join(dir, f)).catch(() => null))?.isFile() === true; + if (!(await done(".key")) && !(await done(SPARSE_FILE))) return null; + const text = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").catch(() => null); + if (!text) return null; + const keys = text.split("\n").filter(Boolean); + return keys.length === count ? keys : null; +} + +/** What a run `[lo, hi]` (1-based) of a sequence contributes to a key, by its frame keys. */ +export function frameKeysIdentity(keys, [lo, hi]) { + return `fk:${createHash("sha1").update(keys.slice(lo - 1, hi).join("\n")).digest("hex")}`; +} + /** A frame sequence's file name for 1-based frame `n` (frame_%06d.png). */ export const frameFile = (dir, n) => path.join(dir, `frame_${String(n).padStart(6, "0")}.png`); diff --git a/umtool/report-to-video/chunked-encode.test.mjs b/umtool/report-to-video/chunked-encode.test.mjs @@ -1,5 +1,5 @@ // The chunked final encode (chunked-encode.mjs, build-video's -// chunkedXfadeConcat): the spans a cut is cut into, what a chunk's key covers +// chunkedConcat): the spans a cut is cut into, what a chunk's key covers // (and that a MOVED chunk keys as it did while a changed input does not), and // real ffmpeg runs -- a chunked build of a small cut with joins, a hold, a dip, // a whole-cut chrome sequence and a posts window, losslessly encoded, frame for @@ -17,7 +17,9 @@ import test from "node:test"; import { CHUNKS_DIR, CHUNKS_RECORD, HashMemo, chunkKey, chunkSpans, framesRead, spanSegments, whyRebuilt, } from "./chunked-encode.mjs"; -import { chunkVideoArgs, concatWithXfade, dipWindows, setProgressMode, withCutEdits, xfadeConcatArgs } from "./build-video.mjs"; +import { + applyChromeArgs, chunkVideoArgs, chunkedConcat, concatListText, concatWithXfade, dipWindows, hardCutFilterArgs, setProgressMode, withCutEdits, xfadeConcatArgs, +} from "./build-video.mjs"; import { scheduleFrom } from "./deck.mjs"; test("chunkSpans: anchored where each segment is fully in, long spans cut from the anchor", () => { @@ -335,3 +337,222 @@ test("two spans that key alike are encoded once and joined twice", { skip: !have rmSync(dir, { recursive: true, force: true }); } }); + +// ---- the hard-cut deck build (a take's --no-xfade) ---------------------------- + +/** A segment whose sound runs `extra` seconds past its picture (as an AAC-padded one does). */ +function longSoundSegment(dir, i, frames, fps, extra) { + const out = path.join(dir, `l${i}.mp4`); + run([ + "-v", "error", "-y", + "-f", "lavfi", "-i", `testsrc2=s=64x36:r=${fps}:d=${frames / fps + 1},trim=end_frame=${frames},colorchannelmixer=rr=${0.4 + 0.1 * i}`, + "-f", "lavfi", "-i", `sine=f=${300 + 100 * i}:r=48000:d=${frames / fps + extra}`, + "-map", "0:v", "-map", "1:a", "-ac", "2", + "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", + out, + ]); + return out; +} + +/** A sequence directory made of other frames (hard links), with frame keys when `keys` is given. */ +function linkedSequence(dir, files, keys = null) { + rmSync(dir, { recursive: true, force: true }); + mkdirSync(dir, { recursive: true }); + files.forEach((f, k) => linkSync(f, path.join(dir, `frame_${String(k + 1).padStart(6, "0")}.png`))); + if (keys) { + writeFileSync(path.join(dir, ".frame-keys"), keys.join("\n") + "\n"); + writeFileSync(path.join(dir, ".key"), "k\n"); + } +} + +const R10 = { width: 64, height: 36, fps: 10, transition: 0, audioRate: 48000, audioChannels: 2, preset: "ultrafast", crf: 0, palette: { bg: "#101820" } }; + +test("a chunked hard-cut deck build is the hard-cut concat and its overlay pass, frame for frame, with NO drift: each segment at its own frame, its sound with it", { skip: !have }, async () => { + const fps = 10; + const dir = mkdtempSync(path.join(tmpdir(), "chunked-hc-")); + const events = []; + setProgressMode((e) => events.push(e)); + process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; + try { + // Each segment's sound runs past its picture (0.15 s): a stream-copied + // concat laid each next segment that much late. + const lens = [25, 40, 33, 30]; + const segments = lens.map((f, i) => longSoundSegment(dir, i, f, fps, 0.15)); + const N = lens.reduce((a, b) => a + b, 0); + sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12); + const chrome = { regions: [{ name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" }; + + // The old path's drift: the copied concat is longer than the segments' frames. + const list = path.join(dir, "list.txt"); + writeFileSync(list, concatListText(segments)); + const copied = path.join(dir, "copied.mp4"); + run(["-v", "error", "-y", "-f", "concat", "-safe", "0", "-fflags", "+genpts", "-i", list, "-c", "copy", copied]); + assert.ok(audioSeconds(copied) > N / fps + 0.4, `the copy laid each segment by its sound (${audioSeconds(copied)} vs ${N / fps})`); + + // Frame-exact: the segments' pictures end to end (lossless; a silent + // track for the overlay pass to copy), then one overlay pass. + const prerail = path.join(dir, "prerail.mp4"); + run([ + "-v", "error", "-y", ...segments.flatMap((f) => ["-i", f]), "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", + "-filter_complex", `${segments.map((_, i) => `[${i}:v]`).join("")}concat=n=${segments.length}:v=1:a=0[v]`, + "-map", "[v]", "-map", `${segments.length}:a`, "-shortest", + "-c:v", "libx264", "-preset", "ultrafast", "-qp", "0", "-pix_fmt", "yuv420p", "-r", String(fps), "-c:a", "aac", prerail, + ]); + assert.equal(probeFrames(prerail), N); + const single = path.join(dir, "single.mp4"); + run(applyChromeArgs(prerail, single, R10, chrome).slice(1)); + + const chunked = path.join(dir, "chunked.mp4"); + await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true }); + assert.equal(probeFrames(chunked), N); + const want = frameMd5(single); + const got = frameMd5(chunked); + assert.equal(got.length, want.length); + assert.deepEqual(got.map((h, f) => (h === want[f] ? null : f)).filter((f) => f != null), [], "every frame is the overlay pass's"); + // The sound pinned to the picture: as long as the cut, every segment's at its own frame. + assert.ok(Math.abs(audioSeconds(chunked) - N / fps) < 0.03, `the sound runs the cut (${audioSeconds(chunked)} vs ${N / fps})`); + // NO DRIFT (lane/join-continuity: mid-7's master ran 0.33-0.385 s late on its schedule by the end, + // the concat demuxer placing each file by its longer stream). The master is the segments' + // pictures summed, frame for frame; each segment's first frame is at its schedule's frame and + // its own tone is playing just after it -- where the copied concat had the one before still. + const starts = lens.map((_, i) => lens.slice(0, i).reduce((a, b) => a + b, 0)); + // (Without the deck -- whose overlay converts every pixel through RGB -- the lossless master is the + // segments' own frames, exactly.) + const bareDir = path.join(dir, "bare"); + mkdirSync(bareDir); + const bare = path.join(bareDir, "bare.mp4"); + await chunkedConcat({ segments, render: R10, outPath: bare, workDir: bareDir, hardCut: true }); + const master = frameMd5(bare); + assert.equal(master.length, lens.reduce((a, b) => a + b, 0), "the master is the sum of the segments' pictures"); + segments.forEach((f, i) => { + assert.deepEqual(master.slice(starts[i], starts[i] + lens[i]), frameMd5(f), `segment ${i} is the master's frames ${starts[i]}-${starts[i] + lens[i] - 1}, exactly`); + }); + const toneAt = (file, at) => { + const r = spawnSync("ffmpeg", ["-v", "error", "-ss", String(at), "-t", "0.2", "-i", file, "-map", "0:a", "-ac", "1", "-ar", "48000", "-f", "s16le", "-"], { maxBuffer: 1 << 24 }); + const pcm = new Int16Array(r.stdout.buffer, r.stdout.byteOffset, r.stdout.length >> 1); + let z = 0; + for (let k = 1; k < pcm.length; k += 1) if ((pcm[k - 1] < 0) !== (pcm[k] < 0)) z += 1; + return z / 2 / (pcm.length / 48000); + }; + starts.forEach((s, i) => { + const hz = toneAt(chunked, s / fps + 0.05); + assert.ok(Math.abs(hz - (300 + 100 * i)) < 40, `segment ${i}'s sound starts with its picture (${hz.toFixed(0)} Hz, want ${300 + 100 * i})`); + }); + // (The copied concat, for contrast, is still playing segment 2's tone where segment 3's picture starts.) + assert.ok(Math.abs(toneAt(copied, starts[3] / fps + 0.05) - 600) >= 40, "the copy drifted"); + const record = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); + // Anchored at each segment's start, a long one cut every 24 frames from it. + assert.deepEqual(record.chunks.map((c) => [c.a, c.b]), [[0, 25], [25, 49], [49, 65], [65, 89], [89, 98], [98, 122], [122, 128]]); + for (const c of record.chunks) assert.equal(c.parts.segments.length, 1, "a hard-cut chunk is one segment's run"); + + // Again: nothing encoded. + events.length = 0; + await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true }); + assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "nothing encoded the second time"); + assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? ""))); + + // Segment 2's picture made again, its sound the same packets (a caption + // fixed): its chunks are encoded, the cut's sound is not. + const other = longSoundSegment(dir, 5, 33, fps, 0.15); + const remade = path.join(dir, "remade.mp4"); + run(["-v", "error", "-y", "-i", other, "-i", segments[2], "-map", "0:v", "-map", "1:a", "-c", "copy", remade]); + rmSync(segments[2]); + linkSync(remade, segments[2]); + events.length = 0; + await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, workDir: dir, hardCut: true }); + assert.ok(events.some((e) => /5\/7 chunk\(s\) unchanged/.test(e.message ?? "")), events.map((e) => e.message).join("\n")); + assert.ok(events.some((e) => /sound unchanged/.test(e.message ?? "")), "a new picture over the same sound keeps the cut's sound"); + } finally { + setProgressMode("human"); + delete process.env.REPORT_VIDEO_CHUNK_FRAMES; + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("a chunked hard-cut build with joins (a hold, a dip, the end fade) is hardCutFilterArgs and the overlay, frame for frame", { skip: !have }, async () => { + const fps = 10; + const dir = mkdtempSync(path.join(tmpdir(), "chunked-hcj-")); + setProgressMode(() => {}); + process.env.REPORT_VIDEO_CHUNK_FRAMES = "24"; + try { + const lens = [25, 40, 33, 30]; + const segments = lens.map((f, i) => segment(dir, i, f, fps)); + const joins = withCutEdits([null, { hold: 0.8, move: null }, null, null], 4, { + dips: new Map([[2, { seconds: 0.6, lastFrame: 32, black: 0.3 }]]), + fade: { seconds: 0.5, lastFrame: 29 }, + }); + const durs = lens.map((f, i) => f / fps + (joins?.[i]?.hold ?? 0)); + const N = Math.round(scheduleFrom(durs, 0).total * fps); + sequence(path.join(dir, "chrome", "deck-frames"), N, fps, 64, 12); + const chrome = { regions: [{ name: "deck", frames: path.join(dir, "chrome", "deck-frames"), x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" }; + + const prerail = path.join(dir, "prerail.mp4"); + run(hardCutFilterArgs(segments, joins, R10, prerail).slice(1)); + const single = path.join(dir, "single.mp4"); + run(applyChromeArgs(prerail, single, R10, chrome, null, dipWindows(joins, durs, 0, fps)).slice(1)); + + const chunked = path.join(dir, "chunked.mp4"); + await chunkedConcat({ segments, render: R10, outPath: chunked, chrome, joins, workDir: dir, hardCut: true }); + assert.equal(probeFrames(chunked), N); + assert.deepEqual(frameMd5(chunked), frameMd5(single)); + assert.ok(Math.abs(audioSeconds(chunked) - N / fps) < 0.05, `the sound runs the cut (${audioSeconds(chunked)} vs ${N / fps})`); + } finally { + setProgressMode("human"); + delete process.env.REPORT_VIDEO_CHUNK_FRAMES; + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("a post that grew re-encodes its own chunks only: the deck after it MOVED, keyed by bytes or by its frame keys", { skip: !have }, async () => { + const fps = 10; + const dir = mkdtempSync(path.join(tmpdir(), "chunked-hcs-")); + const events = []; + setProgressMode((e) => events.push(e)); + try { + const lens = [25, 30, 33, 30]; + const segments = lens.map((f, i) => segment(dir, i, f, fps)); + const N = lens.reduce((a, b) => a + b, 0); + // The deck: one frame per cut frame, and its frame keys (here: the frame's own number). + const pool = path.join(dir, "pool"); + sequence(pool, N + 20, fps, 64, 12); + const poolFile = (n) => path.join(pool, `frame_${String(n).padStart(6, "0")}.png`); + const deck = path.join(dir, "chrome", "deck-frames"); + const framesA = Array.from({ length: N }, (_, k) => poolFile(k + 1)); + linkedSequence(deck, framesA, framesA.map((_, k) => `f${k + 1}`)); + const chrome = { regions: [{ name: "deck", frames: deck, x: 0, y: 24, width: 64, height: 12 }], outLabel: "[hfout]" }; + const out = path.join(dir, "cut.mp4"); + await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); + const rec1 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); + assert.equal(rec1.chunks.length, 4); + + // Segment 1 made 7 frames longer; the deck holds its last frame 7 frames more + // and is otherwise the same frames, later. + segments[1] = segment(dir, 7, 37, fps, "s1"); + const grown = [...framesA.slice(0, 55), ...Array(7).fill(framesA[54]), ...framesA.slice(55)]; + const grownKeys = [...Array.from({ length: 55 }, (_, k) => `f${k + 1}`), ...Array(7).fill("f55"), ...Array.from({ length: N - 55 }, (_, k) => `f${k + 56}`)]; + linkedSequence(deck, grown, grownKeys); + events.length = 0; + await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); + const rec2 = JSON.parse(readFileSync(path.join(dir, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); + assert.deepEqual(rec2.chunks.map((c) => c.a), [0, 25, 62, 95]); + const enc = rec2.chunks.filter((c, k) => c.key !== rec1.chunks[k].key).map((c) => c.anchor); + assert.deepEqual(enc, ["s1.mp4@0"], "only the grown segment's chunk is encoded"); + assert.ok(events.some((e) => /3\/4 chunk\(s\) unchanged/.test(e.message ?? "")), events.map((e) => e.message).join("\n")); + assert.equal(probeFrames(out), N + 7); + + // The deck captured again, a hair different (other bytes), drawing the same: by its keys, nothing to encode. + const other = Array.from({ length: N + 7 }, (_, k) => poolFile(((k + 3) % (N + 20)) + 1)); + linkedSequence(deck, other, grownKeys); + events.length = 0; + await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); + assert.ok(events.some((e) => /0 to encode/.test(e.message ?? "")), "recaptured frames with the same keys reuse every chunk"); + // Without frame keys the same frames are other bytes: every chunk again. + linkedSequence(deck, other); + events.length = 0; + await chunkedConcat({ segments, render: R10, outPath: out, chrome, workDir: dir, hardCut: true }); + assert.ok(events.some((e) => /0\/4 chunk\(s\) unchanged/.test(e.message ?? "")), "by bytes, other frames are other chunks"); + } finally { + setProgressMode("human"); + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -44,6 +44,8 @@ import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, t import { GSAP_FILE } from "./chrome-deck.mjs"; import { fxGeometry, threadShotOf } from "./deck.mjs"; import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; +import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs"; +import { poolFor, poolFrame, poolFrameEvents, poolPutFrames } from "./render-pool.mjs"; import { regionCaching, regionModule } from "./modules/index.mjs"; const run = promisify(execFile); @@ -867,7 +869,7 @@ export async function composeChrome({ schedule = null, preview = false, doRender = false, fps = null, workers = null, quality = "high", format = "png-sequence", still = null, png = null, from = 0, duration = null, window = null, segment = null, transition = null, - lease = null, + lease = null, want = null, }) { // The variant's view, and its own out directory. Handed the whole manifest // the band would draw claims this cut never makes, and the deck would name @@ -1017,8 +1019,11 @@ export async function composeChrome({ return { ...result, frames: target, cached: true }; } if (fk) { + // The frames the build will read (`want`, build-video's chunk plan): + // only those are captured; the rest are left out (a SPARSE sequence). + const need = want ? await want(fk) : null; const r = await reuseFrames({ - base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(), + base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(), need, }); if (r) return { ...result, frames: target, ...r }; } @@ -1042,7 +1047,16 @@ export async function composeChrome({ if (got !== frames) { throw new Error(`the ${region} render wrote ${got} frames to ${target}, expected ${frames} (${size.duration}s at ${rate} fps)`); } - if (fk) await writeFrameKeys(target, fk); + if (fk) { + await writeFrameKeys(target, fk); + // Each distinct frame into the render pool (render-pool.mjs). + const pool = await poolFor(base); + if (pool) { + const first = new Map(); + fk.forEach((k, i) => first.has(k) || first.set(k, path.join(target, frameName(i + 1)))); + await poolPutFrames(pool, [...first]); + } + } await writeFile(keyFile, key + "\n", "utf8"); } return { ...result, frames: target, ...(fk ? { reused: 0, captured: frames } : {}) }; @@ -1050,8 +1064,8 @@ export async function composeChrome({ // ---- frame reuse (frame-keys.mjs) -------------------------------------------- -/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1. */ -export const FRAME_KEYS_FILE = ".frame-keys"; +/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1 (the final encode keys its chunks by them). */ +export { FRAME_KEYS_FILE }; const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`; @@ -1145,7 +1159,7 @@ export function frameDedupOn(env = process.env) { * is the cheaper one then), or, with `dedup` off, when nothing on disk has * frame keys. */ -async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true }) { +async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true, need = null }) { const chrome = path.join(base, "chrome"); const candidates = [target, path.join(chrome, `work-from-${stem}-frames`), path.join(chrome, `work-from-own-${stem}-frames`)]; // Every frame on disk, by key: `occ` holds each key's frames as ids @@ -1156,24 +1170,48 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf const have = new Map(); for (const dir of candidates) { const keys = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").then((t) => t.split("\n").filter(Boolean), () => null); - if (!keys || (await framesOnDisk(dir)) !== keys.length) continue; + if (!keys) continue; + // A sparse sequence (`.sparse`) offers the frames it has; any other, all or none. + const sparse = (await stat(path.join(dir, SPARSE_FILE)).catch(() => null))?.isFile() === true; + const present = sparse ? new Set((await readdir(dir)).filter((f) => /^frame_\d+\.png$/.test(f))) : null; + if (!sparse && (await framesOnDisk(dir)) !== keys.length) continue; const d = dirs.length; dirs.push(dir); - keysOf.push(keys); + // (A frame a sparse sequence lacks keys as nothing: never matched.) + keysOf.push(present ? keys.map((k, i) => (present.has(frameName(i + 1)) ? k : null)) : keys); keys.forEach((k, i) => { + if (present && !present.has(frameName(i + 1))) return; if (!occ.has(k)) occ.set(k, []); occ.get(k).push(d * 1e7 + i); if (!have.has(k)) have.set(k, true); }); } if (!dirs.length && !dedup) return null; + // The render pool (render-pool.mjs): a frame of this key drawn by any take of any project. + const pool = await poolFor(base); + if (pool) { + let hits = 0; + let misses = 0; + for (const k of new Set(fk)) { + if (have.has(k)) continue; + const f = await poolFrame(pool, k); + if (f) { + have.set(k, f); + hits += 1; + } else misses += 1; + } + await poolFrameEvents(pool, hits, misses); + } const missing = []; for (let i = 0; i < fk.length; i += 1) if (!have.has(fk[i])) missing.push(i); + // `need` (a Set of 0-based frames): only those are drawn; a frame on no + // disk and not needed is left out, and the sequence is SPARSE. + const wanted = need ? missing.filter((i) => need.has(i)) : missing; // One capture per new key. const seen = new Set(); - const capture = missing.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true))); - if (capture.length > fk.length * 0.9) return null; + const capture = wanted.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true))); + if (!need && capture.length > fk.length * 0.9) return null; const capDir = path.join(chrome, `work-capture-${stem}-frames`); const capProj = path.join(chrome, `work-capture-${stem}`); if (capture.length) { @@ -1192,6 +1230,7 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf const got = await framesOnDisk(capDir); if (got !== capture.length) throw new Error(`the ${region} frame capture wrote ${got} frames to ${capDir}, expected ${capture.length}`); capture.forEach((i, j) => have.set(fk[i], path.join(capDir, frameName(j + 1)))); + if (pool) await poolPutFrames(pool, capture.map((i, j) => [fk[i], path.join(capDir, frameName(j + 1))])); } // Which frame on disk each frame is. One key is often drawn by many frames @@ -1227,6 +1266,9 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf if (g >= 0) off = g - i; } + // Left out: a frame no disk has and nothing captured draws (a frame of a + // captured key is that capture, wanted or not). + const absent = pick.filter((src) => !src); const next = path.join(chrome, `work-next-${stem}-frames`); await rm(next, { recursive: true, force: true }); await mkdir(next, { recursive: true }); @@ -1234,16 +1276,17 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf // A frame deduplicated onto one inode may be at the filesystem's link cap: one copy stands in (link-or-copy.mjs). const linkOne = makeLinker(); for (let i = 0; i < fk.length; i += 512) { - await Promise.all(pick.slice(i, i + 512).map((src, j) => linkOne(src, path.join(next, frameName(i + j + 1))))); + await Promise.all(pick.slice(i, i + 512).map((src, j) => (src ? linkOne(src, path.join(next, frameName(i + j + 1))) : null))); } await writeFrameKeys(next, fk); - await writeFile(path.join(next, ".key"), key + "\n", "utf8"); + if (absent.length) await writeFile(path.join(next, SPARSE_FILE), JSON.stringify({ key, frames: fk.length, absent: absent.length }) + "\n", "utf8"); + else await writeFile(path.join(next, ".key"), key + "\n", "utf8"); const old = path.join(chrome, `work-old-${stem}-frames`); await rm(old, { recursive: true, force: true }); await rename(target, old).catch((e) => { if (e?.code !== "ENOENT") throw e; }); await rename(next, target); for (const d of [old, capDir, capProj, ...candidates.slice(1)]) await rm(d, { recursive: true, force: true }); - return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: missing.length - capture.length }; + return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: wanted.length - capture.length, ...(absent.length ? { absent: absent.length } : {}) }; } if (import.meta.url === `file://${process.argv[1]}`) { diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -27,6 +27,7 @@ import { claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck, } from "./factcheck.mjs"; import { resolveCounter } from "./counter.mjs"; +import { TRAILER_HIT_TIERS, TRAILER_SWELL } from "./trailer-hits.mjs"; import { DECK_PAD_X, COUNTER_CELL } from "./modules/design.mjs"; import { DECK_DEFAULTS, MARKER_ALIGNS, MARKER_DEFAULT_COLOR, MARKER_LAYOUTS, MARKER_LIMITS, MARKER_PALETTE_KEYS, markerShapeErrors, @@ -3160,12 +3161,8 @@ export function teaserHits(entry, D = 0.5, fps = 30) { const { gain, f0, f1 } = DIP_RISER; out.push({ kind: "riser", at, role: "dip", gain, decay: 0.04, f0, f1, dur: Math.round((end - at) * 10000) / 10000 }); } - const HIT = { - title: { gain: 1, decay: 0.42, f0: 92, f1: 40 }, - overline: { gain: 0.72, decay: 0.34, f0: 96, f1: 44 }, - kicker: { gain: 0.8, decay: 0.36, f0: 94, f1: 42 }, - sub: { gain: 0.42, decay: 0.16, f0: 120, f1: 64 }, - }; + // The tiers are the trailer hits' (trailer-hits.mjs, which a post item's slam plays too). + const HIT = TRAILER_HIT_TIERS; lines.forEach((l, i) => { out.push({ kind: "hit", at: times.lines[i].impact, role: l.role, ...HIT[l.role] }); if (l.sub && !l.together && times.lines[i].subAt != null) { @@ -3173,7 +3170,7 @@ export function teaserHits(entry, D = 0.5, fps = 30) { } }); if (tail && times.tailAt != null) { - out.push({ kind: "swell", at: times.tailAt, role: "tail", gain: 0.34, decay: 0.7, f0: 46, f1: 62, dur: times.tailDur }); + out.push({ kind: "swell", at: times.tailAt, role: "tail", ...TRAILER_SWELL, dur: times.tailDur }); } return out; } diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs @@ -424,3 +424,62 @@ test("compose-chrome with the deck's items: a changed title captures only the fr rmSync(dir, { recursive: true, force: true }); } }); + +test("compose-chrome `want`: only the frames asked for are drawn (a SPARSE sequence), and what it has is reused by key", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "frame-want-")); + const env = process.env.HYPERFRAMES_BIN; + try { + const stub = path.join(dir, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const font = path.join(dir, "face.ttf"); + writeFileSync(font, "face"); + const render = { ...RENDER, fontRegular: font, fontBold: font }; + const mp = path.join(dir, "video.manifest.json"); + writeFileSync(mp, JSON.stringify({ slug: "f", render, timeline: [] })); + const out = path.join(dir, "out", "sourced"); + mkdirSync(out, { recursive: true }); + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(schedule(0))); + const { composeChrome, FRAME_KEYS_FILE } = await import("./compose-chrome.mjs"); + const { framesOf, frameKeyOf } = await import("./prune-frames.mjs"); + const { readFrameKeys, SPARSE_FILE } = await import("./chunked-encode.mjs"); + const range = (a, b) => new Set(Array.from({ length: b - a }, (_, k) => a + k)); + const frameFiles = (d) => readdirSync(d).filter((f) => /^frame_\d+\.png$/.test(f)); + let asked = null; + + // Nothing on disk, frames 100..199 wanted: those are drawn, nothing else. + const first = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30, want: async (fk) => ((asked = fk.length), range(100, 200)) }); + assert.equal(asked, 1200, "want is handed every frame's key"); + const seq = first.frames; + const drawn = new Set(frameFiles(seq)); + for (const i of range(100, 200)) assert.ok(drawn.has(`frame_${String(i + 1).padStart(6, "0")}.png`), `frame ${i + 1} drawn`); + assert.ok(drawn.size < 1200 && first.absent === 1200 - drawn.size, `${drawn.size} drawn (a frame of a captured key is that capture), ${first.absent} left out`); + assert.ok(readdirSync(seq).includes(SPARSE_FILE) && !readdirSync(seq).includes(".key"), "sparse: a .sparse, never a .key"); + assert.equal(await framesOf(seq), 1200, "as long as the cut, for verify-build and the prune record"); + assert.equal(await frameKeyOf(seq), first.key); + assert.equal((await readFrameKeys(seq, 1200))?.length, 1200, "its frame keys stand for its chunks"); + const keys = readFileSync(path.join(seq, FRAME_KEYS_FILE), "utf8").trim().split("\n"); + for (const f of drawn) { + const i = Number(f.slice(6, 12)) - 1; + const [, cut] = readFileSync(path.join(seq, f), "utf8").split(":"); + assert.equal(keys[Number(cut)], keys[i], `frame ${i + 1} draws its key`); + } + + // Asked again for 150..299: 150..199 are on disk; only new keys are captured. + const second = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30, want: async () => range(150, 300) }); + for (const i of range(150, 300)) assert.ok(frameFiles(seq).includes(`frame_${String(i + 1).padStart(6, "0")}.png`), `frame ${i + 1} drawn`); + assert.ok(second.reused >= 50, `${second.reused} reused from the sparse sequence`); + + // Without `want`: the whole sequence, a .key and no .sparse; cached whole after. + const third = await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 }); + assert.equal(frameFiles(seq).length, 1200); + assert.ok(readdirSync(seq).includes(".key") && !readdirSync(seq).includes(SPARSE_FILE)); + assert.ok(third.reused > 0); + assert.equal((await composeChrome({ manifestPath: mp, region: "deck", doRender: true, fps: 30 })).cached, true); + } finally { + if (env === undefined) delete process.env.HYPERFRAMES_BIN; + else process.env.HYPERFRAMES_BIN = env; + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/hardcut-deck.test.mjs b/umtool/report-to-video/hardcut-deck.test.mjs @@ -0,0 +1,213 @@ +// A take's render: the deck over HARD CUTS (`transition: 0`), built in keyed +// chunks (build-video chunkedConcat), the deck's frames drawn only where a +// chunk to encode reads them (deckWant / compose-chrome `want`): +// +// - the first build encodes every chunk and draws every frame, then prunes them; +// - the same cut again draws NO frame and encodes no chunk -- the deck's +// frame keys say every chunk on disk is still the cut's -- and verify-build +// still reads the deck as whole; +// - one still made a second longer: its chunk alone is encoded, the deck's +// frames drawn only over it, the chunk after it moved and reused. +// +// Real encodes, kept tiny; the deck's renderer is a stub that logs how many +// frames each render drew. Skipped without ffmpeg/ffprobe. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; +import { buildVideo, setProgressMode } from "./build-video.mjs"; +import { CHUNKS_DIR, CHUNKS_RECORD } from "./chunked-encode.mjs"; +import { PRUNED_RECORD } from "./prune-frames.mjs"; +import { verifyBuild } from "./verify-build.mjs"; + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const RENDER = { + width: 1920, height: 1080, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2, + palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + chrome: { engine: "hyperframes", layout: "deck", deck: {} }, +}; + +const STUB = `#!/usr/bin/env node +import { spawnSync } from "node:child_process"; +import { appendFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs"; +const a = process.argv.slice(2); +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const w = Number((/data-width="(\\d+)"/.exec(html) ?? [0, 640])[1]); +const h = Number((/data-height="(\\d+)"/.exec(html) ?? [0, 360])[1]); +mkdirSync(out, { recursive: true }); +const one = out + "/.one.png"; +spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x112233:size=" + w + "x" + h, "-frames:v", "1", one]); +const n = Math.round(dur * fps); +for (let i = 1; i <= n; i += 1) copyFileSync(one, out + "/frame_" + String(i).padStart(6, "0") + ".png"); +appendFileSync(process.env.HF_LOG, n + "\\n"); +`; + +test("a hard-cut deck build: keyed chunks, and the deck drawn only where a chunk to encode reads it", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-hcdeck-")); + const env = { bin: process.env.HYPERFRAMES_BIN, log: process.env.HF_LOG }; + t.after(() => { + for (const [k, v] of [["HYPERFRAMES_BIN", env.bin], ["HF_LOG", env.log]]) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + setProgressMode("human"); + rmSync(root, { recursive: true, force: true }); + }); + const stub = path.join(root, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const log = path.join(root, "renders.log"); + process.env.HF_LOG = log; + const drawn = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(Number) : []); + + mkdirSync(path.join(root, "stills"), { recursive: true }); + for (const [n, c] of [["one", "334455"], ["two", "554433"], ["three", "445533"]]) { + const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x${c}:size=320x180`, "-frames:v", "1", path.join(root, "stills", `${n}.png`)]); + assert.equal(r.status, 0, String(r.stderr)); + } + const manifestPath = path.join(root, "video.manifest.json"); + const write = (seconds2) => writeFileSync(manifestPath, JSON.stringify({ + slug: "hc", title: "Hard cuts", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, render: RENDER, + timeline: [ + { id: "i1", type: "image", src: "stills/one.png", seconds: 2 }, + { id: "i2", type: "image", src: "stills/two.png", seconds: seconds2 }, + { id: "i3", type: "image", src: "stills/three.png", seconds: 2 }, + ], + })); + const v = path.join(root, "out", "sourced"); + const notes = []; + const events = []; + setProgressMode((e) => { + events.push(e); + if (e.ev === "note") notes.push(e.message); + }); + const record = () => JSON.parse(readFileSync(path.join(v, CHUNKS_DIR, CHUNKS_RECORD), "utf8")); + + // First: every chunk encoded, every frame drawn, the frames pruned after. + write(2); + await buildVideo({ manifestPath, opts: {} }); + const rec1 = record(); + assert.equal(rec1.frames, 60); + assert.deepEqual(rec1.chunks.map((c) => c.anchor), ["i1.mp4@0", "i2.mp4@0", "i3.mp4@0"], "one chunk a segment"); + assert.equal(drawn().reduce((a, b) => a + b, 0) > 0, true); + assert.ok(!existsSync(path.join(v, "chrome", "deck-frames")), "pruned after the mux"); + assert.equal((await verifyBuild(manifestPath, {})).problems.length, 0); + + // The same cut: no chunk encoded, no deck frame drawn. + const before = drawn().length; + notes.length = 0; + await buildVideo({ manifestPath, opts: {} }); + assert.ok(notes.some((m) => /^final encode: 3\/3 chunk\(s\) unchanged/.test(m)), notes.join("\n")); + assert.ok(notes.some((m) => /0 of 3 chunk\(s\) to encode read 0 of 60 deck-frames frames/.test(m)), notes.join("\n")); + assert.equal(drawn().length, before, "the renderer was not run"); + assert.equal(JSON.parse(readFileSync(path.join(v, "chrome", PRUNED_RECORD), "utf8")).dirs["deck-frames"].frames, 60, "the sparse deck recorded as the cut's length"); + assert.deepEqual((await verifyBuild(manifestPath, {})).problems, []); + + // i2 a second longer: its chunk alone, the deck drawn only over it. + notes.length = 0; + write(3); + await buildVideo({ manifestPath, opts: {} }); + const rec3 = record(); + assert.equal(rec3.frames, 70); + const encoded = rec3.chunks.filter((c) => !rec1.chunks.some((o) => o.key === c.key)).map((c) => c.anchor); + assert.deepEqual(encoded, ["i2.mp4@0"], "only the grown still's chunk"); + const read = notes.find((m) => /chunk\(s\) to encode read/.test(m)); + assert.match(read, /1 of 3 chunk\(s\) to encode read (\d+) of 70/); + assert.ok(Number(/read (\d+) of/.exec(read)[1]) <= 32, read); + assert.ok(drawn().slice(before).every((n) => n <= 32), `drawn ${drawn().slice(before)}`); + assert.deepEqual((await verifyBuild(manifestPath, {})).problems, []); + + // --chrome-only over the same segments: the same chunks, nothing drawn or encoded. + const runs = drawn().length; + notes.length = 0; + await buildVideo({ manifestPath, opts: { chromeOnly: true } }); + assert.ok(notes.some((m) => /^final encode: 3\/3 chunk\(s\) unchanged/.test(m)), notes.join("\n")); + assert.equal(drawn().length, runs); + assert.deepEqual(record().chunks.map((c) => c.key), rec3.chunks.map((c) => c.key)); +}); + +test("the render pool: a cut built before it is filed by its next build; another project's build of the same cut takes every chunk and the sound from it", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-hcpool-")); + const env = { bin: process.env.HYPERFRAMES_BIN, log: process.env.HF_LOG, pool: process.env.UMTOOL_RENDER_POOL }; + t.after(() => { + for (const [k, v] of [["HYPERFRAMES_BIN", env.bin], ["HF_LOG", env.log], ["UMTOOL_RENDER_POOL", env.pool]]) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + setProgressMode("human"); + rmSync(root, { recursive: true, force: true }); + }); + const stub = path.join(root, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const log = path.join(root, "renders.log"); + process.env.HF_LOG = log; + const pool = path.join(root, "pool"); + process.env.UMTOOL_RENDER_POOL = pool; + const drawn = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map(Number) : []); + const project = (name) => { + const dir = path.join(root, name); + mkdirSync(path.join(dir, "stills"), { recursive: true }); + for (const [n, c] of [["one", "334455"], ["two", "554433"]]) { + const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x${c}:size=320x180`, "-frames:v", "1", path.join(dir, "stills", `${n}.png`)]); + assert.equal(r.status, 0, String(r.stderr)); + } + const manifestPath = path.join(dir, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify({ + slug: "hc", title: "Pooled", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, render: RENDER, + timeline: [ + { id: "i1", type: "image", src: "stills/one.png", seconds: 2 }, + { id: "i2", type: "image", src: "stills/two.png", seconds: 2 }, + ], + })); + return manifestPath; + }; + const notes = []; + setProgressMode((e) => { + if (e.ev === "note") notes.push(e.message); + }); + // Built before the pool (off), then again with it: what it reused of its own is filed. + process.env.UMTOOL_RENDER_POOL = "0"; + const ma = project("a"); + await buildVideo({ manifestPath: ma, opts: {} }); + process.env.UMTOOL_RENDER_POOL = pool; + await buildVideo({ manifestPath: ma, opts: {} }); + const runs = drawn().length; + const { poolStats } = await import("./render-pool.mjs"); + const s1 = await poolStats(pool); + assert.equal(s1.kinds.chunk.objects, 2, "its chunks filed"); + assert.equal(s1.kinds.sound.objects, 1, "its sound filed"); + + // Project b: the same cut, built anew -- from the pool. + notes.length = 0; + const mb = project("b"); + await buildVideo({ manifestPath: mb, opts: {} }); + assert.ok(notes.some((m) => /^final encode: 2\/2 chunk\(s\) unchanged \(.*2 from the render pool\)/.test(m)), notes.join("\n")); + assert.ok(notes.some((m) => /sound from the render pool/.test(m)), notes.join("\n")); + assert.equal(drawn().length, runs, "no deck frame drawn"); + assert.deepEqual((await verifyBuild(mb, {})).problems, []); + const s2 = await poolStats(pool); + assert.ok(s2.kinds.chunk.hits >= 2 && s2.kinds.sound.hits >= 1); + assert.equal(s2.kinds.chunk.objects, 2, "nothing stored twice"); + + // A build stopped mid-encode, run again: what it encoded is on disk or in + // the pool; only the rest is encoded (here: one chunk lost, taken back). + const chunksB = path.join(root, "b", "out", "sourced", CHUNKS_DIR); + const rec = JSON.parse(readFileSync(path.join(chunksB, CHUNKS_RECORD), "utf8")); + rmSync(path.join(chunksB, rec.chunks[1].file)); + notes.length = 0; + await buildVideo({ manifestPath: mb, opts: {} }); + assert.ok(notes.some((m) => /^final encode: 2\/2 chunk\(s\) unchanged \(.*1 from the render pool\)/.test(m)), notes.join("\n")); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -30,6 +30,7 @@ "./clip-blur": "./clip-blur.mjs", "./clip-words": "./clip-words.mjs", "./compose-chrome": "./compose-chrome.mjs", + "./render-pool": "./render-pool.mjs", "./counter": "./counter.mjs", "./cues": "./cues.mjs", "./cut-points": "./cut-points.mjs", @@ -67,6 +68,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", @@ -81,6 +83,8 @@ "./word-zoom": "./word-zoom.mjs", "./post-caption": "./post-caption.mjs", "./post-clock": "./post-clock.mjs", + "./post-slam": "./post-slam.mjs", + "./trailer-hits": "./trailer-hits.mjs", "./read-follow": "./read-follow.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.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, followKnobs, followSchedule, scopeBlocks 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-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -57,8 +57,12 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco * read as their source (takeSourceOf). */ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); -/** The ops umtool runs itself on a take's own file (no editor job): `rejoin` -- its kept parts cut out and joined again (lib/report/postReread.mjs). */ -export const POST_LOCAL_OPS = Object.freeze(["rejoin"]); +/** + * The ops umtool runs itself on a take's own file (no editor job, no TTS): `rejoin` -- its kept parts cut out and + * joined again; `tempo` -- named parts time-stretched, pitch kept (lib/report/postReread.mjs); `yell` -- the words + * he wrote in ALL CAPS raised, as a voice raised (lib/report/postYell.mjs). + */ +export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell"]); /** The editor's op route for each. */ export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); @@ -148,6 +152,8 @@ export const POST_NARRATION_LIMITS = Object.freeze({ lufs: [-40, -10], speed: [0.5, 2], rate: [0.8, 1.5], + /** A part's own tempo (a `tempo` step: the part time-stretched in the take's file, its pitch kept). */ + tempo: [1, 1.6], /** A script is the whole post read aloud (operator, 2 Nov: never excerpted); the editor's tts op takes 20,000. */ scriptChars: 20000, takes: 50, @@ -181,9 +187,10 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs"]); -const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's. -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece"]); +// `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece", "tempo"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -643,6 +650,10 @@ export function validatePostNarration(e) { for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); // A re-join's record: what it left out (a piece, "part <n>", "url"). if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`); + // A tempo step's record: each run of parts ("4-16", "21") and the tempo it reads at. + if (st.tempo !== undefined && !(isObj(st.tempo) && Object.keys(st.tempo).length <= 200 && Object.entries(st.tempo).every(([r, v]) => /^\d{1,3}(-\d{1,3})?$/.test(r) && numIn(v, POST_NARRATION_LIMITS.tempo)))) errors.push(`${tw}.steps[${k}].tempo must be {"<part>[-<part>]": ${POST_NARRATION_LIMITS.tempo.join("–")}}`); + // A yell step's record: the take seconds it raised. + if (st.spans !== undefined && !(Array.isArray(st.spans) && st.spans.length <= 500 && st.spans.every((x) => Array.isArray(x) && x.length === 2 && fin(x[0]) && fin(x[1]) && x[0] >= 0 && x[1] > x[0]))) errors.push(`${tw}.steps[${k}].spans must be a list of [from, to] (take seconds)`); } }); } @@ -660,6 +671,7 @@ export function validatePostNarration(e) { if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`); if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`); if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); + if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); }); } 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,11 +27,15 @@ 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"; import { applyJoinState, endMediaOf, joinClockOf } from "./post-join.mjs"; import { applyVisitState } from "./post-link-visit.mjs"; import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; +import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); @@ -97,7 +101,7 @@ export function clockJoinExpr(base, d, seconds) { return `${num(base)}+${num(d)}*(1-${e})`; } -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 }) { +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 = []; @@ -177,6 +181,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) { @@ -324,10 +337,30 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render cur = next; } } + // SLAMS (post-slam.mjs): their frames shot alone over the whole box, laid over everything while each is up; then + // the frame's punch at each hit -- the box padded in the card's ground and cropped back, moved on t. + for (const [si, sl] of slams.entries()) { + const li = add(["-f", "concat", "-safe", "0", "-i", sl.list]); + parts.push(`[${li}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS+${num(sl.t0)}/TB[slm${si}]`); + const next = `b${++n}`; + parts.push(`[${cur}][slm${si}]overlay=x=0:y=0:eof_action=pass:enable='between(t,${num(sl.t0)},${num(sl.t3)})'[${next}]`); + cur = next; + } + const landings = slams.flatMap((sl) => sl.landings ?? []); + if (landings.length) { + const amp = SLAM_MOTION.shake.amp * (box.height / 1080); + const P = Math.ceil(amp * 2.2) + 2; + const bg = String(render.palette?.bg ?? "#12100c").replace("#", "0x"); + const next = `b${++n}`; + parts.push(`[${cur}]pad=iw+${2 * P}:ih+${2 * P}:${P}:${P}:color=${bg},crop=${box.width}:${box.height}:'${P}+${slamShakeExpr(landings, "x", amp)}':'${P}+${slamShakeExpr(landings, "y", amp)}'[${next}]`); + cur = next; + } parts.push(`[${cur}]format=yuv420p${place.length ? `,${place.join(",")}` : ",setsar=1"}[v]`); const sil = add(["-f", "lavfi", "-t", num(T), "-i", `anullsrc=channel_layout=stereo:sample_rate=${render.audioRate ?? 48000}`]); // Narrated (post-narration.mjs): the item's own sound is the bed the narrator reads over -- muffled, then clean. - const media = narration && plan.narration ? "pm" : "a"; + // THE SLAM's HITS (post-slam.mjs, trailer-hits.mjs): mixed in after the item's own sound and the read -- no duck. + const outA = slamHitList.length ? "apre" : "a"; + const media = narration && plan.narration ? "pm" : outA; if (audio.length) { parts.push(...audio.map((a) => a.chain)); parts.push(`[${sil}:a]${audio.map((a) => `[${a.label}]`).join("")}amix=inputs=${audio.length + 1}:normalize=0:duration=first[${media}]`); @@ -337,7 +370,12 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render // A take that says a slur the cut masks (post-slurs.mjs takeBleeps): silenced or beeped over it, on the take's own clock. const bl = narration.bleeps?.spans?.length ? bleepFilters(`${vi}:a`, "pnbl", narration.bleeps, { audioRate: render.audioRate ?? 48000, seconds: narration.bleeps.seconds ?? 600 }) : []; parts.push(...bl); - parts.push(...postNarrationFilters({ media: "pm", voice: bl.length ? "pnbl" : `${vi}:a`, out: "a", sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 })); + parts.push(...postNarrationFilters({ media: "pm", voice: bl.length ? "pnbl" : `${vi}:a`, out: outA, sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 })); + } + if (slamHitList.length) { + parts.push(trailerHitsGraph(slamHitList, { seconds: T, rate: render.audioRate ?? 48000, layout: "stereo", prefix: "sl" })); + // A ceiling just under full scale: a hit on a loud word never clips (the read is untouched below it). + parts.push(`[apre][sla]amix=inputs=2:normalize=0:duration=first,alimiter=limit=0.95:level=0:latency=1:attack=2:release=60[a]`); } return [ "-nostdin", "-v", "error", "-y", @@ -382,7 +420,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 = [] }) { +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 : "", @@ -518,8 +556,15 @@ 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 }); + // 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 }); } finally { await browser.close(); } @@ -849,6 +894,177 @@ async function clockPlaceOn(page, { follow, total, size, k }) { } /** + * Each SLAM's FRAMES (post-slam.mjs): on the card page as it is drawn at its + * first hit (read-follow's state then), its words measured -- the matched + * words' lines and the words read at a hit, which it may not cover, and the + * rest of what is drawn, which it may (the gag, for its window) -- the units + * mounted at their size, the row placed (slamLayout: above the line, else + * below it; refused when neither is clear), then the layer shot alone on a + * clear page at every frame of its span (each distinct state once; a pan + * moves the row with the words, measured frame by frame) and a concat list + * holding each for its frames. `slams`: slamPlan's. Returns `[{ ...slam, + * list, t0, t3, layout, size, shots }]`. + */ +export async function shootSlams(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, slams, 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, "slam.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 }); + 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(12 * k); + const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset }; + const cardRect = () => page.evaluate(() => { + const b = document.querySelector("[data-post-card]")?.getBoundingClientRect(); + return b ? { x: b.left, y: b.top, width: b.width, height: b.height } : null; + }); + for (const p of slams) { + await stateAt(p.span.landings[0]); + // Judged at each hit (a pan's words too): what it may not cover, and what it lies over. + const looks = []; + if (p.scope) { + for (const L of follow ? p.span.landings : [p.span.landings[0]]) { + await stateAt(L); + const g = await page.evaluate(measureCaptionWords, { scope: p.scope, from: p.from, to: p.to, avoid: p.avoid }); + if (g.error) throw new Error(`${entry.id}: slam ${p.i + 1}: its words are ${g.error}`); + looks.push(g); + } + await stateAt(p.span.landings[0]); + } + const geo = looks[0] ?? null; + const card = geo ? geo.card : await cardRect(); + if (!card) throw new Error(`${entry.id}: slam ${p.i + 1}: the card is not drawn`); + // Its size by the words' line (one line's height, not a phrase's wrapped box). + const line = geo ? geo.lines.reduce((a, l) => (l.height > a.height ? l : a), geo.lines[0]) : null; + const size = slamSize(p.fx, line, k); + const units = p.units.map((text, kk) => ({ i: p.i, k: kk, text, size, face: SLAM_FACE_STACK[p.fx.face] ?? SLAM_FACE_STACK.jp, vars: slamVars(p.fx, size) })); + const arg = { css: slamCss(), units, dust: [...SLAM_DUST] }; + await page.evaluate(mountSlams, arg); + await page.evaluate(() => document.fonts.ready.then(() => true)); + // Measured again once its face is in. + const boxes = await page.evaluate(mountSlams, arg); + const layout = slamLayout({ + word: geo ? geo.word : null, card, bounds, units: boxes, place: p.fx.place, gap: Math.round(6 * k), + protect: looks.flatMap((l) => [...l.lines, ...l.avoid]), obstacles: looks.flatMap((l) => l.obstacles), + }); + const errs = slamCoverErrors(entry.id, p.i, layout); + if (errs.length) throw new Error(errs.join("; ")); + const q = { ...p, centers: layout.centers }; + // Shot alone: the card hidden, the page clear. + await page.evaluate(() => { + const st = document.createElement("style"); + st.setAttribute("data-pslam-solo", ""); + st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-slams]) { visibility: hidden !important; }"; + document.head.appendChild(st); + }); + const sdir = path.join(dir, `slam-${p.i}`); + await rm(sdir, { recursive: true, force: true }); + await mkdir(sdir, { recursive: true }); + const f0 = Math.max(0, Math.floor(p.span.t0 * fps)); + const f1 = Math.max(f0 + 1, Math.ceil(p.span.t3 * fps)); + const shots = new Map(); + const runs = []; + const base = geo ? geo.word : null; + for (let f = f0; f < f1; f += 1) { + const s = f / fps; + let dx = 0; + let dy = 0; + if (follow && p.scope && base) { + await stateAt(s); + const g = await page.evaluate(measureCaptionWords, { scope: p.scope, from: p.from, to: p.to, avoid: [] }); + if (!g.error) { + dx = Math.round(g.word.x - base.x); + dy = Math.round(g.word.y - base.y); + } + } + const list = slamListAt(q, s, dx, dy); + const key = JSON.stringify(list); + if (!shots.has(key)) { + const png = path.join(sdir, `s-${String(shots.size).padStart(4, "0")}.png`); + await page.evaluate(setSlamState, { list, shake: null }); + await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height }, omitBackground: true }); + shots.set(key, png); + } + if (runs.length && runs[runs.length - 1].key === key) runs[runs.length - 1].n += 1; + else runs.push({ key, n: 1 }); + } + await page.evaluate(setSlamState, { list: [], shake: null }); + await page.evaluate(() => document.querySelectorAll("style[data-pslam-solo]").forEach((el) => el.remove())); + await stateAt(0); + const qq = (f) => `'${f.replace(/'/g, "'\\''")}'`; + const lines = ["ffconcat version 1.0"]; + for (const r of runs) lines.push(`file ${qq(shots.get(r.key))}`, ...concatRate(fps), `duration ${(r.n / fps).toFixed(6)}`); + lines.push(`file ${qq(shots.get(runs[runs.length - 1].key))}`, ...concatRate(fps)); + const list = path.join(sdir, "frames.ffconcat"); + await writeFile(list, lines.join("\n") + "\n", "utf8"); + out.push({ ...q, list, t0: f0 / fps, t3: f1 / fps, landings: p.span.landings, layout, size, shots: shots.size }); + } + } finally { + await ctx.close(); + } + return out; +} + +/** + * 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 @@ -943,6 +1159,7 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin * hold, place; its clock fx's on/rewind -- its `narration.pace`, its id: a * repeated item is its own segment); what it does NOT carry is added here: * captionV / clockV the chip's and the clock's drawing (bumped when their look changes) + * slam a slam's drawing version, its motion and its trailer hit (post-slam.mjs) * clock clockPlan -- this post's time, the time it runs from (the * item before's, when that one is a clock item), the mode * (forward / rewind / none, a forced rewind) and the zone @@ -957,12 +1174,23 @@ export const POST_CAPTION_DRAW_V = 2; */ export const POST_JOIN_DRAW_V = 2; export const POST_CLOCK_DRAW_V = 1; -export function postFxKeyFields(entry, render, prev = null) { +/** + * A SLAM's drawing and sound (post-slam.mjs): bumped when its look changes. Its + * fields are in the entry (`fx`); the key adds this, the motion it is drawn on + * and the trailer hit's tier and level it sounds (trailer-hits.mjs) -- so a + * 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, { 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; @@ -1002,7 +1230,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 } : {}), }; } @@ -1099,17 +1327,37 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box const key = postSegmentKey(postSegmentKeyOf({ entry, redaction, box, place, render, encode, stamps, avatars, take, plan, bleeps, layout, from, prev })); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); + // The render pool (render-pool.mjs): this item, by this key, built by any take of any project. + const pool = await poolFor(outDir); if (had?.key === key && (await stat(seg).catch(() => null))) { emit("note", { message: `${entry.id}: post item unchanged — its segment kept` }); + // (One the pool has not got -- built before it, or linked in by --from -- is filed now: the item as + // post-render made it, which a combo badge's pass keeps beside it as `.plain.mp4`.) + if (pool) { + const badged = await stat(seg.replace(/\.mp4$/, ".combo.json")).catch(() => null); + const plain = seg.replace(/\.mp4$/, ".plain.mp4"); + const made = !badged ? seg : (await stat(plain).catch(() => null)) ? plain : null; + if (made) await poolPut(pool, "post", key, { "seg.mp4": made, "post.json": record }); + } + return seg; + } + if (pool && (await poolFetch(pool, "post", key, { "seg.mp4": seg, "post.json": record }))) { + emit("note", { message: `${entry.id}: post item from the render pool (key ${key.slice(0, 12)})` }); return seg; } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); const zoomPlan = postZoomPlan(entry, render, plan.total, plan.narration); // 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 }); + // Its slams (post-slam.mjs): never up with a zoom; gone by the media phase (a stack card), as a caption is. + const fxEnd = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total; + const slPlan = slamPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: fxEnd, schedule: plan.narration ?? undefined }); + // A caption up with a slam WAITS for it to be gone (the slam first, then the chip), as it waits for a zoom. + 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)) : [] }); + // 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). @@ -1143,7 +1391,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 }); + 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) { @@ -1154,16 +1402,19 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box // 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 }); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. - await writeFile(`${record}.tmp`, 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, rel: c.placed.rel, 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, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(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 } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); + await writeFile(`${record}.tmp`, 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, rel: c.placed.rel, 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, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(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 } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); await rename(`${record}.tmp`, record); + if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record }); 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` }); + 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 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 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" : ""}` }); 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/post-slam.mjs b/umtool/report-to-video/post-slam.mjs @@ -0,0 +1,615 @@ +// A POST ITEM's SLAM (umtool/docs/report-video.md, "A slam"; operator, 4 Nov: +// "as a joke effect I'd like to see the japanese characters of 'fudoshin' +// (不動心) pop in with three trailer hits like a corny effect, make the +// characters gold with a black outline, starting large and shrinking before +// hitting the page like standard trailer hits"; "three hits evenly spaced over +// the pronunciation of the word, one for each character"; "do it above the +// word on the page"; "do the same with baji quan (八极拳)"). +// +// entry.fx = [{ kind: "slam", +// text: "不動心", // the glyphs that slam in (≤ SLAM_TEXT_MAX) +// match?: "Fudōshin", // the word or phrase it lands on (as the card shows it) +// target?: "post" | "quoted" | "parent:<i>", // whose words (default the post's own) +// occurrence?: n, // its n-th time in that text (default 1) +// at?: <item seconds>, // the first hit; absent: the word's start in the take's words +// gap?: s, // seconds between hits; absent: spread over the word's span +// whole?: true, // the text as ONE unit and one hit (default: one per glyph) +// hold?: s, fromScale?: x, // held after the last hit; how big a glyph starts +// color?: "#rrggbb", outline?: "#rrggbb", outlineWidth?: px, +// place?: "over-match" | "center", // above the matched words (default), or the card's middle +// size?: px, // the glyphs' size at rest, px at 1080 (absent: by the word's line) +// face?: "jp" | "sc" | "tc" | "kr", // the CJK face (Noto Sans CJK <face> Black) +// sfx?: "trailer-hit" | "off", volume?: x, swell?: true }] +// +// WHEN: each glyph LANDS on a hit. Absent `at` and `gap`, the hits are spread +// evenly over the matched words' SPOKEN span in the picked take's word timings +// -- the first on its first word's start, the last on its last word's end +// (a phrase: "Baji"'s start to "Quan"'s end) -- else the reading estimate's +// start, `SLAM_GAP` apart. `at` moves the first hit; `gap` overrides the +// spacing. A glyph is in from `hit` before its landing, huge (`fromScale`×) and +// blurred, and SHRINKS onto its spot -- the teaser's slam (deck.mjs +// TEASER_MOTION: power3.in down past rest to `under`, a power2.out settle up to +// it, the blur focusing over hit + 0.12 s) -- with a flash, a dust ring and a +// screen shake as it hits. After the last hit it holds `hold`, then fades. +// +// WHERE: a row of glyphs centred on the matched words and sitting just ABOVE +// their line (below it when there is no room above in the frame; `center`: the +// card's middle), each glyph huge and centred on its own landing spot. It +// follows the card's pan (read-follow): every frame is placed by where the +// words are drawn then. +// +// THE ONE EXEMPTION (deliberate, the gag): the landed row may cover the line +// ABOVE the word -- for the slam's own window only (t0 → t3: its hits, its +// hold, its fade; at most SLAM_LIMITS.hold + the hits' spread). It is drawn +// OVER the card, never in it (no data-w, no data-post-block), so the read-follow +// geometry and readInViewErrors are measured without it; what it may NOT cover +// is checked here instead (slamCoverErrors): the matched words themselves, and +// the words read at each hit. A row that would is placed below the line; when +// neither place is clear the build refuses, in its own words. +// +// THE SOUND: one trailer hit per glyph at its landing (trailer-hits.mjs, the +// teaser's generator, title tier), the tail's swell after the last with +// `swell`, mixed into the segment's audio without ducking the read. +// +// Pure but for the DOM functions (mountSlams, setSlamState), 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, targetScope, targetTextOf } from "./word-zoom.mjs"; +import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; +import { cardWordTimes } from "./post-caption.mjs"; +import { mixHex } from "./post-item.mjs"; +import { TRAILER_HIT_TIERS, TRAILER_SWELL } from "./trailer-hits.mjs"; + +export const SLAM_PLACES = Object.freeze(["over-match", "center"]); +export const SLAM_FACES = Object.freeze(["jp", "sc", "tc", "kr"]); +export const SLAM_SFX = Object.freeze(["trailer-hit", "off"]); +export const SLAM_DEFAULTS = Object.freeze({ + target: "post", occurrence: 1, whole: false, hold: 1.6, fromScale: 3.5, color: "#f5c542", outline: "#000000", + place: "over-match", face: "jp", sfx: "trailer-hit", volume: 1, swell: false, +}); +export const SLAM_LIMITS = Object.freeze({ + at: [0, 600], gap: [0.12, 2], hold: [0.3, 4], fromScale: [1.5, 8], outlineWidth: [0, 30], size: [40, 320], volume: [0, 3], occurrence: [1, 99], +}); +export const SLAM_TEXT_MAX = 12; +/** The spacing between hits when there is no spoken span to spread them over (an `at`, the estimate). */ +export const SLAM_GAP = 0.45; +/** The tightest even spread: hits closer than this are SLAM_GAP_MIN apart. */ +export const SLAM_GAP_MIN = 0.12; +/** + * THE MOTION -- the teaser's slam (deck.mjs TEASER_MOTION: `hit`, `under`, + * `settle`, `blur`; a test holds them equal), from `fromScale` instead of its + * 1.42: `fadeIn` its opacity's rise as it comes in, `out` the row's fade after + * the hold, `flash` / `ring` / `dust` the impact's light, shock ring and dust + * (seconds from the landing), `shake` the frame's punch (px at 1080, its time + * constant, its span, its rate). + */ +export const SLAM_MOTION = Object.freeze({ + hit: 0.2, under: 0.968, settle: 0.5, blur: 18, fadeIn: 0.06, out: 0.35, flash: 0.32, ring: 0.45, dust: 0.55, + shake: Object.freeze({ amp: 9, tau: 0.075, span: 0.3, hz: 23 }), +}); +/** The faces: Noto Sans CJK at its Black weight, the region's forms first. */ +export const SLAM_FACE_STACK = Object.freeze({ + jp: "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', sans-serif", + sc: "'Noto Sans CJK SC', 'Noto Sans CJK JP', 'Source Han Sans CN', sans-serif", + tc: "'Noto Sans CJK TC', 'Noto Sans CJK JP', 'Source Han Sans TW', sans-serif", + kr: "'Noto Sans CJK KR', 'Noto Sans CJK JP', 'Source Han Sans KR', sans-serif", +}); + +const KEYS = new Set(["kind", "text", "target", "match", "occurrence", "at", "gap", "whole", "hold", "fromScale", "color", "outline", "outlineWidth", "place", "size", "face", "sfx", "volume", "swell"]); +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 HEX_RE = /^#[0-9a-fA-F]{6}$/; +const MATCH_MAX = 120; + +/** + * One slam with every default filled in. + * @param {Record<string, any> | null | undefined} fx + * @returns {{ kind?: string, text: string, target: string, match: string, occurrence: number, at?: number, gap?: number, whole: boolean, hold: number, fromScale: number, color: string, outline: string, outlineWidth?: number, place: string, size?: number, face: string, sfx: string, volume: number, swell: boolean }} + */ +export const resolveSlam = (fx) => ({ ...SLAM_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) }); + +/** The slam's units: each glyph (whitespace dropped), or the whole text as one. */ +export function slamUnits(fx) { + const t = String(fx?.text ?? "").trim(); + if (!t) return []; + if (fx?.whole === true) return [t]; + return Array.from(t).filter((c) => c.trim()); +} + +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 slam `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */ +export function slamErrors(e, fx, fw) { + const errors = []; + for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a slam key (${[...KEYS].join(", ")})`); + if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be the glyphs that slam in ("不動心")`); + else if (Array.from(fx.text.trim()).length > SLAM_TEXT_MAX) errors.push(`${fw}.text is longer than ${SLAM_TEXT_MAX} characters (a slam is a few glyphs, not a sentence)`); + const place = fx.place ?? SLAM_DEFAULTS.place; + if (fx.place !== undefined && !SLAM_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${SLAM_PLACES.join(", ")}`); + const target = fx.target ?? "post"; + 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>"`); + const text = typeof target === "string" ? targetTextOf(e, target) : null; + if (fx.match === undefined) { + if (!fin(fx.at)) errors.push(`${fw}: a slam needs its word (match) or its second (at)`); + else if (place === "over-match") errors.push(`${fw}: a slam with no match has no word to land over (place "center", or set match)`); + } else if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase the slam lands on, as the card shows it`); + else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`); + 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"})`); + else { + 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}`); + } + if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, SLAM_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`); + for (const k of ["at", "gap", "hold"]) if (fx[k] !== undefined && !numIn(fx[k], SLAM_LIMITS[k])) errors.push(`${fw}.${k} must be ${SLAM_LIMITS[k][0]}–${SLAM_LIMITS[k][1]} seconds`); + if (fx.fromScale !== undefined && !numIn(fx.fromScale, SLAM_LIMITS.fromScale)) errors.push(`${fw}.fromScale must be ${SLAM_LIMITS.fromScale[0]}–${SLAM_LIMITS.fromScale[1]} (times its size at rest)`); + for (const k of ["outlineWidth", "size"]) if (fx[k] !== undefined && !numIn(fx[k], SLAM_LIMITS[k])) errors.push(`${fw}.${k} must be ${SLAM_LIMITS[k][0]}–${SLAM_LIMITS[k][1]} px (at 1080)`); + if (fx.volume !== undefined && !numIn(fx.volume, SLAM_LIMITS.volume)) errors.push(`${fw}.volume must be ${SLAM_LIMITS.volume[0]}–${SLAM_LIMITS.volume[1]} (times the trailer hit's level)`); + for (const k of ["color", "outline"]) if (fx[k] !== undefined && !(typeof fx[k] === "string" && HEX_RE.test(fx[k]))) errors.push(`${fw}.${k} must be a colour (#rrggbb)`); + if (fx.face !== undefined && !SLAM_FACES.includes(fx.face)) errors.push(`${fw}.face must be one of ${SLAM_FACES.join(", ")}`); + if (fx.sfx !== undefined && !SLAM_SFX.includes(fx.sfx)) errors.push(`${fw}.sfx must be one of ${SLAM_SFX.join(", ")}`); + for (const k of ["whole", "swell"]) if (fx[k] !== undefined && typeof fx[k] !== "boolean") errors.push(`${fw}.${k} must be true or false`); + return errors; +} + +// --------------------------------------------------------------------------- +// WHEN. +// --------------------------------------------------------------------------- + +/** + * Each slam's moment, one per fx (another effect's row is `{ i, kind }`): + * `{ i, t, end, source: "at"|"words"|"estimate" }` -- `t` its matched words' + * spoken start (or `at`), `end` their spoken end (null when unknown: an `at` + * with no words, the 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, end?: number | null, source?: string, error?: string, kind?: string | null }>} + */ +export function slamTimes(entry, render = undefined, schedule = undefined) { + const list = Array.isArray(entry?.fx) ? entry.fx : []; + return list.map((fx0, i) => { + if (!isObj(fx0) || fx0.kind !== "slam") return { i, kind: fx0?.kind ?? null }; + const fx = resolveSlam(fx0); + const w = `${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}")`; + if (typeof fx0.match !== "string") return fin(fx0.at) ? { i, t: r3(fx0.at), end: null, source: "at" } : { i, error: `${w} has no time (set at, or match)` }; + const text = targetTextOf(entry, fx.target); + const m = findMatch(text, fx.match, fx.occurrence); + if (m.error) return { i, error: `${w}: "${fx.match}" is not on the card` }; + // The spoken span, from the take's word timings. + let span = null; + if (isNarrated(entry)) { + const take = pickedTake(entry); + const timed = Array.isArray(take?.words) && take.words.length ? take.words : null; + if (timed) { + const sch = schedule ?? narrationSchedule(entry, render); + const rate = sch.rate || 1; + const map = alignWords(cardWordsOf(text), timed.map((x) => x.w)); + const ks = []; + for (let k = m.from; k <= m.to; k += 1) if (map[k] >= 0) ks.push(map[k]); + if (ks.length) { + const a = timed[ks[0]]; + const b = timed[ks[ks.length - 1]]; + if (fin(a.start) && fin(b.end)) span = { t: r3(sch.at + a.start / rate), end: r3(sch.at + b.end / rate) }; + } + } + } + if (fin(fx0.at)) return { i, t: r3(fx0.at), end: span ? r3(fx0.at + (span.end - span.t)) : null, source: "at" }; + if (span) return { i, t: span.t, end: span.end, source: "words" }; + const wt = cardWordTimes(entry, render, fx.target, schedule); + const t = wt?.times?.[m.from]; + return { i, t: fin(t) ? r3(t) : readingEstimate(m.from), end: null, source: "estimate" }; + }); +} + +/** + * Each unit's LANDING (where its hit sounds), item seconds: `gap` apart when the + * slam sets one; else spread evenly from `t` to `end` (the first on the word's + * start, the last on its end) when the span is known and there are two or more; + * else SLAM_GAP apart. Never closer than SLAM_GAP_MIN. + * @param {Record<string, any>} fx0 + * @param {{ t: number, end?: number | null }} time + * @returns {number[]} + */ +export function slamLandings(fx0, { t, end = null }) { + const n = slamUnits(resolveSlam(fx0)).length; + if (!n) return []; + let gap = SLAM_GAP; + if (fin(fx0?.gap)) gap = fx0.gap; + else if (fin(end) && n > 1 && end > t) gap = (end - t) / (n - 1); + gap = Math.max(SLAM_GAP_MIN, gap); + return Array.from({ length: n }, (_, k) => r3(t + k * gap)); +} + +/** + * One slam's span on the item's clock: in from t0 (its first glyph's start, + * `hit` before its landing) through each landing, held to t2 (`hold` after the + * last), out by t3 -- the hold shortened to end by `end` (the item's last + * second, or a stack card's media phase). `{ t0, t2, t3, landings }` or `{ error }`. + * @param {Record<string, any>} fx0 + * @param {number[]} landings + * @param {{ end?: number }} [o] + */ +export function slamSpan(fx0, landings, { end = Infinity } = {}) { + const fx = resolveSlam(fx0); + if (!landings.length) return { error: "has no glyphs" }; + const last = landings[landings.length - 1]; + const t0 = Math.max(0, landings[0] - SLAM_MOTION.hit); + if (last >= end - 0.05) return { error: `lands at ${r3(last)} s, at or after the item's ${r3(end)} s` }; + let t2 = last + fx.hold; + if (t2 + SLAM_MOTION.out > end) t2 = Math.max(last + 0.15, end - SLAM_MOTION.out); + return { t0: r3(t0), t2: r3(t2), t3: r3(Math.min(end, t2 + SLAM_MOTION.out)), landings }; +} + +const easeIn3 = (x) => Math.min(1, Math.max(0, x)) ** 3; +const easeOut2 = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 2; + +/** + * One unit's look at item second `s` (landing `L`): `{ scale, blur, opacity, + * flash, ring, dust, ghost }` -- scale × its rest size, blur px at 1080, the + * flash's and ghosts' strength 0–1, the ring's and dust's progress 0–1 (-1: + * none) -- or null before it comes in. `fade` is the row's (1 → 0 over its out). + * @param {number} L @param {number} s @param {{ fromScale?: number, fade?: number }} [o] + */ +export function slamUnitAt(L, s, { fromScale = SLAM_DEFAULTS.fromScale, fade = 1 } = {}) { + const M = SLAM_MOTION; + const u = s - (L - M.hit); + if (u < 0) return null; + let scale = 1; + if (u < M.hit) scale = fromScale + (M.under - fromScale) * easeIn3(u / M.hit); + else if (u < M.hit + M.settle) scale = M.under + (1 - M.under) * easeOut2((u - M.hit) / M.settle); + const blur = M.blur * (1 - easeOut2(u / (M.hit + 0.12))); + const opacity = Math.min(1, u / M.fadeIn) * fade; + const v = s - L; + const flash = v >= -0.03 && v < M.flash ? (v < 0 ? 1 + v / 0.03 : 1 - v / M.flash) * fade : 0; + const ring = v >= 0 && v < M.ring ? v / M.ring : -1; + const dust = v >= 0 && v < M.dust ? v / M.dust : -1; + const ghost = u < M.hit ? (1 - u / M.hit) * fade : 0; + return { scale: r3(scale), blur: Math.round(blur * 10) / 10, opacity: r3(opacity), flash: r3(Math.max(0, flash)), ring: r3(ring), dust: r3(dust), ghost: r3(ghost) }; +} + +/** The row's fade at `s` (1 until its hold ends, 0 by t3). */ +export const slamFadeAt = (span, s) => (s < span.t2 ? 1 : s >= span.t3 ? 0 : 1 - (s - span.t2) / Math.max(1e-6, span.t3 - span.t2)); + +/** + * The slam's state at item second `s`: `{ units: [{ k, …slamUnitAt }] }` for + * the units in, or null when it is not up. + * @param {{ span: { t0: number, t2: number, t3: number, landings: number[] }, fromScale: number }} p + * @param {number} s + */ +export function slamStateAt(p, s) { + if (!p?.span || s < p.span.t0 || s >= p.span.t3) return null; + const fade = slamFadeAt(p.span, s); + const units = []; + p.span.landings.forEach((L, k) => { + const st = slamUnitAt(L, s, { fromScale: p.fromScale, fade }); + if (st) units.push({ k, ...st }); + }); + return { units }; +} + +/** The frame's punch at `s` (unit amplitudes: × SLAM_MOTION.shake.amp × k px): `{ x, y }`. */ +export function slamShakeAt(landings, s) { + const { tau, span, hz } = SLAM_MOTION.shake; + let x = 0; + let y = 0; + for (const L of landings) { + const v = s - L; + if (v < 0 || v > span) continue; + const e = Math.exp(-v / tau); + x += e * Math.sin(2 * Math.PI * hz * v); + y += e * 0.75 * Math.cos(2 * Math.PI * hz * 1.37 * v); + } + return { x: r3(x), y: r3(y) }; +} + +/** slamShakeAt's `axis` as an ffmpeg expression of t, × `amp` px ("0" with no landings). */ +export function slamShakeExpr(landings, axis, amp) { + const { tau, span, hz } = SLAM_MOTION.shake; + const n = (v) => String(r3(v)); + const terms = landings.map((L) => { + const u = `(t-${n(L)})`; + const wave = axis === "x" ? `sin(${n(2 * Math.PI * hz)}*${u})` : `0.75*cos(${n(2 * Math.PI * hz * 1.37)}*${u})`; + return `if(between(t,${n(L)},${n(L + span)}),exp(-${u}/${n(tau)})*${wave},0)`; + }); + return terms.length ? `${n(amp)}*(${terms.join("+")})` : "0"; +} + +/** Two slams of one post up at once: their indices, or null. */ +export function overlappingSlams(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; +} + +// --------------------------------------------------------------------------- +// THE SOUND. +// --------------------------------------------------------------------------- + +/** + * The slam's hits as trailer-hits.mjs reads them: one title-tier hit per + * landing, the tail's swell after the last with `swell` (over the hold). Empty + * with `sfx: "off"`. + * @param {Record<string, any>} fx0 + * @param {{ t0: number, t2: number, landings: number[] }} span + */ +export function slamHits(fx0, span) { + const fx = resolveSlam(fx0); + if (fx.sfx === "off") return []; + const out = span.landings.map((at) => ({ kind: "hit", at, role: "title", ...TRAILER_HIT_TIERS.title })); + if (fx.swell === true) { + const last = span.landings[span.landings.length - 1]; + out.push({ kind: "swell", at: r3(last + 0.15), role: "tail", ...TRAILER_SWELL, dur: r3(Math.max(0.6, span.t2 - last)) }); + } + return out; +} + +// --------------------------------------------------------------------------- +// THE PLAN. +// --------------------------------------------------------------------------- + +/** + * Post item `entry`'s slams, resolved: `[{ i, units, scope, from, to, fx, + * t, end, source, span, avoid }]` -- `avoid` the target's word indices read + * near a hit (their start within SLAM_AVOID_WINDOW of one: the row covers + * none of them), the matched words apart (always protected). `zooms`: the + * item's word zooms' spans (a slam up with one is refused); `end`: the last + * second a slam may be up. Throws in the build's words. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @param {{ zooms?: Array<Record<string, any>>, end?: number, schedule?: Record<string, any> }} [o] + */ +export function slamPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) { + const list = Array.isArray(entry?.fx) ? entry.fx : []; + if (!list.some((f) => f?.kind === "slam")) return []; + const times = slamTimes(entry, render, schedule); + const bad = times.filter((t) => t.error); + if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); + /** @type {any[]} */ + const out = []; + for (const [i, fx0] of list.entries()) { + if (fx0?.kind !== "slam") continue; + const fx = resolveSlam(fx0); + const tm = times[i]; + const landings = slamLandings(fx0, { t: Number(tm.t), end: tm.end ?? null }); + const span = slamSpan(fx0, landings, { end }); + if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}") ${span.error} (move its at)`); + const z = zooms.find((zz) => fin(zz.t0) && fin(zz.t3) && zz.t0 < span.t3 && span.t0 < zz.t3); + if (z) throw new Error(`${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}") is up while word zoom ${(z.i ?? 0) + 1} is (one at a time: move one's at)`); + let scope = null, from = -1, to = -1, avoid = []; + if (typeof fx0.match === "string") { + const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence); + scope = targetScope(fx.target); + from = m.from; + to = m.to; + const read = cardWordTimes(entry, render, fx.target, schedule)?.times ?? []; + avoid = read.map((s, k) => (fin(s) && (k < m.from || k > m.to) && landings.some((L) => Math.abs(s - L) <= SLAM_AVOID_WINDOW) ? k : -1)).filter((k) => k >= 0); + } + out.push({ i, units: slamUnits(fx), scope, from, to, fx, t: Number(tm.t), end: tm.end ?? null, source: String(tm.source), span: { ...span, i }, avoid }); + } + const clash = overlappingSlams(out.map((p) => p.span)); + if (clash) throw new Error(`${entry?.id ?? "?"}: slams ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at)`); + return out; +} + +/** A word whose read starts this near a hit is being read as it lands: the row never covers it. */ +export const SLAM_AVOID_WINDOW = 0.25; + +// --------------------------------------------------------------------------- +// WHERE. +// --------------------------------------------------------------------------- + +/** @typedef {{ x: number, y: number, width: number, height: number }} Rect */ +/** @param {Rect} a @param {Rect} b */ +const hits = (a, b) => Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x) > 0.5 && Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y) > 0.5; + +/** The glyphs' size at rest, px: the slam's `size` (at 1080, × k), else by the matched words' line (2.5×), in 64–170 px at 1080. */ +export function slamSize(fx, word, k = 1) { + if (fin(fx?.size)) return Math.round(fx.size * k); + const h = word ? word.height : 50 * k; + return Math.round(Math.min(170 * k, Math.max(64 * k, h * 2.5))); +} + +/** + * THE ROW's PLACE: the units (`units`: each one's box at rest, `{ width, + * height }`, side by side) centred on the matched words (`word`) and sitting + * `gap` above their line -- or, when that leaves the frame (`bounds`) or covers + * a `protect`ed box (the matched words, the words read at a hit), `gap` below + * it; `center`: the card's middle. Kept in the frame (moved in). `{ x, y, width, + * height, centers: [{ x, y }], where: "above"|"below"|"center"|"clamped", + * covers: n (the boxes of `obstacles` it lies over: the gag), blocked: bool + * (it covers a protected box) }`. + * @param {{ word?: Rect | null, card: Rect, bounds: Rect, units: Array<{ width: number, height: number }>, place?: string, gap?: number, protect?: Rect[], obstacles?: Rect[] }} o + */ +export function slamLayout({ word = null, card, bounds, units, place = "over-match", gap = 8, protect = [], obstacles = [] }) { + const W = units.reduce((a, u) => a + u.width, 0); + const H = Math.max(...units.map((u) => u.height)); + const clampX = (x) => Math.min(bounds.x + bounds.width - W, Math.max(bounds.x, x)); + const clampY = (y) => Math.min(bounds.y + bounds.height - H, Math.max(bounds.y, y)); + const tries = []; + if (place === "center" || !word) tries.push({ x: clampX(card.x + card.width / 2 - W / 2), y: clampY(card.y + card.height / 2 - H / 2), where: "center" }); + else { + const x = clampX(word.x + word.width / 2 - W / 2); + const above = word.y - gap - H; + const below = word.y + word.height + gap; + if (above >= bounds.y) tries.push({ x, y: above, where: "above" }); + if (below + H <= bounds.y + bounds.height) tries.push({ x, y: below, where: "below" }); + tries.push({ x, y: clampY(above), where: "clamped" }); + } + const judged = tries.map((t) => { + const r = { x: t.x, y: t.y, width: W, height: H }; + return { ...t, blocked: protect.some((p) => hits(r, p)), covers: obstacles.filter((o) => hits(r, o)).length }; + }); + const pick = judged.find((t) => !t.blocked) ?? judged[0]; + let cx = pick.x; + const centers = units.map((u) => { + const c = { x: Math.round(cx + u.width / 2), y: Math.round(pick.y + H / 2) }; + cx += u.width; + return c; + }); + return { x: Math.round(pick.x), y: Math.round(pick.y), width: Math.round(W), height: Math.round(H), centers, where: pick.where, covers: pick.covers, blocked: pick.blocked }; +} + +/** + * Why a placed row cannot be built, as sentences: it covers the matched words, + * or a word read as a glyph lands (the one exemption -- the line above, for + * the slam's window -- is the gag; these are not). + */ +export function slamCoverErrors(id, i, layout) { + return layout.blocked ? [`${id}: slam ${i + 1} would cover the words being read as it lands (its matched words, or a word read at a hit) -- above and below its line alike: set place "center", a smaller size, or move it`] : []; +} + +// --------------------------------------------------------------------------- +// THE LOOK. +// --------------------------------------------------------------------------- + +/** The CSS of the slams' layer (each unit's colours and face are its own inline variables). */ +export function slamCss() { + return ` +[data-post-fx-slams] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 70; overflow: visible; } +.pslam { position: absolute; left: 0; top: 0; line-height: 1; white-space: nowrap; transform-origin: 50% 50%; opacity: 0; font-weight: 900; font-synthesis: none; will-change: transform, opacity, filter; } +.pslam-g { position: relative; display: block; } +.pslam-back, .pslam-front, .pslam-ghost { display: block; } +.pslam-back { color: var(--pslam-stroke); -webkit-text-stroke: var(--pslam-sw) var(--pslam-stroke); paint-order: stroke fill; + filter: drop-shadow(0 0.05em 0.035em rgba(0,0,0,0.6)) drop-shadow(0 0.015em 0.01em rgba(0,0,0,0.5)); } +.pslam-front { position: absolute; left: 0; top: 0; color: transparent; background: linear-gradient(180deg, var(--pslam-hi) 0%, var(--pslam-gold) 44%, var(--pslam-lo) 56%, var(--pslam-gold) 100%); + -webkit-background-clip: text; background-clip: text; -webkit-text-stroke: max(1px, calc(var(--pslam-sw) * 0.12)) var(--pslam-lo); } +.pslam-ghost { position: absolute; left: 0; top: 0; color: var(--pslam-gold); opacity: 0; transform-origin: 50% 50%; -webkit-text-stroke: var(--pslam-sw) var(--pslam-stroke); paint-order: stroke fill; } +.pslam-flash { position: absolute; left: 50%; top: 50%; width: 2.4em; height: 2.4em; margin: -1.2em 0 0 -1.2em; border-radius: 50%; opacity: 0; + background: radial-gradient(circle, rgba(255,252,232,0.95) 0%, var(--pslam-flash) 30%, rgba(0,0,0,0) 68%); } +.pslam-ring { position: absolute; left: 50%; top: 50%; width: 1.5em; height: 1.5em; margin: -0.75em 0 0 -0.75em; border-radius: 50%; opacity: 0; + border: 0.05em solid var(--pslam-hi); box-shadow: 0 0 0.12em var(--pslam-gold); } +.pslam-dust { position: absolute; left: 50%; top: 62%; width: 0; height: 0; } +.pslam-dust i { position: absolute; left: 0; top: 0; width: 0.07em; height: 0.07em; margin: -0.035em; border-radius: 50%; background: var(--pslam-hi); opacity: 0; } +`; +} + +/** A unit's colour variables: its gold's highlight, body and shadow, its outline and width (px at its size). */ +export function slamVars(fx, size) { + const f = resolveSlam(fx); + const sw = fin(fx?.outlineWidth) ? fx.outlineWidth * (size / 120) : Math.max(4, size * 0.11); + return { + "--pslam-gold": f.color, "--pslam-hi": mixHex(f.color, "#ffffff", 0.62), "--pslam-lo": mixHex(f.color, "#5a3a00", 0.55), + "--pslam-stroke": f.outline, "--pslam-sw": `${Math.round(sw * 10) / 10}px`, "--pslam-flash": `${f.color}aa`, + }; +} + +/** The dust's directions (degrees): a fan up and out from the foot of the glyph. */ +export const SLAM_DUST = Object.freeze([-170, -150, -128, -105, -80, -55, -32, -10, 200, 225]); + +/** + * Mount the slams' units over the card page: `{ css, units: [{ i, k, text, + * size, face, vars }] }`. Returns each one's box at rest `[{ i, k, width, + * height }]` (its glyph's em box: line height 1). + * @param {{ css?: string, units?: Array<{ i: number, k: number, text: string, size: number, face: string, vars: Record<string, string> }>, dust?: number[] } | null} arg + * @param {Document} [doc] + * @returns {Array<{ i: number, k: number, width: number, height: number }>} + */ +export function mountSlams(arg, doc = document) { + doc.querySelectorAll("[data-post-fx-slams], style[data-post-fx-slams-css]").forEach((el) => el.remove()); + const units = (arg && arg.units) || []; + if (!units.length) return []; + const style = doc.createElement("style"); + style.setAttribute("data-post-fx-slams-css", ""); + style.textContent = arg.css || ""; + doc.head.appendChild(style); + const layer = doc.createElement("div"); + layer.setAttribute("data-post-fx-slams", ""); + doc.body.appendChild(layer); + const dust = (arg && arg.dust) || []; + const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] || c); + return units.map((u) => { + const el = doc.createElement("div"); + el.className = "pslam"; + el.setAttribute("data-post-fx-slam", `${u.i}:${u.k}`); + el.style.fontSize = `${u.size}px`; + el.style.fontFamily = u.face; + for (const [k, v] of Object.entries(u.vars || {})) el.style.setProperty(k, v); + const t = esc(u.text); + el.innerHTML = + `<span class="pslam-flash"></span><span class="pslam-ring"></span>` + + `<span class="pslam-dust">${dust.map((a) => `<i data-a="${a}"></i>`).join("")}</span>` + + `<span class="pslam-g"><span class="pslam-ghost">${t}</span><span class="pslam-ghost">${t}</span><span class="pslam-ghost">${t}</span>` + + `<span class="pslam-back">${t}</span><span class="pslam-front">${t}</span></span>`; + layer.appendChild(el); + const b = el.getBoundingClientRect(); + el.dataset.rw = String(b.width); + el.dataset.rh = String(b.height); + return { i: u.i, k: u.k, width: Math.ceil(b.width), height: Math.ceil(b.height) }; + }); +} + +/** + * Set the slams: `{ list: [{ i, k, x, y, scale, blur, opacity, flash, ring, + * dust, ghost }], shake: { x, y } | null }` -- x, y the unit's centre (px); + * a unit not listed is hidden. `shake` (Play) moves the page's body by that + * many px (the build shakes the frame in ffmpeg instead). + * @param {{ list?: Array<Record<string, any>>, shake?: { x: number, y: number } | null } | null} arg + * @param {Document} [doc] + */ +export function setSlamState(arg, doc = document) { + const list = (arg && arg.list) || []; + const shake = arg && arg.shake; + if (doc.body) doc.body.style.translate = shake && (shake.x || shake.y) ? `${Math.round(shake.x * 10) / 10}px ${Math.round(shake.y * 10) / 10}px` : ""; + const layer = doc.querySelector("[data-post-fx-slams]"); + if (!layer) return; + for (const el of Array.from(layer.querySelectorAll(".pslam"))) { + const id = el.getAttribute("data-post-fx-slam") || ""; + const st = list.find((x) => `${x.i}:${x.k}` === id); + if (!st) { + el.style.opacity = "0"; + continue; + } + const w = Number(el.dataset.rw || 0); + const h = Number(el.dataset.rh || 0); + const size = parseFloat(el.style.fontSize) || 100; + el.style.opacity = String(st.opacity); + el.style.transform = `translate(${Math.round((st.x - w / 2) * 10) / 10}px, ${Math.round((st.y - h / 2) * 10) / 10}px) scale(${st.scale})`; + const g = el.querySelector(".pslam-g"); + // The teaser's blur (px on its title) scaled to this glyph and halved: a motion smear, never a blob. + if (g) g.style.filter = st.blur > 0.2 ? `blur(${Math.round(st.blur * (size / 120) * 0.45 * 10) / 10}px)` : ""; + // The ghosts: bigger copies trailing the shrink (where it came from), gone as it lands. + Array.from(el.querySelectorAll(".pslam-ghost")).forEach((gh, j) => { + gh.style.opacity = String(Math.round(st.ghost * (0.3 / (j + 1)) * 1000) / 1000); + gh.style.transform = `scale(${Math.round((1 + 0.16 * (j + 1) * st.ghost) * 1000) / 1000})`; + }); + // The impact: a flash behind it (it is drawn under the glyph), a ring, the dust thrown up and out. + const fl = el.querySelector(".pslam-flash"); + if (fl) { + fl.style.opacity = String(st.flash); + fl.style.transform = `scale(${Math.round((0.7 + 0.5 * (1 - st.flash)) * 1000) / 1000})`; + } + const ring = el.querySelector(".pslam-ring"); + if (ring) { + ring.style.opacity = st.ring < 0 ? "0" : String(Math.round((1 - st.ring) * 0.9 * st.opacity * 1000) / 1000); + ring.style.transform = `scale(${st.ring < 0 ? 0.4 : Math.round((0.45 + 1.5 * (1 - (1 - st.ring) ** 2)) * 1000) / 1000})`; + } + for (const d of Array.from(el.querySelectorAll(".pslam-dust i"))) { + if (st.dust < 0) { + d.style.opacity = "0"; + continue; + } + const a = (Number(d.getAttribute("data-a")) * Math.PI) / 180; + const p = 1 - (1 - st.dust) ** 2; + const r = size * (0.25 + 0.75 * p); + const fall = size * 0.35 * st.dust * st.dust; + d.style.opacity = String(Math.round((1 - st.dust) * st.opacity * 1000) / 1000); + d.style.transform = `translate(${Math.round(Math.cos(a) * r * 10) / 10}px, ${Math.round((Math.sin(a) * r * 0.55 + fall) * 10) / 10}px) scale(${Math.round((1.4 - st.dust) * 100) / 100})`; + } + } +} + +/** + * The units of a plan at item second `s` as setSlamState takes them: `p` a + * slam (slamPlan's, with `centers` from its layout), `dx`/`dy` how far its + * words have moved since it was placed (a pan). + */ +export function slamListAt(p, s, dx = 0, dy = 0) { + const st = slamStateAt({ span: p.span, fromScale: p.fx.fromScale }, s); + if (!st) return []; + return st.units.map((u) => ({ i: p.i, ...u, x: p.centers[u.k].x + dx, y: p.centers[u.k].y + dy })); +} diff --git a/umtool/report-to-video/post-slam.test.mjs b/umtool/report-to-video/post-slam.test.mjs @@ -0,0 +1,198 @@ +// A post item's SLAM (post-slam.mjs): its validation, its timing (three hits +// spread over the word's spoken span, a phrase's too; --gap; --at), its motion +// (the teaser's slam, from its own scale), its place (above the line, below +// when it would cover the words read), its sound (the teaser's trailer hit, one +// per glyph) and the segment key (an item without a slam keeps its key). +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + SLAM_GAP, SLAM_MOTION, slamHits, slamLandings, slamLayout, slamPlan, slamShakeAt, slamShakeExpr, slamSpan, slamStateAt, slamTimes, slamUnitAt, slamUnits, +} from "./post-slam.mjs"; +import { TEASER_MOTION } from "./deck.mjs"; +import { TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs"; +import { captionPlan } 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 BAJI = "For those wondering, the martial art I'm pursuing is called Baji Quan, need to start."; +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 slam = (o = {}) => ({ kind: "slam", text: "不動心", match: "Fudōshin", ...o }); +const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 10, script: TEXT, ...o }); +// The take's words: "achieved" 3.84–4.24, "Fudōshin." 4.24–5.36 (the proof post's own). +const WORDS = [["I'm", 0.2, 0.4], ["ignoring", 0.4, 0.8], ["my", 0.8, 0.9], ["broken", 0.9, 1.2], ["bones", 1.2, 1.5], ["so", 1.5, 1.6], ["my", 1.6, 1.7], ["training", 1.7, 2.1], ["can", 2.1, 2.3], ["continue.", 2.3, 2.9], ["I", 3.3, 3.4], ["have", 3.4, 3.84], ["achieved", 3.84, 4.24], ["Fudōshin.", 4.24, 5.36], ["Its", 5.7, 5.9], ["amazing.", 5.9, 6.4]].map(([w, start, end]) => ({ w, start, end })); +const narrated = (o = {}) => base({ narration: { script: TEXT, takes: [take({ words: WORDS })], lead: 0.5, rate: 1 }, ...o }); + +test("validation: a slam's keys, text, match, knobs -- in the build's words; a slam is not a word zoom", () => { + assert.deepEqual(validatePostFx(base({ fx: [slam()] })), []); + const errs = validatePostFx(base({ fx: [slam({ match: "Fudoshinn", text: "", place: "left", hold: 9, scale: 2, color: "gold", face: "zh", sfx: "boom", fromScale: 20 })] })); + for (const re of [/fx\[0\]\.scale is not a slam key/, /match "Fudoshinn" is not in the post's words/, /\.text must be the glyphs/, /\.place must be one of over-match, center/, /\.hold must be 0.3–4 seconds/, /\.color must be a colour/, /\.face must be one of jp, sc, tc, kr/, /\.sfx must be one of trailer-hit, off/, /\.fromScale must be 1.5–8/]) { + assert.ok(errs.some((e) => re.test(e)), `${re}\n${errs.join("\n")}`); + } + assert.ok(validatePostFx(base({ fx: [slam({ text: "不".repeat(13) })] })).some((e) => /longer than 12 characters/.test(e))); + // No match: an `at` and the card's middle. + assert.ok(validatePostFx(base({ fx: [slam({ match: undefined })] })).some((e) => /needs its word \(match\) or its second \(at\)/.test(e))); + assert.ok(validatePostFx(base({ fx: [slam({ match: undefined, at: 2 })] })).some((e) => /no word to land over/.test(e))); + assert.deepEqual(validatePostFx(base({ fx: [slam({ match: undefined, at: 2, place: "center" })] })), []); + assert.deepEqual(wordZoomTimes(base({ fx: [slam()] })), [{ i: 0, kind: "slam" }]); +}); + +test("units: one per glyph (whitespace dropped), or the whole text as one", () => { + assert.deepEqual(slamUnits(slam()), ["不", "動", "心"]); + assert.deepEqual(slamUnits(slam({ text: "八极拳" })), ["八", "极", "拳"]); + assert.deepEqual(slamUnits(slam({ text: " 不 動心 " })), ["不", "動", "心"]); + assert.deepEqual(slamUnits(slam({ whole: true })), ["不動心"]); +}); + +test("WHEN: three hits spread evenly over the word's spoken span -- the first on its start, the last on its end, the second midway", () => { + const e = narrated({ fx: [slam()] }); + const [t] = slamTimes(e); + // On the item's clock: the read's lead (0.5) + the take's second. + assert.deepEqual(t, { i: 0, t: 4.74, end: 5.86, source: "words" }); + assert.deepEqual(slamLandings(e.fx[0], t), [4.74, 5.3, 5.86]); + // The read's rate (its schedule's): a take second is 1/rate of the item's. + assert.deepEqual(slamTimes(e, undefined, { at: 0.5, rate: 2 })[0], { i: 0, t: 2.62, end: 3.18, source: "words" }); +}); + +test("WHEN: a two-word phrase spreads over both -- the first hit on Baji's start, the last on Quan's end", () => { + const words = [["For", 0.1, 0.3], ["those", 0.3, 0.6], ["wondering,", 0.6, 1.1], ["the", 1.2, 1.3], ["martial", 1.3, 1.7], ["art", 1.7, 1.9], ["I'm", 1.9, 2.1], ["pursuing", 2.1, 2.5], ["is", 2.5, 2.6], ["called", 2.6, 2.88], ["Baji", 2.88, 3.36], ["Quan,", 3.44, 3.84], ["need", 4.0, 4.2]].map(([w, start, end]) => ({ w, start, end })); + const e = base({ text: BAJI, narration: { script: BAJI, takes: [take({ script: BAJI, words })], lead: 0, rate: 1 }, fx: [slam({ text: "八极拳", match: "Baji Quan", face: "sc" })] }); + assert.deepEqual(validatePostFx(e), []); + const [t] = slamTimes(e); + assert.deepEqual(t, { i: 0, t: 2.88, end: 3.84, source: "words" }); + assert.deepEqual(slamLandings(e.fx[0], t), [2.88, 3.36, 3.84]); +}); + +test("WHEN: --gap overrides the spread; --at moves the first hit (the span kept when the words have one); none: SLAM_GAP apart", () => { + const e = narrated({ fx: [slam({ gap: 0.3 })] }); + assert.deepEqual(slamLandings(e.fx[0], slamTimes(e)[0]), [4.74, 5.04, 5.34]); + const at = narrated({ fx: [slam({ at: 2 })] }); + assert.deepEqual(slamTimes(at)[0], { i: 0, t: 2, end: 3.12, source: "at" }); + const plain = base({ fx: [slam({ match: undefined, at: 1, place: "center" })] }); + assert.deepEqual(slamTimes(plain)[0], { i: 0, t: 1, end: null, source: "at" }); + assert.deepEqual(slamLandings(plain.fx[0], slamTimes(plain)[0]), [1, 1 + SLAM_GAP, 1 + 2 * SLAM_GAP]); + // Un-narrated with a match: the reading estimate's start ("Fudōshin." is word 13: 1 + 13/3). + assert.deepEqual(slamTimes(base({ fx: [slam()] }))[0], { i: 0, t: 5.33, end: null, source: "estimate" }); + // One glyph (whole): one hit, on the start. + assert.deepEqual(slamLandings(slam({ whole: true }), { t: 4, end: 5 }), [4]); +}); + +test("SPAN: in from `hit` before the first landing, held after the last, faded; shortened to the item's end, refused past it", () => { + const sp = slamSpan(slam(), [4, 4.5, 5]); + assert.deepEqual(sp, { t0: 3.8, t2: 6.6, t3: 6.95, landings: [4, 4.5, 5] }); + assert.equal(slamSpan(slam(), [4, 4.5, 5], { end: 6 }).t3, 6); + assert.match(slamSpan(slam(), [4, 4.5, 5], { end: 5 }).error, /lands at 5 s, at or after the item's 5 s/); +}); + +test("MOTION: the teaser's slam (deck.mjs TEASER_MOTION's hit, under, settle, blur), from its own scale -- huge, shrinking onto its spot, landing, settling", () => { + for (const k of ["hit", "under", "settle", "blur"]) assert.equal(SLAM_MOTION[k], TEASER_MOTION[k], k); + assert.equal(slamUnitAt(4, 3.79), null); + const start = slamUnitAt(4, 3.8); + assert.equal(start.scale, 3.5); + assert.equal(start.blur, 18); + assert.equal(start.opacity, 0); + assert.ok(start.ghost > 0.99); + const mid = slamUnitAt(4, 3.9); + assert.ok(mid.scale < 3.5 && mid.scale > 2, String(mid.scale)); + // Lands under its rest size, the flash and the ring and the dust fire. + const land = slamUnitAt(4, 4); + assert.equal(land.scale, SLAM_MOTION.under); + assert.equal(land.flash, 1); + assert.equal(land.ring, 0); + assert.equal(land.ghost, 0); + assert.equal(slamUnitAt(4, 5).scale, 1); + assert.equal(slamUnitAt(4, 5).blur, 0); + assert.equal(slamUnitAt(4, 5).ring, -1); + // The row: glyphs land left to right; before the second's start only the first is in. + const st = slamStateAt({ span: slamSpan(slam(), [4, 4.5, 5]), fromScale: 3.5 }, 4.2); + assert.deepEqual(st.units.map((u) => u.k), [0]); + assert.equal(slamStateAt({ span: slamSpan(slam(), [4, 4.5, 5]), fromScale: 3.5 }, 7), null); +}); + +test("SHAKE: a punch at each landing that dies in its span; the ffmpeg term is the same curve", () => { + assert.deepEqual(slamShakeAt([4], 3.9), { x: 0, y: 0 }); + assert.equal(slamShakeAt([4], 4).y, 0.75); + assert.deepEqual(slamShakeAt([4], 4.4), { x: 0, y: 0 }); + const ex = slamShakeExpr([4, 4.5], "x", 9); + assert.match(ex, /^9\*\(if\(between\(t,4,4\.3\),exp\(-\(t-4\)\/0\.075\)\*sin\(/); + assert.equal(slamShakeExpr([], "x", 9), "0"); +}); + +test("SOUND: one title-tier trailer hit per landing (the teaser's generator), the swell after the last with swell; none with sfx off", () => { + const sp = slamSpan(slam(), [4, 4.5, 5]); + const hits = slamHits(slam(), sp); + assert.deepEqual(hits.map((h) => [h.kind, h.at, h.gain, h.f0]), [["hit", 4, 1, 92], ["hit", 4.5, 1, 92], ["hit", 5, 1, 92]]); + assert.deepEqual({ ...hits[0], kind: undefined, at: undefined, role: undefined }, { ...TRAILER_HIT_TIERS.title, kind: undefined, at: undefined, role: undefined }); + assert.equal(slamHits(slam({ swell: true }), sp).at(-1).kind, "swell"); + assert.deepEqual(slamHits(slam({ sfx: "off" }), sp), []); + const g = trailerHitsGraph(hits, { seconds: 8, rate: 48000, prefix: "sl" }); + assert.match(g, /\[sla\]$/); + assert.match(g, /\[slb\]\[slp\]\[slr\]amix/); + assert.ok(!/\[ta\]/.test(g)); +}); + +test("PLAN: a slam up with a word zoom is refused; a caption up with it waits for it to be gone (the slam first, then the chip)", () => { + const e = narrated({ fx: [{ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin" }, slam()] }); + const [p] = slamPlan(e); + assert.deepEqual(p.span.landings, [4.74, 5.3, 5.86]); + assert.deepEqual(p.units, ["不", "動", "心"]); + // "Its" (word 14) starts 5.7 + 0.5 = 6.2 s, within 0.25 s... of no hit (5.86 is 0.34 s before): not protected; nothing else is near. + assert.deepEqual(p.avoid, []); + const caps = captionPlan(e, undefined, { zooms: [{ t0: p.span.t0, t3: p.span.t3, i: p.i }] }); + assert.equal(caps[0].span.t0, p.span.t3); + assert.equal(caps[0].span.waited, 1); + assert.throws(() => slamPlan(e, undefined, { zooms: [{ t0: 5, t3: 6, i: 0 }] }), /is up while word zoom 1 is/); + assert.throws(() => slamPlan(narrated({ fx: [slam(), slam({ text: "心" })] })), /slams 1 and 2 are up at once/); +}); + +test("WHERE: a row centred on the word just above its line; below when above would leave the frame or cover a word read at a hit; centre on the card", () => { + const word = { x: 400, y: 300, width: 200, height: 40 }; + const card = { x: 100, y: 100, width: 900, height: 800 }; + const bounds = { x: 12, y: 12, width: 1896, height: 1056 }; + const units = [{ width: 120, height: 120 }, { width: 120, height: 120 }, { width: 120, height: 120 }]; + const up = slamLayout({ word, card, bounds, units, gap: 6, protect: [word], obstacles: [{ x: 300, y: 250, width: 400, height: 40 }] }); + assert.equal(up.where, "above"); + assert.deepEqual([up.x, up.y, up.width, up.height], [320, 174, 360, 120]); + assert.deepEqual(up.centers, [{ x: 380, y: 234 }, { x: 500, y: 234 }, { x: 620, y: 234 }]); + // It lies over the line above: the gag, counted. + assert.equal(up.covers, 1); + assert.equal(up.blocked, false); + // Near the frame's top: below its line. + assert.equal(slamLayout({ word: { ...word, y: 60 }, card, bounds, units, gap: 6, protect: [{ ...word, y: 60 }] }).where, "below"); + // A word read at a hit above it: below. + const read = { x: 420, y: 250, width: 80, height: 40 }; + assert.equal(slamLayout({ word, card, bounds, units, gap: 6, protect: [word, read] }).where, "below"); + // Kept in the frame sideways. + assert.equal(slamLayout({ word: { ...word, x: 0, width: 50 }, card, bounds, units, gap: 6 }).x, 12); + const mid = slamLayout({ card, bounds, units, place: "center" }); + assert.deepEqual([mid.where, mid.x, mid.y], ["center", 370, 440]); +}); + +test("THE SEGMENT KEY (post-render.mjs postFxKeyFields): nothing for an item without a slam; a slam adds its drawing version, its motion and its hit", async () => { + const { postFxKeyFields, POST_SLAM_DRAW_V } = await import("./post-render.mjs"); + assert.deepEqual(postFxKeyFields(base(), {}), {}); + assert.deepEqual(postFxKeyFields(base({ fx: [{ kind: "caption", match: "x", text: "y" }] }), {}), { captionV: 2 }); + const k = postFxKeyFields(base({ fx: [slam()] }), {}); + assert.deepEqual(Object.keys(k), ["slam"]); + assert.equal(k.slam.v, POST_SLAM_DRAW_V); + assert.deepEqual(k.slam.hit, TRAILER_HIT_TIERS.title); + assert.deepEqual(k.slam.motion, SLAM_MOTION); +}); + +test("THE ENCODE (postSegmentArgs): the slam's frames laid over everything while up, the frame's punch, the hits mixed into the audio", async () => { + const { postSegmentArgs } = await import("./post-render.mjs"); + const args = (o) => postSegmentArgs({ + entry: base(), box: { width: 1600, height: 900 }, plan: { total: 8, steps: [] }, layout: { mode: "card", slot: null }, cards: { read: "/c/read.png" }, files: [], + render: { fps: 30, audioRate: 48000, palette: { bg: "#101010" } }, outPath: "/o.mp4", ...o, + }); + const plainArgs = args({}); + const fc0 = plainArgs[plainArgs.indexOf("-filter_complex") + 1]; + assert.ok(!/slm|sla|crop=/.test(fc0)); + assert.match(fc0, /anull\[a\]$/); + const a = args({ slams: [{ list: "/c/slam-1/frames.ffconcat", t0: 3.8, t3: 6.95, landings: [4, 4.5, 5] }], slamHitList: slamHits(slam(), slamSpan(slam(), [4, 4.5, 5])) }); + const fc = a[a.indexOf("-filter_complex") + 1]; + assert.match(fc, /\[slm0\]overlay=x=0:y=0:eof_action=pass:enable='between\(t,3\.8,6\.95\)'/); + assert.match(fc, /pad=iw\+\d+:ih\+\d+:\d+:\d+:color=0x101010,crop=1600:900:'\d+\+7\.5\*\(if\(between\(t,4,/); + assert.match(fc, /anull\[apre\]/); + assert.match(fc, /\[apre\]\[sla\]amix=inputs=2:normalize=0:duration=first,alimiter=limit=0\.95/); + assert.ok(a.includes("/c/slam-1/frames.ffconcat")); +}); diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -61,6 +61,11 @@ export async function keepFramesAsked(outRoot) { } const FRAME_RE = /^frame_\d+\.png$/; +/** A sparse sequence's `.sparse` (`{ key, frames, absent }`), or null. */ +async function sparseRecord(dir) { + return readFile(path.join(dir, ".sparse"), "utf8").then((s) => JSON.parse(s), () => null); +} + /** Is this `chrome/` entry one a prune removes? A real directory, named for it. */ export function isPrunable(dirent) { return dirent.isDirectory() && (dirent.name.endsWith("-frames") || dirent.name.startsWith("work-")); @@ -103,9 +108,7 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date(), se let bytes = 0; for (const name of sequences) { const dir = path.join(chromeDir, name); - const files = await readdir(dir).catch(() => []); - const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); - dirs[name] = { frames: files.filter((f) => FRAME_RE.test(f)).length, key }; + dirs[name] = { frames: await framesOf(dir), key: await frameKeyOf(dir) }; } for (const name of [...sequences, ...work]) bytes += await dirBytes(path.join(chromeDir, name)); const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; @@ -174,6 +177,8 @@ async function recorded(dir, since) { */ export async function framesOf(dir, { since = null } = {}) { const files = await readdir(dir).catch(() => null); + // A SPARSE sequence (chunked-encode.mjs SPARSE_FILE) is as long as its record says. + if (files?.includes(".sparse")) return Number((await sparseRecord(dir))?.frames ?? 0); if (files) return files.filter((f) => FRAME_RE.test(f)).length; return Number((await recorded(dir, since))?.frames ?? 0); } @@ -181,6 +186,7 @@ export async function framesOf(dir, { since = null } = {}) { /** A sequence's render key: its `.key`, or the one the prune recorded; null when neither. */ export async function frameKeyOf(dir, { since = null } = {}) { const files = await readdir(dir).catch(() => null); + if (files?.includes(".sparse")) return (await sparseRecord(dir))?.key ?? null; if (files) return readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); return (await recorded(dir, since))?.key ?? null; } diff --git a/umtool/report-to-video/render-pool.mjs b/umtool/report-to-video/render-pool.mjs @@ -0,0 +1,370 @@ +// THE RENDER POOL: a content-addressed cache of built units, shared by every +// take of every project (operator, 4 Nov: "every clip that could be inserted +// into a video is put into a shared cached clip pool by all input params by +// default, kind of like archilyzer videos"). +// +// Each built unit is stored ONCE, under the hash of its kind, its kind's +// renderer salt and the full key the build already computes for it: +// +// post a post item's segment and its record (post-render.mjs +// postSegmentKeyOf: the entry, its plan, the box, the encode, its +// files' stamps, the narration…): `seg.mp4`, `post.json` +// clip a clip (or still) segment and its cut record (segment-cache.mjs +// segmentKey: the ffmpeg argv with every input by its identity): +// `seg.mp4`, `cut.json` +// chunk a chunk of the final encode (chunked-encode.mjs chunkKey: its +// inputs' contents, its graph in its own clock -- position-free): +// `chunk.mp4` +// sound a cut's sound (the hard-cut pins and encode, or the crossfade's +// graph): `sound.m4a` +// frame one chrome frame, by its frame key (frame-keys.mjs: what it +// draws): `<key>.png`, a file of its own +// +// Every build looks in the pool when its own out/ misses, and HARD-LINKS a hit +// into the take; a unit it builds is linked into the pool (through a tmp +// directory renamed into place, so a reader never sees half an object). A +// link, never a copy: the pool costs no disk while a take holds the same +// inode, and a build REPLACES its files (rename), never writes through them, +// so neither side can change the other's bytes. Another filesystem than the +// pool's (EXDEV) is simply no pool. +// +// WHERE: `UMTOOL_RENDER_POOL` (a directory), else `<media root>/.render-pool` +// (UMTOOL_MEDIA_DIR's, else the reports root's) -- for an out/ under that +// root only, so a test's or a scratch copy's build never writes into the +// operator's pool. `UMTOOL_RENDER_POOL=0` turns it off. +// +// DISK: `UMTOOL_RENDER_POOL_MAX_GB` (default 30) caps the bytes ONLY the pool +// holds (a file with one link: no take has it). Over the cap, objects go least +// recently used first (an object's directory -- a frame's shard -- is touched +// on every hit); an object a take still links is never evicted, so neither is +// one a pinned or picked take holds, nor one a running build just made or +// took. `umtool pool stats|prune|verify`. +// +// Hits and misses are appended to `<pool>/events.ndjson` (a line each, an +// atomic append), which `stats` reads. +// +// Plain node; every path is a parameter or the environment. + +import { createHash, randomBytes } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { appendFile, link, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { MEDIA_ROOT } from "../lib/paths.mjs"; + +/** + * The kinds, each with its renderer SALT: bumped when code changes what a + * kind's unit is for unchanged inputs (every object of the kind is then a + * miss once). A kind's own key may carry a salt of its own as well + * (post-render POST_SEGMENT_RV, SEGMENT_KEY_VERSION, CHUNK_KEY_VERSION, + * FRAME_KEY_VERSION): those are in the keys this hashes. + */ +export const POOL_KINDS = Object.freeze({ + post: { salt: 1, noun: "post segments" }, + clip: { salt: 1, noun: "clip segments" }, + chunk: { salt: 1, noun: "final-encode chunks" }, + sound: { salt: 1, noun: "cut sounds" }, + frame: { salt: 1, noun: "chrome frames" }, +}); + +/** The pool's default cap on the bytes only it holds, in GB. */ +export const POOL_MAX_GB_DEFAULT = 30; +const META = "meta.json"; +const EVENTS = "events.ndjson"; +const sha256 = (s) => createHash("sha256").update(s).digest("hex"); + +/** + * The pool for a build whose out dir is `outDir`: a directory, or null (off, + * or an out/ outside the media root with no pool named). + */ +export async function poolFor(outDir, env = process.env) { + const named = env.UMTOOL_RENDER_POOL; + if (named === "0" || named === "off") return null; + if (named) return path.resolve(named); + const root = await realpath(MEDIA_ROOT).catch(() => MEDIA_ROOT); + const out = await realpath(outDir).catch(() => path.resolve(outDir)); + if (!(out === root || out.startsWith(root + path.sep))) return null; + return path.join(root, ".render-pool"); +} + +/** An object's id: its kind, the kind's salt and the build's key, hashed. */ +export function poolId(kind, key) { + const k = POOL_KINDS[kind]; + if (!k) throw new Error(`render pool: no kind ${kind}`); + return sha256(JSON.stringify({ kind, salt: k.salt, key: String(key) })).slice(0, 40); +} + +/** Where an object lives: a directory for a unit, a file for a frame. */ +export function objectPath(pool, kind, key) { + const id = poolId(kind, key); + return kind === "frame" ? path.join(pool, kind, id.slice(0, 2), `${id}.png`) : path.join(pool, kind, id.slice(0, 2), id); +} + +const MADE = new Set(); +async function event(pool, kind, hit) { + if (!MADE.has(pool)) { + await mkdir(pool, { recursive: true }).catch(() => {}); + MADE.add(pool); + } + await appendFile(path.join(pool, EVENTS), JSON.stringify({ at: Date.now(), kind, hit }) + "\n").catch(() => {}); +} + +/** Hard-link `src` at `dst` through a rename (whatever was at `dst` replaced); false when it cannot (EXDEV, gone). */ +async function linkInto(src, dst) { + const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.${randomBytes(3).toString("hex")}.pool`); + try { + await link(src, tmp); + } catch { + return false; + } + await rename(tmp, dst); + return true; +} + +const touch = (p) => utimes(p, new Date(), new Date()).catch(() => {}); + +/** + * A unit from the pool: each of `files` (`{ name: dest }`) hard-linked at its + * dest. True on a hit (every file linked), false on a miss. + */ +export async function poolFetch(pool, kind, key, files) { + if (!pool) return false; + const dir = objectPath(pool, kind, key); + const meta = await readFile(path.join(dir, META), "utf8").then((t) => JSON.parse(t), () => null); + const names = Object.keys(files); + if (!meta || names.some((n) => !meta.files?.[n])) { + await event(pool, kind, false); + return false; + } + for (const n of names) { + if (!(await linkInto(path.join(dir, n), files[n]))) { + await event(pool, kind, false); + return false; + } + } + await touch(dir); + await event(pool, kind, true); + return true; +} + +function fileSha(file) { + return new Promise((resolve, reject) => { + const h = createHash("sha256"); + createReadStream(file).on("error", reject).on("data", (b) => h.update(b)).on("end", () => resolve(h.digest("hex"))); + }); +} + +/** + * A unit into the pool: each of `files` (`{ name: src }`) hard-linked into a + * tmp directory with its `meta.json` (each file's bytes and sha256), renamed + * into place. An object already there is kept. Never throws: a pool that + * cannot take it (another filesystem, a full disk) is no pool. + */ +export async function poolPut(pool, kind, key, files, extra = {}) { + if (!pool) return false; + const dir = objectPath(pool, kind, key); + try { + if ((await stat(path.join(dir, META)).catch(() => null))?.isFile()) return true; + const shard = path.dirname(dir); + await mkdir(shard, { recursive: true }); + const tmp = path.join(path.dirname(shard), `.tmp-${process.pid}-${randomBytes(4).toString("hex")}`); + await mkdir(tmp); + try { + const meta = { kind, key: String(key), salt: POOL_KINDS[kind].salt, at: new Date().toISOString(), files: {}, ...extra }; + for (const [n, src] of Object.entries(files)) { + await link(src, path.join(tmp, n)); + const st = await stat(src); + meta.files[n] = { bytes: st.size, sha256: await fileSha(src) }; + } + await writeFile(path.join(tmp, META), JSON.stringify(meta, null, 1) + "\n", "utf8"); + await rename(tmp, dir).catch(async (e) => { + if (e?.code !== "EEXIST" && e?.code !== "ENOTEMPTY") throw e; + }); + } finally { + await rm(tmp, { recursive: true, force: true }); + } + return true; + } catch { + return false; + } +} + +/** A frame's file in the pool, when it has one (its shard touched), else null. */ +export async function poolFrame(pool, key) { + if (!pool) return null; + const f = objectPath(pool, "frame", key); + if (!(await stat(f).catch(() => null))?.isFile()) return null; + await touch(path.dirname(f)); + return f; +} + +/** Frames into the pool: each `[key, file]` linked in (one already there kept). Returns how many went in. */ +export async function poolPutFrames(pool, pairs) { + if (!pool || !pairs.length) return 0; + let n = 0; + const shards = new Set(); + for (const [key, src] of pairs) { + const f = objectPath(pool, "frame", key); + if (!shards.has(path.dirname(f))) { + await mkdir(path.dirname(f), { recursive: true }).catch(() => {}); + shards.add(path.dirname(f)); + } + if ((await lstat(f).catch(() => null))?.isFile()) continue; + if (await linkInto(src, f).catch(() => false)) n += 1; + } + return n; +} + +/** Record a batch of frame lookups (one line, not one per frame). */ +export async function poolFrameEvents(pool, hits, misses) { + if (!pool || !(hits + misses)) return; + await mkdir(pool, { recursive: true }).catch(() => {}); + await appendFile(path.join(pool, EVENTS), JSON.stringify({ at: Date.now(), kind: "frame", hits, misses }) + "\n").catch(() => {}); +} + +// ---- the pool as a whole: stats, prune, verify ------------------------------- + +/** Every object: `{ kind, path, bytes, onlyPool, used }` (`onlyPool`: the bytes no take links). */ +export async function poolObjects(pool) { + const out = []; + for (const kind of Object.keys(POOL_KINDS)) { + const kdir = path.join(pool, kind); + for (const shard of await readdir(kdir).catch(() => [])) { + if (shard.startsWith(".")) continue; + const sdir = path.join(kdir, shard); + const sst = await stat(sdir).catch(() => null); + if (!sst?.isDirectory()) continue; + for (const name of await readdir(sdir).catch(() => [])) { + const p = path.join(sdir, name); + const st = await lstat(p).catch(() => null); + if (!st) continue; + if (kind === "frame") { + if (!st.isFile()) continue; + out.push({ kind, path: p, bytes: st.size, onlyPool: st.nlink <= 1 ? st.size : 0, linked: st.nlink > 1, used: sst.mtimeMs }); + continue; + } + if (!st.isDirectory()) continue; + let bytes = 0; + let only = 0; + let linked = false; + for (const f of await readdir(p).catch(() => [])) { + const fs = await lstat(path.join(p, f)).catch(() => null); + if (!fs?.isFile()) continue; + bytes += fs.size; + if (f === META || fs.nlink <= 1) only += fs.size; + else linked = true; + } + out.push({ kind, path: p, bytes, onlyPool: linked ? 0 : only, linked, used: st.mtimeMs }); + } + } + } + return out; +} + +/** The cap on the bytes only the pool holds: `UMTOOL_RENDER_POOL_MAX_GB`, else the default. */ +export function poolMaxBytes(env = process.env) { + const gb = Number(env.UMTOOL_RENDER_POOL_MAX_GB); + return (Number.isFinite(gb) && gb >= 0 ? gb : POOL_MAX_GB_DEFAULT) * 1024 ** 3; +} + +/** + * Size, what only the pool holds, hits and misses per kind (from the events, + * `since` ms), the biggest objects. + */ +export async function poolStats(pool, { since = 0, top = 10 } = {}) { + const objs = await poolObjects(pool); + const kinds = {}; + for (const k of Object.keys(POOL_KINDS)) kinds[k] = { objects: 0, bytes: 0, onlyPool: 0, hits: 0, misses: 0 }; + for (const o of objs) { + kinds[o.kind].objects += 1; + kinds[o.kind].bytes += o.bytes; + kinds[o.kind].onlyPool += o.onlyPool; + } + const text = await readFile(path.join(pool, EVENTS), "utf8").catch(() => ""); + for (const line of text.split("\n")) { + if (!line) continue; + let e; + try { + e = JSON.parse(line); + } catch { + continue; + } + if (!kinds[e.kind] || e.at < since) continue; + if (Number.isFinite(e.hits)) { + kinds[e.kind].hits += e.hits; + kinds[e.kind].misses += e.misses ?? 0; + } else if (e.hit) kinds[e.kind].hits += 1; + else kinds[e.kind].misses += 1; + } + const bytes = objs.reduce((n, o) => n + o.bytes, 0); + const onlyPool = objs.reduce((n, o) => n + o.onlyPool, 0); + const biggest = [...objs].sort((a, b) => b.bytes - a.bytes).slice(0, top).map((o) => ({ kind: o.kind, path: o.path, bytes: o.bytes, linked: o.onlyPool === 0 })); + return { pool, objects: objs.length, bytes, onlyPool, maxOnlyPool: poolMaxBytes(), kinds, biggest }; +} + +/** + * Evict least-recently-used objects that no take links until the bytes only + * the pool holds are under `maxBytes`; tmp directories over a day old go too. + * `dryRun` says what would go. + */ +export async function poolPrune(pool, { maxBytes = poolMaxBytes(), dryRun = false } = {}) { + const objs = await poolObjects(pool); + let only = objs.reduce((n, o) => n + o.onlyPool, 0); + const before = only; + const gone = []; + // An object a take links (any file with a second name) is never a candidate. + const free = objs.filter((o) => !o.linked).sort((a, b) => a.used - b.used); + for (const o of free) { + if (only <= maxBytes) break; + if (!dryRun) await rm(o.path, { recursive: true, force: true }); + only -= o.onlyPool; + gone.push({ kind: o.kind, path: o.path, bytes: o.bytes }); + } + for (const kind of Object.keys(POOL_KINDS)) { + for (const name of await readdir(path.join(pool, kind)).catch(() => [])) { + if (!name.startsWith(".tmp-")) continue; + const p = path.join(pool, kind, name); + const st = await stat(p).catch(() => null); + if (st && Date.now() - st.mtimeMs > 86_400_000 && !dryRun) await rm(p, { recursive: true, force: true }); + } + } + return { before, after: only, maxBytes, evicted: gone.length, bytes: gone.reduce((n, o) => n + o.bytes, 0), gone }; +} + +/** + * Check a sample of objects: each unit's files against the sha256 its meta + * recorded, each frame a PNG. Returns the problems (and removes nothing). + */ +export async function poolVerify(pool, { sample = 50, all = false } = {}) { + const objs = await poolObjects(pool); + const pick = all ? objs : [...objs].sort(() => Math.random() - 0.5).slice(0, sample); + const problems = []; + for (const o of pick) { + if (o.kind === "frame") { + const head = await readFile(o.path).then((b) => b.subarray(0, 8).toString("hex"), () => null); + if (head !== "89504e470d0a1a0a") problems.push(`${o.path}: not a PNG`); + continue; + } + const meta = await readFile(path.join(o.path, META), "utf8").then((t) => JSON.parse(t), () => null); + if (!meta) { + problems.push(`${o.path}: no ${META}`); + continue; + } + for (const [n, f] of Object.entries(meta.files ?? {})) { + const got = await fileSha(path.join(o.path, n)).catch(() => null); + if (got !== f.sha256) problems.push(`${o.path}/${n}: ${got ? "its bytes are not the ones put in" : "missing"}`); + } + } + return { checked: pick.length, of: objs.length, problems }; +} + +/** Prune at most once an hour per pool (the end of a build calls this). */ +export async function poolPruneThrottled(pool, env = process.env) { + if (!pool) return null; + const mark = path.join(pool, ".pruned"); + const st = await stat(mark).catch(() => null); + if (st && Date.now() - st.mtimeMs < 3_600_000) return null; + await mkdir(pool, { recursive: true }).catch(() => {}); + await writeFile(mark, new Date().toISOString() + "\n").catch(() => {}); + return poolPrune(pool, { maxBytes: poolMaxBytes(env) }).catch(() => null); +} diff --git a/umtool/report-to-video/render-pool.test.mjs b/umtool/report-to-video/render-pool.test.mjs @@ -0,0 +1,237 @@ +// The render pool (render-pool.mjs): put and fetch by hard link, hits and +// misses, the cap's least-recently-used eviction that never takes a linked +// object, verify, where the pool is -- and the KEYS: every input that changes +// a unit's pixels, sound or timing changes the key the pool files it under +// (each field of a fixture mutated in turn). +// +// Run with: node --test umtool/report-to-video/render-pool.test.mjs +import assert from "node:assert/strict"; +import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + POOL_KINDS, objectPath, poolFetch, poolFor, poolFrame, poolId, poolPrune, poolPut, poolPutFrames, poolStats, poolVerify, +} from "./render-pool.mjs"; + +const tmp = (p) => mkdtempSync(path.join(tmpdir(), p)); + +test("put links a unit in; fetch links it out (the same inode); a miss is a miss; hits and misses counted", async () => { + const dir = tmp("pool-"); + try { + const pool = path.join(dir, "pool"); + const a = path.join(dir, "a"); + mkdirSync(a); + writeFileSync(path.join(a, "seg.mp4"), "picture"); + writeFileSync(path.join(a, "rec.json"), "{}"); + assert.equal(await poolFetch(pool, "clip", "k1", { "seg.mp4": path.join(a, "x.mp4") }), false); + assert.equal(await poolPut(pool, "clip", "k1", { "seg.mp4": path.join(a, "seg.mp4"), "cut.json": path.join(a, "rec.json") }), true); + const b = path.join(dir, "b"); + mkdirSync(b); + writeFileSync(path.join(b, "seg.mp4"), "an older build"); // replaced, through a rename + assert.equal(await poolFetch(pool, "clip", "k1", { "seg.mp4": path.join(b, "seg.mp4"), "cut.json": path.join(b, "cut.json") }), true); + assert.equal(statSync(path.join(b, "seg.mp4")).ino, statSync(path.join(a, "seg.mp4")).ino, "one inode: the pool costs no disk"); + assert.equal(readFileSync(path.join(b, "seg.mp4"), "utf8"), "picture"); + // Another kind, the same key: another object. + assert.notEqual(poolId("post", "k1"), poolId("clip", "k1")); + assert.equal(await poolFetch(pool, "post", "k1", { "seg.mp4": path.join(b, "p.mp4") }), false); + const st = await poolStats(pool); + assert.equal(st.kinds.clip.hits, 1); + assert.equal(st.kinds.clip.misses, 1); + assert.equal(st.kinds.post.misses, 1); + assert.equal(st.kinds.clip.objects, 1); + assert.equal(st.onlyPool, 0, "both takes link it"); + assert.deepEqual((await poolVerify(pool, { all: true })).problems, []); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("frames: one file per frame key, linked; a second put of a key keeps the first", async () => { + const dir = tmp("pool-f-"); + try { + const pool = path.join(dir, "pool"); + const f1 = path.join(dir, "f1.png"); + writeFileSync(f1, Buffer.from("89504e470d0a1a0a00", "hex")); + const f2 = path.join(dir, "f2.png"); + writeFileSync(f2, Buffer.from("89504e470d0a1a0a01", "hex")); + assert.equal(await poolFrame(pool, "fk1"), null); + assert.equal(await poolPutFrames(pool, [["fk1", f1], ["fk1", f2]]), 1); + const got = await poolFrame(pool, "fk1"); + assert.equal(statSync(got).ino, statSync(f1).ino); + assert.deepEqual((await poolVerify(pool, { all: true })).problems, []); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("prune: least recently used first, only what no take links, down to the cap; verify finds changed bytes", async () => { + const dir = tmp("pool-p-"); + try { + const pool = path.join(dir, "pool"); + const src = path.join(dir, "src"); + mkdirSync(src); + const put = async (k, bytes) => { + const f = path.join(src, `${k}.mp4`); + writeFileSync(f, "x".repeat(bytes)); + await poolPut(pool, "chunk", k, { "chunk.mp4": f }); + return f; + }; + const fa = await put("a", 1000); + const fb = await put("b", 1000); + const fc = await put("c", 1000); + // Only the pool holds a and b; c is still linked by a "take". + rmSync(fa); + rmSync(fb); + void fc; + const old = new Date(Date.now() - 3600_000); + utimesSync(objectPath(pool, "chunk", "a"), old, old); // a used longest ago + const dry = await poolPrune(pool, { maxBytes: 1500, dryRun: true }); + assert.equal(dry.evicted, 1); + assert.match(dry.gone[0].path, new RegExp(poolId("chunk", "a"))); + const done = await poolPrune(pool, { maxBytes: 0 }); + assert.equal(done.evicted, 2, "a and b go; c, linked, never"); + assert.ok(existsSync(objectPath(pool, "chunk", "c"))); + // A file changed under the pool: verify says so. + const c = path.join(objectPath(pool, "chunk", "c"), "chunk.mp4"); + rmSync(c); + writeFileSync(c, "y"); + assert.equal((await poolVerify(pool, { all: true })).problems.length, 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("poolFor: the named pool, off with 0, and none for an out/ outside the media root", async () => { + assert.equal(await poolFor("/x/out", { UMTOOL_RENDER_POOL: "/p" }), "/p"); + assert.equal(await poolFor("/x/out", { UMTOOL_RENDER_POOL: "0" }), null); + assert.equal(await poolFor(path.join(tmpdir(), "nowhere"), {}), null, "a test's or a scratch copy's build never writes the operator's pool"); + assert.deepEqual(Object.keys(POOL_KINDS).sort(), ["chunk", "clip", "frame", "post", "sound"]); +}); + +// ---- the keys: every field that changes a unit changes its key ---------------- + +/** Every leaf path of an object: [["a"], ["b", "c"], …]. */ +function leaves(o, at = []) { + if (o === null || typeof o !== "object") return [at]; + const ks = Object.keys(o); + if (!ks.length) return [at]; + return ks.flatMap((k) => leaves(o[k], [...at, k])); +} +function mutate(o, at) { + const c = structuredClone(o); + let p = c; + for (const k of at.slice(0, -1)) p = p[k]; + const k = at[at.length - 1]; + const v = p[k]; + p[k] = typeof v === "number" ? v + 1 : typeof v === "boolean" ? !v : v === null ? "x" : `${v}~`; + return c; +} + +test("post key: every field of the entry, the box, the render's palette, fonts and fps, the encode, the files' stamps", async () => { + const { postSegmentKey, postSegmentKeyOf } = await import("./post-render.mjs"); + const base = { + entry: { + type: "post", id: "p1", post: "a/1", platform: "x", author: "A", handle: "a", date: "2026-10-19T12:00:00Z", text: "words", + media: [{ src: "m.png", type: "image", crop: { top: 0.1 } }], narration: { rate: 1.1, takes: [{ file: "t.wav", lufs: -20 }], pick: 0 }, + hold: 12, follow: { dim: 0.7 }, thread: { dim: 0.5 }, + }, + box: { width: 1600, height: 880 }, + place: ["pad=1920:1080"], + render: { palette: { bg: "#000", fg: "#fff" }, fontRegular: "/f/r.ttf", fontBold: "/f/b.ttf", fps: 30, postNarration: { rate: 1.08, linger: 0.85 } }, + encode: ["-crf", "21", "-preset", "slow"], + stamps: ["/p/m.png:100:1", "/p/t.wav:200:2"], + plan: { narration: { at: 0.25, seconds: 10 }, follow: { blocks: [1] } }, + }; + const key = (f) => postSegmentKey(postSegmentKeyOf({ ...f, take: { file: "t.wav" } })); + const k0 = key(base); + const fields = ["entry", "box", "place", "encode", "stamps", "plan"].flatMap((top) => leaves(base[top]).map((p) => [top, ...p])); + fields.push(["render", "palette", "bg"], ["render", "fontRegular"], ["render", "fontBold"], ["render", "fps"], ["render", "postNarration", "linger"]); + const missed = fields.filter((at) => key(mutate(base, at)) === k0).map((at) => at.join(".")); + assert.deepEqual(missed, [], "a post segment's key covers every input that draws or times it"); + assert.ok(fields.length > 25, `${fields.length} fields mutated`); +}); + +test("chunk key: the segment, the chrome's frames, the overlay's place, the encode settings, the span's length", async () => { + const { chunkVideoArgs } = await import("./build-video.mjs"); + const { chunkKey } = await import("./chunked-encode.mjs"); + const render = { width: 64, height: 36, fps: 30, transition: 0, preset: "slow", crf: 21, audioRate: 48000, audioChannels: 2 }; + const region = { name: "deck", frames: "/c/deck-frames", x: 0, y: 20, width: 64, height: 16 }; + const keyOf = ({ r = render, reg = region, segId = "s1", seqId = "d1", durs = [10, 12], span = { a: 300, b: 660 } } = {}) => { + const starts = [0, durs[0]]; + const proto = chunkVideoArgs({ segments: ["/x/a.mp4", "/x/b.mp4"], durs, starts, span, D: 0, render: r, chrome: { regions: [reg] }, totalFrames: Math.round((durs[0] + durs[1]) * 30), outPath: "" }); + const ids = proto.inputs.map((x) => (x.kind === "seg" ? { seg: segId } : { seq: seqId })); + return chunkKey({ keyArgv: proto.keyArgv, inputs: ids, ffmpeg: "ff" }); + }; + const k0 = keyOf(); + const changed = { + segment: keyOf({ segId: "s2" }), frames: keyOf({ seqId: "d2" }), + crf: keyOf({ r: { ...render, crf: 22 } }), preset: keyOf({ r: { ...render, preset: "medium" } }), fps: keyOf({ r: { ...render, fps: 25 } }), + x: keyOf({ reg: { ...region, x: 2 } }), y: keyOf({ reg: { ...region, y: 2 } }), length: keyOf({ span: { a: 300, b: 650 }, durs: [10, 11.6667] }), + }; + for (const [what, k] of Object.entries(changed)) assert.notEqual(k, k0, `${what} changes the chunk's key`); + // A segment before it grew: the chunk moved, its key the same (position-free). + assert.equal(keyOf({ durs: [11, 12], span: { a: 330, b: 690 } }), k0); +}); + +test("sound key: each segment's length in the cut, its joins, the rate, the channels, the bitrate", async () => { + const { hardCutSoundArgs, withCutEdits } = await import("./build-video.mjs"); + const render = { fps: 30, audioRate: 48000, audioChannels: 2, audioBitrate: "160k" }; + const argv = ({ durs = [10, 12], joins = null, r = render } = {}) => { + const a = hardCutSoundArgs({ durs, joins, render: r }); + return JSON.stringify([a.pin(0, "<in>", "<pin>"), a.pin(1, "<in>", "<pin>"), a.encode("<l>", "<o>")]); + }; + const k0 = argv(); + assert.notEqual(argv({ durs: [10, 12.0333] }), k0); + assert.notEqual(argv({ joins: withCutEdits(null, 2, { mutes: new Map([[0, 3]]) }) }), k0); + assert.notEqual(argv({ r: { ...render, audioRate: 44100 } }), k0); + assert.notEqual(argv({ r: { ...render, audioChannels: 1 } }), k0); + assert.notEqual(argv({ r: { ...render, audioBitrate: "128k" } }), k0); +}); + +test("clip key: its ffmpeg argv, each input file's contents, its cut record, the ffmpeg binary", async () => { + const { segmentKey } = await import("./segment-cache.mjs"); + const dir = tmp("pool-k-"); + try { + const f = path.join(dir, "in.mp4"); + writeFileSync(f, "source"); + const key = (o = {}) => segmentKey({ argv: ["-i", f, "-crf", "21"], record: { id: "c1", snap: 1.2 }, outDir: dir, ffmpeg: "ffmpeg", ...o }); + const k0 = await key(); + assert.notEqual(await key({ argv: ["-i", f, "-crf", "22"] }), k0); + assert.notEqual(await key({ record: { id: "c1", snap: 1.3 } }), k0); + writeFileSync(f, "source2"); + assert.notEqual(await key(), k0, "an input's bytes"); + // Two takes' out dirs: the same key (the out dir is `<out>` in it). + writeFileSync(f, "source"); + const other = tmp("pool-k2-"); + linkSync(f, path.join(other, "in.mp4")); + assert.equal(await segmentKey({ argv: ["-i", f, "-crf", "21"], record: { id: "c1", snap: 1.2 }, outDir: other, ffmpeg: "ffmpeg" }), k0); + rmSync(other, { recursive: true, force: true }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("umtool pool stats|prune|verify --json", async () => { + const { poolCommand } = await import("../lib/report/poolCli.mjs"); + const dir = tmp("pool-cli-"); + try { + const pool = path.join(dir, "pool"); + const f = path.join(dir, "c.mp4"); + writeFileSync(f, "chunk"); + await poolPut(pool, "chunk", "k", { "chunk.mp4": f }); + const out = []; + assert.equal(await poolCommand(["stats", "--pool", pool, "--json"], { log: (l) => out.push(l) }), 0); + assert.equal(JSON.parse(out[0]).kinds.chunk.objects, 1); + out.length = 0; + assert.equal(await poolCommand(["prune", "--pool", pool, "--max-gb", "0", "--dry-run", "--json"], { log: (l) => out.push(l) }), 0); + assert.equal(JSON.parse(out[0]).evicted, 0, "a linked object is never evicted"); + out.length = 0; + assert.equal(await poolCommand(["verify", "--pool", pool, "--all"], { log: (l) => out.push(l) }), 0); + assert.match(out[0], /checked 1 of 1 object\(s\): all as put in/); + assert.equal(await poolCommand(["bogus", "--pool", pool], { log: () => {} }), 2); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/segment-cache.mjs b/umtool/report-to-video/segment-cache.mjs @@ -31,6 +31,8 @@ import { createReadStream } from "node:fs"; import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; +import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; + /** Bumped when what the key covers changes: every segment is rebuilt once. */ export const SEGMENT_KEY_VERSION = 1; /** A file at or under this many bytes is keyed by its contents; above, by real path, size and mtime. */ @@ -159,7 +161,7 @@ async function sameBytes(a, b) { * probe: (file: string) => Promise<number>, * emit?: (ev: string, fields: object) => void, noCache?: boolean, id?: string }} o * `argv` ENDS with the output path (`seg`), as the build always ran it - * @returns {Promise<{ reused: false | "key" | "bytes", key: string, seconds: number }>} + * @returns {Promise<{ reused: false | "key" | "bytes" | "pool", key: string, seconds: number }>} */ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmpeg, exec, probe, emit = () => {}, noCache = false, id = path.basename(seg, ".mp4") }) { if (argv[argv.length - 1] !== seg) throw new Error(`encodeSegmentCached: the argv must end with ${seg}`); @@ -172,11 +174,24 @@ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmp const got = await probe(seg).catch(() => null); if (got != null && Math.abs(got - prev.segSeconds) <= tol) { emit("note", { message: `${id}: segment unchanged (key ${key.slice(0, 12)}) — reused` }); + // (Filed in the render pool when it has not got it: built before it, or linked in by --from.) + await poolPut(await poolFor(outDir), "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }); return { reused: "key", key, seconds: prev.segSeconds }; } emit("note", { message: `${id}: segment key matches but the file probes ${got ?? "unreadable"}s, not ${prev.segSeconds}s — rebuilt` }); } } + // The render pool (render-pool.mjs): the same segment built by any take of any project. + const pool = noCache ? null : await poolFor(outDir); + if (pool && (await poolFetch(pool, "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }))) { + const rec = await readFile(cutRecordOf(seg), "utf8").then(JSON.parse, () => null); + const got = await probe(seg).catch(() => null); + if (rec?.segKey === key && got != null && Math.abs(got - rec.segSeconds) <= tol) { + emit("note", { message: `${id}: segment from the render pool (key ${key.slice(0, 12)})` }); + return { reused: "pool", key, seconds: rec.segSeconds }; + } + emit("note", { message: `${id}: the render pool's segment does not probe as recorded — rebuilt` }); + } const tmp = path.join(path.dirname(seg), `.${path.basename(seg, ".mp4")}.${process.pid}.partial.mp4`); await rm(tmp, { force: true }); try { @@ -191,6 +206,7 @@ export async function encodeSegmentCached({ seg, argv, record, outDir, fps, ffmp await rename(tmp, seg); } await replaceText(cutRecordOf(seg), JSON.stringify({ ...recordForKey(record), segKey: key, segSeconds: seconds }) + "\n"); + if (pool) await poolPut(pool, "clip", key, { "seg.mp4": seg, "cut.json": cutRecordOf(seg) }); return { reused, key, seconds }; } finally { await rm(tmp, { force: true }); diff --git a/umtool/report-to-video/trailer-hits.mjs b/umtool/report-to-video/trailer-hits.mjs @@ -0,0 +1,152 @@ +// TRAILER HITS: the movie-trailer boom the teaser card plays under each pop +// (deck.mjs teaserHits, build-video.mjs teaserAudioGraph -- the ferret-rescue +// finale's), factored out so a post item's SLAM (post-slam.mjs) plays the same +// generator: one hit per glyph, the title tier, and optionally the tail's swell. +// +// Synthesised in ffmpeg, no samples: nothing is downloaded or bundled. The +// teaser's graph is byte for byte what it was before this module (its tests, +// and so the ferret cut's render key, are unchanged); the slam's names its own +// labels (`prefix`) so the graph can sit inside a post segment's. +// +// Plain ESM, no imports: build-video, deck, post-render and the browser (Play's +// live sound, trailerHitSamples) all read it. + +/** + * The hits' tiers (gains relative: the main title is 1): a title's hit is the + * biggest, an overline's and a kicker's a little smaller, a second tier's + * lighter and shorter. `decay` is the boom's time constant, `f0 → f1` its pitch drop. + */ +export const TRAILER_HIT_TIERS = Object.freeze({ + title: Object.freeze({ gain: 1, decay: 0.42, f0: 92, f1: 40 }), + overline: Object.freeze({ gain: 0.72, decay: 0.34, f0: 96, f1: 44 }), + kicker: Object.freeze({ gain: 0.8, decay: 0.36, f0: 94, f1: 42 }), + sub: Object.freeze({ gain: 0.42, decay: 0.16, f0: 120, f1: 64 }), +}); + +/** The tail's swell (a low rise under a slow entrance): its gain, decay and pitch, the duration the caller's. */ +export const TRAILER_SWELL = Object.freeze({ gain: 0.34, decay: 0.7, f0: 46, f1: 62 }); + +/** The sound's level and ceiling: `limit` is −6 dBFS; `level` is set against the ferret cut's loudness (README). */ +export const TRAILER_AUDIO = Object.freeze({ level: 1.4, limit: 0.5 }); + +/** A number for an aevalsrc expression: 6 decimals, no trailing zeros. */ +export const ev6 = (v) => { + const s = (Math.round(Number(v) * 1e6) / 1e6).toFixed(6).replace(/\.?0+$/, ""); + return s === "-0" ? "0" : s; +}; + +/** The hash noise every layer uses (the same whatever else is in the graph), as an expression of the sample `n`. */ +const NOISE = "(2*(sin(n*12.9898+78.233)*43758.5453-floor(sin(n*12.9898+78.233)*43758.5453))-1)"; + +/** + * The hits' sound, as one filtergraph fragment from no inputs to `[<prefix>a]` + * (`prefix` "t": the teaser's `[ta]`, and its inner labels `[tb] [tp] [tr] [tw]`). + * + * A hit is three layers, each summed over every hit in one `aevalsrc` and + * gated to its own span, so each starts on the sample its time names: + * - the boom: a sine whose pitch drops from f0 to f1 (most of the way in + * ~0.4 s), with its octave for body, on an exponential decay (`decay` is + * the time constant; it is inaudible by ~7×) after a 3 ms attack; + * - the punch: a burst of noise (50 ms time constant), band-passed (180 Hz–3.2 kHz); + * - the tail: a low noise decay (low-passed at 260 Hz) under it. + * A swell is the boom's sine rising f0 → f1 under an envelope that peaks + * three quarters of the way through `dur` and settles, with a breath of the + * low noise. A riser (a dip's, under the black) is a sub whose pitch climbs + * f0 → f1 over `dur` and a noise swell -- its own layer, band-passed + * 400 Hz–6.5 kHz, present only when there is a riser -- both rising (the sub + * squared, the noise cubed) to their peak at the first hit and released over + * `decay`. The sum takes a short low-passed echo, then `level`, then a limiter + * at `limit` (no auto-level, latency compensated) so hits that overlap still + * sum cleanly; trimmed and padded to exactly `seconds`. No hits: digital silence. + * + * @param {Array<{ kind: string, at: number, gain: number, decay: number, f0: number, f1: number, dur?: number }>} hits + * @param {{ seconds: number, rate: number, layout?: string, level?: number, limit?: number, prefix?: string }} o + */ +export function trailerHitsGraph(hits, { seconds, rate, layout = "stereo", level = TRAILER_AUDIO.level, limit = TRAILER_AUDIO.limit, prefix = "t" }) { + const p = prefix; + const len = ev6(seconds); + const tail = `atrim=end=${len},apad=whole_dur=${len},asetpts=PTS-STARTPTS[${p}a]`; + if (!hits.length) return `anullsrc=channel_layout=${layout}:sample_rate=${rate},${tail}`; + const noise = NOISE; + const boom = []; + const punch = []; + const rumble = []; + const whoosh = []; + for (const h of hits) { + const a = ev6(h.at); + const u = `(t-${a})`; + const g = ev6(h.gain); + if (h.kind === "riser") { + const D = ev6(h.dur); + const v = `min(${u},${D})`; + const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * h.dur))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`; + const rel = `clip((${ev6(h.dur + h.decay)}-${u})/${ev6(h.decay)},0,1)`; + const span = ev6(h.dur + h.decay); + boom.push(`if(between(t,${a},${a}+${span}),${g}*0.5*pow(${v}/${D},2)*${rel}*sin(2*PI*${phase}),0)`); + whoosh.push(`if(between(t,${a},${a}+${span}),${g}*0.6*pow(${v}/${D},3)*${rel}*${noise},0)`); + continue; + } + if (h.kind === "swell") { + const D = h.dur; + const peak = ev6(D * 0.75); + const v = `min(${u},${ev6(D)})`; + const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * D))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`; + const env = `pow(sin(PI/2*min(1,${u}/${peak})),2)*exp(-max(0,${u}-${peak})/${ev6(h.decay)})`; + const span = ev6(D * 0.75 + h.decay * 7); + boom.push(`if(between(t,${a},${a}+${span}),${g}*0.42*${env}*sin(2*PI*${phase}),0)`); + rumble.push(`if(between(t,${a},${a}+${span}),${g}*0.5*${env}*${noise},0)`); + continue; + } + const k = HIT_PITCH_TAU; + const phase = `(${ev6(h.f1)}*${u}+${ev6((h.f0 - h.f1) * k)}*(1-exp(-${u}/${k})))`; + const span = ev6(h.decay * 7); + boom.push( + `if(between(t,${a},${a}+${span}),${g}*0.3*min(1,${u}/0.003)*exp(-${u}/${ev6(h.decay)})*` + + `(sin(2*PI*${phase})+0.6*exp(-${u}/${ev6(h.decay * 0.6)})*sin(4*PI*${phase})),0)`, + ); + punch.push(`if(between(t,${a},${a}+0.25),${g}*0.5*exp(-${u}/0.05)*${noise},0)`); + rumble.push(`if(between(t,${a},${a}+${ev6(Math.min(2.6, h.decay * 6))}),${g}*0.32*min(1,${u}/0.02)*exp(-${u}/${ev6(h.decay * 1.3)})*${noise},0)`); + } + const src = (terms) => `aevalsrc=exprs='${terms.length ? terms.join("+") : "0"}':s=${rate}:c=${layout}:d=${len}`; + // The riser's layer only when there is one: a teaser without a dip writes the graph it always did. + const w = whoosh.length ? [`${src(whoosh)},highpass=f=400,lowpass=f=6500[${p}w]`] : []; + return [ + `${src(boom)}[${p}b]`, + `${src(punch)},highpass=f=180,lowpass=f=3200[${p}p]`, + `${src(rumble)},lowpass=f=260,lowpass=f=260[${p}r]`, + ...w, + `[${p}b][${p}p][${p}r]${w.length ? `[${p}w]` : ""}amix=inputs=${3 + w.length}:normalize=0,aecho=1:1:90|190:0.18|0.09,lowpass=f=5000,` + + `volume=${ev6(level)},alimiter=limit=${ev6(limit)}:level=0:latency=1:attack=2:release=80,${tail}`, + ].join(";"); +} + +/** The hit's pitch drop's time constant, seconds. */ +export const HIT_PITCH_TAU = 0.13; + +/** + * ONE HIT's raw layers as samples (Play's live sound: the same formulas as + * trailerHitsGraph's `aevalsrc`, which a browser then filters as the graph does + * -- the punch band-passed 180 Hz–3.2 kHz, the rumble low-passed at 260 Hz). + * `{ boom, punch, rumble }`, Float32Arrays of `seconds` at `rate`, from the hit's + * own start (sample 0 is its `at`). + * @param {{ gain: number, decay: number, f0: number, f1: number }} h + * @param {number} rate + */ +export function trailerHitSamples(h, rate = 48000) { + const seconds = Math.min(3, h.decay * 7); + const n = Math.max(1, Math.round(seconds * rate)); + const boom = new Float32Array(n); + const punch = new Float32Array(n); + const rumble = new Float32Array(n); + const k = HIT_PITCH_TAU; + const fr = (x) => x - Math.floor(x); + for (let i = 0; i < n; i += 1) { + const u = i / rate; + const phase = h.f1 * u + (h.f0 - h.f1) * k * (1 - Math.exp(-u / k)); + boom[i] = h.gain * 0.3 * Math.min(1, u / 0.003) * Math.exp(-u / h.decay) * (Math.sin(2 * Math.PI * phase) + 0.6 * Math.exp(-u / (h.decay * 0.6)) * Math.sin(4 * Math.PI * phase)); + const nz = 2 * fr(Math.sin(i * 12.9898 + 78.233) * 43758.5453) - 1; + punch[i] = u <= 0.25 ? h.gain * 0.5 * Math.exp(-u / 0.05) * nz : 0; + rumble[i] = u <= Math.min(2.6, h.decay * 6) ? h.gain * 0.32 * Math.min(1, u / 0.02) * Math.exp(-u / (h.decay * 1.3)) * nz : 0; + } + return { boom, punch, rumble, seconds }; +} diff --git a/umtool/report-to-video/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs @@ -33,10 +33,12 @@ import { cardText, contextText, parentsOf } from "./post-item.mjs"; import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; import { captionErrors } from "./post-caption.mjs"; import { clockErrors } from "./post-clock.mjs"; +import { slamErrors } from "./post-slam.mjs"; // A post's effects: a word zoom, a CAPTION (post-caption.mjs: a chip explaining a phrase as it is read), and its -// CLOCK (post-clock.mjs: the post's time on the card, running from the item before's). -export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock"]); +// CLOCK (post-clock.mjs: the post's time on the card, running from the item before's), and a SLAM (post-slam.mjs: +// a trailer-style title slam of a few glyphs over the word as it is read, one trailer hit per glyph). +export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock", "slam"]); 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" }); @@ -142,6 +144,7 @@ export function validatePostFx(e) { 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)); if (fx.kind === "clock") return errors.push(...clockErrors(e, fx, fw)); + if (fx.kind === "slam") return errors.push(...slamErrors(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;