Archilyzer · Source

archilyzer

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

commit e3e4c75ef597477c43198f8bcef24972d5cdea8d
parent 579d45e4c4f313f4383e3a6f71e102acb3887a7a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 22:48:45 -0500

umtool: narrated post items -- the mix in the build, one layout, the pacing rule, the authors' pictures

A post item may carry `narration` (post-narration.mjs: script, takes as files of the
project under narration/posts/<postId>/, pick, approved, off, and the mix's knobs; a
take may be composed of parts). The build mixes the picked take inside the segment's
audio graph exactly as narr-demo/mix.sh did: the item's own sound split wet/dry, the
wet low-passed at 650 Hz twice at 0.30 under the read, ramped back to clean over
0.8 s, the narrator levelled, compressed and delayed by the lead -- frame-accurate and
the item's true length, so the deck's rail runs on with it.

One layout for every post item (operator, 2 Nov): the card with its full text stays
up the whole item, the attachments beside it played as one sequence like a video --
a video from the first frame, pictures cycling with a crossfade -- never the card
first and a gallery after. The pacing rule: the item is its read (lead + take + tail
+ linger, or the reading time un-narrated); a longer video is cut to it, pictures
share it (at least 1.5 s each); clip=full plays attachments whole.

render.postNarration (the cut's knobs) and posts narrate --import / --list / --script
/ --take (the editor's tts op, waited for) / --pick / --approve / --off / --all
--draft-scripts (the post verbatim, cleaned for pronunciation) / --all --take / --cut;
posts fit (the attachment's best part by a scored scan of its sound, speech and scene
cuts, recorded with why); set-item fit=read[:linger]. Play plays the take and muffles
the attachment live (WebAudio, the same schedule). The deck band no longer pushes the
byline off the frame when two rows of marker labels and the section title crowd it.
The authors' pictures (post-avatars.mjs, from lane/post-threads): postAvatars, posts
avatar / avatars, drawn on the card, a redacted author never.

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

Diffstat:
Mumtool/app/api/report/file/route.ts | 2+-
Mumtool/app/api/report/post-item/route.ts | 5++++-
Mumtool/components/projects/review/PostItemPlayer.tsx | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/manifest.mjs | 226++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/playView.mjs | 6+++---
Aumtool/lib/report/postFit.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postNarration.test.mjs | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postNarrationCli.mjs | 439+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postReel.mjs | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/postsCli.mjs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/timelineCli.mjs | 7+++++++
Mumtool/report-to-video/build-video.mjs | 3+++
Aumtool/report-to-video/deck-band-fit.test.mjs | 38++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 24+++++++++++++++++++++---
Mumtool/report-to-video/lint.mjs | 7+++++++
Mumtool/report-to-video/narrate-via-editor.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/narration-store.mjs | 11+++++++++--
Mumtool/report-to-video/narration.mjs | 5+++--
Mumtool/report-to-video/narration.test.mjs | 2+-
Mumtool/report-to-video/package.json | 3+++
Aumtool/report-to-video/post-avatars.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-item.mjs | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/report-to-video/post-item.test.mjs | 55+++++++++++++++++++++++++++++++++----------------------
Aumtool/report-to-video/post-narration.mjs | 453+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-narration.test.mjs | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mumtool/report-to-video/post-render.test.mjs | 41++++++++++++++++++++++++-----------------
27 files changed, 2577 insertions(+), 126 deletions(-)

diff --git a/umtool/app/api/report/file/route.ts b/umtool/app/api/report/file/route.ts @@ -19,7 +19,7 @@ export async function GET(request: Request) { abs: f.abs, size: f.size, headers: { - "content-type": /\.(m4a|mp3|wav)$/i.test(f.rel) ? "audio/mp4" : "video/mp4", + "content-type": /\.wav$/i.test(f.rel) ? "audio/wav" : /\.mp3$/i.test(f.rel) ? "audio/mpeg" : /\.m4a$/i.test(f.rel) ? "audio/mp4" : "video/mp4", "accept-ranges": "bytes", "cache-control": fresh ? "private, max-age=3600, immutable" : "private, no-store", "x-video-mtime": String(f.mtimeMs), diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -1,6 +1,7 @@ import { readFile, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { postCardHtml } from "umtool-report-to-video/post-item"; +import { avatarUrls } from "umtool-report-to-video/post-avatars"; import { jobState, startJob } from "@/lib/research/case-editor"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs"; @@ -117,8 +118,10 @@ export async function GET(request: Request) { if (!(w >= 160 && w <= 3840 && h >= 90 && h <= 2160)) return new Response("w and h are the footage box, in px", { status: 400 }); const base = `/api/report/post-item?project=${encodeURIComponent(r.project.id)}`; const parentShot = typeof found.item.parentShot === "string" ? `${base}&file=${encodeURIComponent(found.item.parentShot)}` : null; + // The authors' pictures (post-avatars.mjs), served as the project's files. + const avatars = avatarUrls(found.manifest, (src: string) => `${base}&file=${encodeURIComponent(src)}`) as Record<string, string>; const html = postCardHtml(found.item, { - width: w, height: h, + width: w, height: h, avatars, palette: (render.palette ?? {}) as Record<string, string>, fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` }, phase: q.get("phase") === "media" ? "media" : "read", diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item"; +import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration"; // --------------------------------------------------------------------------- // A POST ITEM PLAYED (report-to-video/post-item.mjs; knobs.md, "Play the cut"): @@ -15,10 +16,14 @@ import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-re // drifts. A video's words (its transcript) show at the slot's foot. // --------------------------------------------------------------------------- +/** A narrated item's mix on its clock (post-narration.mjs narrationSchedule). */ +export type NarrationSchedule = { at: number; seconds: number; voiceEnd: number; rampEnd: number; wet: number; lowpassHz: number; duck: boolean; attach?: string; lufs?: number }; + export type PostPlan = { reading: number; total: number; held: number; + narration?: NarrationSchedule; steps: Array<{ kind: string; at: number; @@ -42,8 +47,53 @@ export function postFileUrl(project: string, rel: string) { return `/api/report/post-item?project=${encodeURIComponent(project)}&file=${encodeURIComponent(rel)}`; } +/** A narration take, a file of the project (the "use a file" route). */ +export function takeFileUrl(project: string, rel: string) { + return `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`; +} + +// --------------------------------------------------------------------------- +// THE MUFFLE, LIVE (post-narration.mjs; the render's mix in WebAudio): a +// sound-bearing attachment under a narration goes through two branches -- +// dry, and wet (a low-pass at lowpassHz, twice, as the render's) -- whose +// gains follow the item's clock: wet at `wet` and dry silent under the read, +// a linear ramp back over `ramp`, then clean. One context for the page; an +// element is wired once (createMediaElementSource takes it for good). +// --------------------------------------------------------------------------- + +let audioCtx: AudioContext | null = null; +const wired = new WeakMap<HTMLMediaElement, { wet: GainNode; dry: GainNode; lp: BiquadFilterNode[] }>(); + +function mixGraph(el: HTMLMediaElement, lowpassHz: number) { + const had = wired.get(el); + if (had) { + for (const f of had.lp) f.frequency.value = lowpassHz; + return had; + } + if (typeof window === "undefined" || typeof window.AudioContext === "undefined") return null; + audioCtx ??= new window.AudioContext(); + const ctx = audioCtx; + try { + const src = ctx.createMediaElementSource(el); + const dry = ctx.createGain(); + const wet = ctx.createGain(); + const lp = [ctx.createBiquadFilter(), ctx.createBiquadFilter()]; + for (const f of lp) { + f.type = "lowpass"; + f.frequency.value = lowpassHz; + } + src.connect(dry).connect(ctx.destination); + src.connect(lp[0]).connect(lp[1]).connect(wet).connect(ctx.destination); + const g = { wet, dry, lp }; + wired.set(el, g); + return g; + } catch { + return null; + } +} + function MediaEl({ - project, m, box, b, step, s, playing, inStep, + project, m, box, b, step, s, playing, inStep, mix = null, }: { project: string; m: PostPlan["steps"][number]["items"][number]; @@ -53,8 +103,22 @@ function MediaEl({ s: number; playing: boolean; inStep: boolean; + /** Narrated: its sound muffled under the read, on this schedule. */ + mix?: NarrationSchedule | null; }) { const ref = useRef<HTMLVideoElement | null>(null); + // The muffle follows the clock: the gains set from the item's second, as the render's expressions are. + const muffled = !!mix && mix.duck && step.sound; + useEffect(() => { + const v = ref.current; + if (!v || !muffled || !mix) return; + const g = mixGraph(v, mix.lowpassHz); + if (!g || !audioCtx) return; + if (playing && audioCtx.state === "suspended") void audioCtx.resume().catch(() => {}); + const now = audioCtx.currentTime; + g.wet.gain.setTargetAtTime(wetGainAt(mix, s), now, 0.01); + g.dry.gain.setTargetAtTime(dryGainAt(mix, s), now, 0.01); + }, [muffled, mix, s, playing]); const crop = Array.isArray(m.crop) && m.crop.length === 4 ? m.crop : null; const inner: React.CSSProperties = crop ? { position: "absolute", width: `${100 / crop[2]}%`, height: `${100 / crop[3]}%`, left: `${(-crop[0] / crop[2]) * 100}%`, top: `${(-crop[1] / crop[3]) * 100}%`, maxWidth: "none" } @@ -123,6 +187,27 @@ export default function PostItemPlayer({ }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); + // Narrated (post-narration.mjs): the picked take on the item's clock, from `at`. + const mix = plan.narration ?? null; + const voiceTake = useMemo(() => (mix ? pickedTake(entry) : null), [mix, entry]); + const voice = useRef<HTMLAudioElement | null>(null); + const local = mix ? s - mix.at : -1; + const speaking = !!mix && local >= 0 && local < mix.seconds; + useEffect(() => { + const a = voice.current; + if (!a || !mix) return; + const target = Math.min(Math.max(0, local), Math.max(0, mix.seconds - 0.01)); + const run = playing && speaking; + if (Math.abs(a.currentTime - target) > DRIFT || !run) { + try { + a.currentTime = target; + } catch { + // not seekable yet + } + } + if (run && a.paused) void a.play().catch(() => {}); + if (!run && !a.paused) a.pause(); + }, [mix, local, playing, speaking]); useEffect(() => { const node = wrap.current; if (!node) return; @@ -166,8 +251,17 @@ export default function PostItemPlayer({ data-post-layout={layout.mode} data-post-step={reading ? "read" : current?.kind ?? "held"} data-post-s={String(Math.round(s * 100) / 100)} + data-post-narrated={mix ? "1" : undefined} + data-post-mix-phase={mix ? mixPhaseAt(mix, s) : undefined} + data-post-wet={mix ? String(Math.round(wetGainAt(mix, s) * 100) / 100) : undefined} + data-post-dry={mix ? String(Math.round(dryGainAt(mix, s) * 100) / 100) : undefined} + data-post-narration-playing={mix ? (playing && speaking ? "1" : "0") : undefined} className="pointer-events-none absolute inset-0 overflow-hidden" > + {mix && voiceTake && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <audio ref={voice} src={takeFileUrl(project, voiceTake.file)} preload="auto" data-post-narration-audio={voiceTake.file} /> + )} {scale > 0 && ( <div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}> <iframe @@ -191,7 +285,7 @@ export default function PostItemPlayer({ {shown && layout.slot && (layout.mode === "side" || mediaPhase) && ( <> {stepBoxes(shown, layout.slot).map((b: { x: number; y: number; width: number; height: number }, j: number) => ( - <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} /> + <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={mix} /> ))} {cue && ( <div diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -58,6 +58,8 @@ import { } from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item"; +import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars"; +import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration"; import { parseMuteFrom } from "./playback.mjs"; import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs"; import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources"; @@ -1867,6 +1869,7 @@ function structureErrors(manifest) { ...validateGroups(manifest), // Post items (post-item.mjs): an archived post as an entry of its own. ...validatePostItems(manifest), + ...validatePostAvatars(manifest), ]; } @@ -2324,7 +2327,7 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null * @param {unknown[]} specs * @param {{ token?: string | null, op?: string }} [opts] */ -export async function insertEntries(dir, afterId, specs, { token = null, op = "insert" } = {}) { +export async function insertEntries(dir, afterId, specs, { token = null, op = "insert", avatars = null } = {}) { if (!Array.isArray(specs) || !specs.length) throw new Error("nothing to insert"); return prepAfter(dir, (r) => r.entries.filter((e) => e.type === "clip").map((e) => e.id), structural(dir, op, token, (m) => { let i = afterId === null || afterId === undefined ? m.timeline.length : afterId === "" || afterId === "-" ? 0 : entryIndex(m.timeline, afterId) + 1; @@ -2340,7 +2343,9 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i entries.push(entry); i += 1; } - return { ids: entries.map((e) => e.id), at, entries }; + // The authors' pictures that came with them (postReel.mjs): never over one the project has. + const avatarsSet = avatars ? addArchiveAvatarsIn(m, avatars) : []; + return { ids: entries.map((e) => e.id), at, entries, ...(avatarsSet.length ? { avatars: avatarsSet } : {}) }; }, { snapshotEvery: 0 })); } @@ -2397,6 +2402,223 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { }); } +// ---- the authors' pictures (report-to-video/post-avatars.mjs) -------------- + +/** + * The archive's pictures `avatars` (`{ <handle>: { src, url?, capturedAt? } }`, + * already copied into the project) into `m.postAvatars`, as `source: + * "archive"` -- never over a picture the project has (a manual one, or one + * copied before). Returns the handles set. + * + * @param {Record<string, any>} m + * @param {Record<string, { src: string, url?: string, capturedAt?: string }>} avatars + */ +export function addArchiveAvatarsIn(m, avatars) { + const set = []; + for (const [h, a] of Object.entries(avatars ?? {})) { + if (!isObj(a) || typeof a.src !== "string" || avatarEntryOf(m, h)) continue; + if (!isObj(m.postAvatars)) m.postAvatars = {}; + m.postAvatars[h] = { src: a.src, source: "archive", ...(typeof a.url === "string" ? { url: a.url } : {}), ...(typeof a.capturedAt === "string" ? { capturedAt: a.capturedAt } : {}) }; + set.push(h); + } + return set; +} + +/** + * The archive's pictures into the cut, alone (a posts reel re-run that adds + * no post, `umtool posts avatars`): one structural write; a picture the + * project has is never replaced. + * + * @param {string} dir + * @param {Record<string, { src: string, url?: string, capturedAt?: string }>} avatars + * @param {{ token?: string | null }} [opts] + */ +export async function addArchiveAvatars(dir, avatars, { token = null } = {}) { + return structural(dir, "post-avatars", token, (m) => ({ avatars: addArchiveAvatarsIn(m, avatars) })); +} + +/** + * SET (or clear) ONE AUTHOR's PICTURE (`umtool posts avatar`): `value` + * `{ src, source, url?, capturedAt? }` (its `src` already copied under + * posts-media/_avatars/), or null to clear it. A "manual" picture replaces + * any; an "archive" one never replaces a manual one (`{ kept: true }`). One + * structural write. + * + * @param {string} dir + * @param {string} handle + * @param {{ src: string, source?: string, url?: string, capturedAt?: string } | null} value + * @param {{ token?: string | null }} [opts] + */ +export async function setPostAvatar(dir, handle, value, { token = null } = {}) { + return structural(dir, "post-avatar", token, (m) => { + const had = avatarEntryOf(m, handle); + if (value === null) { + if (!had) throw new Error(`${handle} has no picture in this cut`); + delete m.postAvatars[had[0]]; + if (!Object.keys(m.postAvatars).length) delete m.postAvatars; + return { handle: had[0], cleared: true }; + } + if (!isObj(value) || typeof value.src !== "string" || !value.src.startsWith(`${AVATARS_DIR}/`)) throw new Error(`a picture is a file under ${AVATARS_DIR}/`); + if (had && had[1].source === "manual" && value.source !== "manual") return { handle: had[0], kept: true }; + if (had) delete m.postAvatars[had[0]]; + if (!isObj(m.postAvatars)) m.postAvatars = {}; + const key = String(handle).replace(/^@/, ""); + m.postAvatars[key] = { src: value.src, source: value.source === "archive" ? "archive" : "manual", ...(value.url ? { url: value.url } : {}), ...(value.capturedAt ? { capturedAt: value.capturedAt } : {}) }; + return { handle: key, set: m.postAvatars[key], replaced: had ? had[1].src : null }; + }); +} + +/** The handles a cut's post items draw whose picture the cut does not have yet. */ +export function handlesWithoutAvatar(m, handles) { + return [...new Set(handles.map(handleKey))].filter((h) => h && !avatarEntryOf(m, h)); +} + +// ---- a post item's narration (report-to-video/post-narration.mjs) ---------- + +/** The narration keys a write may set on one post item (post-narration.mjs; knobs.md, "A narrated post item"). */ +export const POST_NARRATION_KNOBS = Object.freeze(["script", "excerpt", "engine", "voice", "speed", "pick", "approved", "off", "lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "window"]); + +/** + * One post item's narration, changed in place (`m` the manifest inside a + * write). `patch`: any of POST_NARRATION_KNOBS (null clears it), `addTake` + * (a take object, appended; it becomes the pick unless `keepPick`), and + * `dropTake` (an index). A new script or a new pick takes the approval away: + * what was approved was that take on those words. Refused in the build's + * words (validatePostItem). + */ +export function postNarrationIn(m, id, patch) { + const i = entryIndex(m.timeline, id); + const e = m.timeline[i]; + if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`); + for (const k of Object.keys(patch)) { + if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake"].join(", ")})`); + } + const before = isObj(e.narration) ? JSON.parse(JSON.stringify(e.narration)) : null; + const n = isObj(e.narration) ? e.narration : { takes: [] }; + if (!Array.isArray(n.takes)) n.takes = []; + for (const k of POST_NARRATION_KNOBS) { + if (!(k in patch)) continue; + const v = patch[k]; + if (v === null || v === undefined || v === false && (k === "excerpt" || k === "approved" || k === "off")) delete n[k]; + else n[k] = typeof v === "number" && k !== "pick" ? round2(v) : typeof v === "string" && k === "script" ? v.trim() : v; + } + if (isObj(patch.addTake)) { + n.takes.push(patch.addTake); + if (patch.keepPick !== true) n.pick = n.takes.length - 1; + } + if (patch.dropTake !== undefined && patch.dropTake !== null) { + const d = Number(patch.dropTake); + if (!Number.isInteger(d) || !n.takes[d]) throw new Error(`${id} has no take ${patch.dropTake}`); + n.takes.splice(d, 1); + const pick = Number.isInteger(n.pick) ? n.pick : 0; + if (!n.takes.length) delete n.pick; + else if (pick === d) n.pick = Math.min(d, n.takes.length - 1); + else if (pick > d) n.pick = pick - 1; + } + // Approval is of a take on its words: a new script or another pick takes it away. + if (before?.approved && !("approved" in patch)) { + const pickOf = (x) => (Number.isInteger(x?.pick) ? x.pick : 0); + if ((before.script ?? "") !== (n.script ?? "") || pickOf(before) !== pickOf(n) || (before.takes?.[pickOf(before)]?.file !== n.takes?.[pickOf(n)]?.file)) delete n.approved; + } + e.narration = n; + const errors = validatePostItem(e); + if (errors.length) throw new StructureRefused(errors); + return { id, at: i, entry: e, narration: n }; +} + +/** + * SET A POST ITEM's NARRATION (`umtool posts narrate`, the post bench): one + * structural write (one undo point) -- the script, a take added or dropped, + * the pick, the approval, off, and the mix's knobs for this post. + * + * @param {string} dir + * @param {string} id + * @param {Record<string, any>} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostNarration(dir, id, patch, { token = null } = {}) { + if (!isObj(patch) || !Object.keys(patch).length) throw new Error("a narration patch is an object of knobs"); + return structural(dir, "post-narration", token, (m) => postNarrationIn(m, id, patch)); +} + +/** + * SEVERAL POSTS' NARRATION IN ONE WRITE (`posts narrate --import`, `--all + * --draft-scripts`): `patches` `[{ id, patch }]`, each as updatePostNarration + * takes it; one undo point, refused whole. + * + * @param {string} dir + * @param {Array<{ id: string, patch: Record<string, any> }>} patches + * @param {{ token?: string | null, op?: string }} [opts] + */ +export async function updatePostNarrations(dir, patches, { token = null, op = "post-narration" } = {}) { + if (!Array.isArray(patches) || !patches.length) throw new Error("nothing to change"); + return structural(dir, op, token, (m) => ({ ids: patches.map((p) => postNarrationIn(m, p.id, p.patch).id) })); +} + +/** + * FIT NARRATED POSTS' ATTACHMENTS TO THEIR READ (`umtool posts fit`, the + * bench's "Re-pick best"; lib/report/postFit.mjs): `fits` `[{ id, media: + * { <i>: { start, end } }, window, linger? }]` -- each attachment's span, the + * record of why, and (when asked) the post's linger -- in ONE write. + * + * @param {string} dir + * @param {Array<{ id: string, media: Record<string, { start: number|null, end: number|null }>, window: Record<string, any>, linger?: number|null }>} fits + * @param {{ token?: string | null }} [opts] + */ +export async function fitPostItems(dir, fits, { token = null } = {}) { + if (!Array.isArray(fits) || !fits.length) throw new Error("nothing to fit"); + return structural(dir, "posts-fit", token, (m) => { + const ids = []; + for (const f of fits) { + const i = entryIndex(m.timeline, f.id); + const e = m.timeline[i]; + if (e?.type !== "post") throw new Error(`${f.id} is not a post item`); + for (const [key, mp] of Object.entries(f.media ?? {})) { + const md = e.media?.[Number(key)]; + if (!md) throw new Error(`${f.id} has no attachment ${key}`); + for (const k of ["start", "end"]) { + if (mp[k] === null || mp[k] === undefined) delete md[k]; + else md[k] = round2(mp[k]); + } + if (md.start === 0) delete md.start; + } + postNarrationIn(m, f.id, { window: f.window ?? null, ...(f.linger !== undefined ? { linger: f.linger } : {}) }); + ids.push(f.id); + } + return { ids }; + }); +} + +/** The cut's mix knobs a write may set (`render.postNarration`). */ +export const POST_NARRATION_RENDER_KNOBS = Object.freeze(Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach")); + +/** + * SET THE CUT's NARRATION MIX (`render.postNarration`; `umtool posts narrate + * <p> --cut k=v …`): each key one of POST_NARRATION_RENDER_KNOBS, null back to + * the default. Validated with the build's check. + * + * @param {string} dir + * @param {Record<string, any>} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostNarrationRender(dir, patch, { token = null } = {}) { + if (!isObj(patch) || !Object.keys(patch).length) throw new Error("nothing to set"); + for (const k of Object.keys(patch)) if (!POST_NARRATION_RENDER_KNOBS.includes(k)) throw new Error(`${k} is not a knob of the cut's narration mix (${POST_NARRATION_RENDER_KNOBS.join(", ")})`); + return structural(dir, "post-narration-mix", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const r = isObj(m.render.postNarration) ? m.render.postNarration : {}; + for (const [k, v] of Object.entries(patch)) { + if (v === null || v === undefined) delete r[k]; + else r[k] = typeof v === "number" ? round2(v) : v; + } + if (Object.keys(r).length) m.render.postNarration = r; + else delete m.render.postNarration; + const errors = validatePostNarrationRender(m.render); + if (errors.length) throw new StructureRefused(errors); + return { postNarration: m.render.postNarration ?? null }; + }); +} + // ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) ----------- /** diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -36,7 +36,7 @@ export function headingOf(e) { * plays when, and the day for the reel strip's tint. Its files are served by * /api/report/post-item, which serves only what a post item names. */ -export function postPlayEntry(e) { +export function postPlayEntry(e, render = undefined) { 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(); @@ -50,7 +50,7 @@ export function postPlayEntry(e) { date: day || null, quote: words || null, post: e, - postPlan: postItemPlan(e), + postPlan: postItemPlan(e, render), }; } @@ -105,7 +105,7 @@ export async function playView(project, { take = null, bare = false } = {}) { const cache = await projectCache(project, manifest); const entries = await Promise.all( timeline.map(async (e) => { - if (e.type === "post") return postPlayEntry(e); + if (e.type === "post") return postPlayEntry(e, render); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); const dateKey = clipDateKey(e); diff --git a/umtool/lib/report/postFit.mjs b/umtool/lib/report/postFit.mjs @@ -0,0 +1,218 @@ +// THE BEST PART OF AN ATTACHMENT (`umtool posts fit`, the post bench's +// "Re-pick best"; report-to-video/post-narration.mjs `clip: "read"`). +// Operator, 2 Nov: "read out every post, and not linger too long after +// finishing the read. Clipping away some attachment runtime is preferable to +// sitting through a long video after a short post, but we'll want to pick +// the best part of the attachment to keep even if it's not necessarily just +// truncated off the end." +// +// A narrated post plays for lead + its read + tail + linger; a video +// attachment longer than that is cut to a WINDOW of that length, and this +// picks the window: a scored scan of the attachment -- +// +// loudness its sound's RMS per 0.1 s (decoded by ffmpeg), on its own range: +// the window's mean and its peak (laughter, a shout, the music's hit) +// speech with a transcript of it (`media[i].words`), the share of the +// window that is speech +// activity its scene cuts (ffmpeg scdet, scenesCli's scan) inside the window +// +// -- the window's start snapped to a pause (a silence, detectSilence's, or a +// quiet frame) or a scene cut near it, never past the file. The winner is +// recorded on the entry (`narration.window`: {media, start, end, score, +// reason, at}) so the bench can say why. PURE scoring (scoreWindows) and an +// async scan (scanAttachment) around it. +import { spawn } from "node:child_process"; +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { detectSilence } from "umtool-report-to-video/cut-points"; +import { isNarrated, postNarrationKnobs, readSpanSeconds } from "umtool-report-to-video/post-narration"; +import { parseSceneLog } from "./scenesCli.mjs"; + +/** The scan's frame: 0.1 s. */ +export const FIT_HOP = 0.1; +/** Candidate windows start this often. */ +export const FIT_STEP = 0.25; +/** How far an edge may move to land on a pause or a cut. */ +export const FIT_SNAP = 0.75; +/** The weights of the score's parts. */ +export const FIT_WEIGHTS = Object.freeze({ mean: 1, peak: 0.6, speech: 0.8, cuts: 0.25, early: 0.05 }); + +const r2 = (v) => Math.round(v * 100) / 100; +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** RMS per hop of mono float samples at `rate`. */ +export function rmsFrames(samples, rate, hop = FIT_HOP) { + const n = Math.max(1, Math.round(rate * hop)); + const out = []; + for (let i = 0; i < samples.length; i += n) { + let acc = 0; + const z = Math.min(samples.length, i + n); + for (let j = i; j < z; j += 1) acc += samples[j] * samples[j]; + out.push(Math.sqrt(acc / Math.max(1, z - i))); + } + return out; +} + +/** RMS as dB, floored at -80. */ +const db = (x) => (x > 1e-4 ? 20 * Math.log10(x) : -80); + +/** + * SCORE EVERY WINDOW of length `L` over a file of `duration` seconds and pick + * the best, PURE: `rms` per `hop` seconds, `cuts` scene cuts (seconds), + * `pauses` quiet seconds an edge may snap to, `cues` its transcript (or none). + * + * @returns {{ start: number, end: number, score: number, reason: string, parts: Record<string, number> } | null} + */ +export function scoreWindows({ rms, hop = FIT_HOP, duration, L, cuts = [], pauses = [], cues = null, step = FIT_STEP, weights = FIT_WEIGHTS }) { + if (!(duration > 0) || !(L > 0)) return null; + if (L >= duration - 0.05) return { start: 0, end: r3(duration), score: 0, reason: "the whole attachment fits the read", parts: {} }; + const dbs = rms.map(db); + const hear = dbs.filter((d) => d > -80); + const lo = hear.length ? Math.min(...hear) : -80; + const hi = hear.length ? Math.max(...hear) : -80; + const norm = (d) => (hi - lo > 1 ? Math.max(0, (d - lo) / (hi - lo)) : 0); + const at = (t) => Math.min(dbs.length - 1, Math.max(0, Math.floor(t / hop))); + const speechIn = (a, b) => { + if (!cues?.length) return 0; + let s = 0; + for (const c of cues) s += Math.max(0, Math.min(b, c.end) - Math.max(a, c.start)); + return Math.min(1, s / (b - a)); + }; + let best = null; + for (let a = 0; a + L <= duration + 1e-6; a += step) { + const b = a + L; + let sum = 0; + let peak = 0; + let n = 0; + for (let i = at(a); i <= at(b - hop / 2); i += 1) { + const v = norm(dbs[i]); + sum += v; + peak = Math.max(peak, v); + n += 1; + } + const mean = n ? sum / n : 0; + const speech = speechIn(a, b); + const cutsIn = cuts.filter((c) => c > a + 0.2 && c < b - 0.2).length; + const parts = { mean, peak, speech, cuts: Math.min(1, cutsIn / Math.max(1, L / 4)), early: -a / duration }; + const score = weights.mean * parts.mean + weights.peak * parts.peak + weights.speech * parts.speech + weights.cuts * parts.cuts + weights.early * parts.early; + if (!best || score > best.score + 1e-9) best = { a, score, parts, cutsIn, speech }; + } + if (!best) return null; + // The start snapped to the nearest pause or cut within FIT_SNAP (kept inside the file). + const marks = [...pauses.map((t) => ({ t, what: "a pause" })), ...cuts.map((t) => ({ t, what: "a scene cut" }))] + .filter((m) => Math.abs(m.t - best.a) <= FIT_SNAP && m.t >= 0 && m.t + L <= duration + 1e-6) + .sort((x, y) => Math.abs(x.t - best.a) - Math.abs(y.t - best.a)); + const snap = marks[0] ?? null; + const start = r2(snap ? snap.t : best.a); + const meanDb = (() => { + let s = 0; + let n = 0; + for (let i = at(start); i <= at(start + L - hop / 2); i += 1) { + s += dbs[i]; + n += 1; + } + return n ? s / n : -80; + })(); + const fileDb = dbs.length ? dbs.reduce((x, y) => x + y, 0) / dbs.length : -80; + const why = [ + start < 0.3 ? "from the start" : `from ${start.toFixed(1)} s`, + `its sound ${meanDb.toFixed(0)} dB (the file ${fileDb.toFixed(0)} dB), peak ${Math.round(best.parts.peak * 100)}% of its range`, + ...(cues?.length ? [`speech ${Math.round(best.speech * 100)}%`] : []), + ...(best.cutsIn ? [`${best.cutsIn} scene cut${best.cutsIn === 1 ? "" : "s"}`] : []), + ...(snap ? [`start on ${snap.what}`] : []), + ]; + return { start, end: r2(start + L), score: r3(best.score), reason: why.join("; "), parts: Object.fromEntries(Object.entries(best.parts).map(([k, v]) => [k, r3(v)])) }; +} + +function run(cmd, args, { binary = false } = {}) { + return new Promise((resolve, reject) => { + const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); + const chunks = []; + let log = ""; + child.stdout.on("data", (d) => chunks.push(d)); + child.stderr.on("data", (d) => { + log += d; + }); + child.on("error", (e) => reject(new Error(`${cmd} did not start: ${e.message}`))); + child.on("exit", (code) => (code === 0 ? resolve({ out: binary ? Buffer.concat(chunks) : Buffer.concat(chunks).toString("utf8"), log }) : reject(new Error(`${cmd} exited ${code}: ${log.trim().split("\n").slice(-2).join(" / ")}`)))); + }); +} + +/** A file's sound as mono floats at 8 kHz (empty when it has none). */ +export async function decodeMono(file, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", rate = 8000 } = {}) { + try { + const { out } = await run(ffmpeg, ["-nostdin", "-v", "error", "-i", file, "-vn", "-ac", "1", "-ar", String(rate), "-f", "f32le", "-"], { binary: true }); + const buf = /** @type {Buffer} */ (out); + return { samples: new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)), rate }; + } catch { + return { samples: new Float32Array(0), rate }; + } +} + +/** Its scene cuts (seconds), by ffmpeg's scdet. */ +export async function sceneCuts(file, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", threshold = 8 } = {}) { + try { + const { log } = await run(ffmpeg, ["-hide_banner", "-nostdin", "-nostats", "-loglevel", "info", "-i", file, "-an", "-sn", "-dn", "-vf", `scale=-2:240,scdet=threshold=${threshold}`, "-f", "null", "-"]); + return parseSceneLog(log).cuts.map((c) => c.t); + } catch { + return []; + } +} + +/** + * SCAN ONE ATTACHMENT for its best `L` seconds: decode its sound, find its + * cuts and pauses, read its transcript when it has one, score. + * + * @param {string} file absolute + * @param {{ duration: number, L: number, wordsFile?: string | null, ffmpeg?: string }} o + */ +export async function scanAttachment(file, { duration, L, wordsFile = null, ffmpeg = undefined }) { + const { samples, rate } = await decodeMono(file, ffmpeg ? { ffmpeg } : {}); + const rms = rmsFrames(samples, rate); + const cuts = await sceneCuts(file, ffmpeg ? { ffmpeg } : {}); + const silences = samples.length ? await detectSilence(file, { silenceMinDur: 0.2 }, null, ffmpeg ? { ffmpeg } : {}).catch(() => []) : []; + const pauses = silences.map((x) => (x.s + x.e) / 2); + let cues = null; + if (wordsFile) { + try { + const doc = JSON.parse(await readFile(wordsFile, "utf8")); + cues = (Array.isArray(doc?.cues) ? doc.cues : []).filter((c) => Number.isFinite(c?.start) && Number.isFinite(c?.end)); + } catch { + cues = null; + } + } + return scoreWindows({ rms, duration, L, cuts, pauses, cues }); +} + +/** + * THE FIT of one narrated post item, not written: for its first video + * attachment longer than the read's span, the best window of that length + * (`media` patch + the `window` record); null when there is nothing to fit + * (not narrated, `clip: "full"`, no video, or one no longer than the read). + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} render + * @param {string} projectDir + * @param {{ linger?: number | null, scan?: typeof scanAttachment }} [o] + */ +export async function fitPostItem(entry, render, projectDir, { linger = null, scan = scanAttachment } = {}) { + if (!isNarrated(entry)) return null; + const k = postNarrationKnobs(entry, render); + if (k.clip === "full" || k.attach === "after") return null; + const media = Array.isArray(entry.media) ? entry.media : []; + const i = media.findIndex((m) => m?.kind === "video"); + if (i < 0) return null; + const m = media[i]; + const span = readSpanSeconds(entry, render); + const L = r2(span - k.linger + (linger ?? k.linger)); + const duration = Number(m.seconds); + if (!(duration > L + 0.05)) return { i, L, duration, untouched: true }; + const file = path.join(projectDir, ...String(m.src).split("/")); + const wordsFile = typeof m.words === "string" ? path.join(projectDir, ...m.words.split("/")) : null; + const w = await scan(file, { duration, L, wordsFile }); + if (!w) return null; + return { + i, L, duration, window: { media: i, start: w.start, end: w.end, score: w.score, reason: w.reason, at: new Date().toISOString() }, + media: { [i]: { start: w.start > 0 ? w.start : null, end: w.end } }, + }; +} diff --git a/umtool/lib/report/postNarration.test.mjs b/umtool/lib/report/postNarration.test.mjs @@ -0,0 +1,223 @@ +// A narrated post item's writers and CLI (postNarrationCli.mjs, manifest.mjs +// updatePostNarration / updatePostNarrations / fitPostItems), the best-part +// scan (postFit.mjs), and the authors' pictures (posts avatar / avatars). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postsCommand } from "./postsCli.mjs"; +import { importPatches, makeTake, mixPatchOf } from "./postNarrationCli.mjs"; +import { fitPostItem, rmsFrames, scanAttachment, scoreWindows } from "./postFit.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; +import { postItemPlan } from "umtool-report-to-video/post-item"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-narration-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const CH = path.join(ROOT, "channels"); +const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]); +/** A take: `secs` of a tone. */ +const wav = (f, secs) => ff(["-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]); +/** A video whose sound is quiet but for a loud burst from 6 to 8 s (of 12). */ +const burst = (f) => + ff(["-f", "lavfi", "-i", "testsrc=s=96x64:d=12", "-f", "lavfi", "-i", "sine=f=440:d=12", "-filter_complex", "[1:a]volume='if(between(t,6,8),1,0.02)':eval=frame[a]", "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-c:a", "aac", "-shortest", f]); + +const item = (id, o = {}) => ({ + type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", + text: `@someone post ${id} & more w/ plan(s)`, ...o, +}); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-x", channelsDir: CH }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, + timeline, + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; +}; + +test("--import reads narration/posts/index.json into the cut in ONE write; a re-run adds only new takes", async () => { + const p = await project("imp", [item("1"), item("2"), item("3")]); + for (const id of ["1", "2"]) { + await mkdir(path.join(p.dir, "narration", "posts", id), { recursive: true }); + wav(path.join(p.dir, "narration", "posts", id, "take-1.orpheus-zac.wav"), 1.5); + } + const rows = [ + { id: "1", entry: "p-1", script: "post one", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1.5 }], pick: 0 }, + { id: "2", entry: "p-2", script: "post two", takes: [{ file: "narration/posts/2/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1.5 }], pick: 0 }, + { id: "9", entry: "p-9", script: "gone", takes: [] }, + ]; + await writeFile(path.join(p.dir, "narration", "posts", "index.json"), JSON.stringify(rows)); + const r = await cli(["narrate", "imp", "--import"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /imported 2 take\(s\) into 2 post item\(s\)/); + assert.match(r.out, /1 row\(s\) name no post item of the cut: p-9/); + const m = await manifest(p); + const one = m.timeline[0].narration; + assert.equal(one.script, "post one"); + assert.equal(one.pick, 0); + assert.equal(one.takes[0].engine, "orpheus"); + assert.ok(Math.abs(one.takes[0].seconds - 1.5) < 0.05); + assert.ok(Number.isFinite(one.takes[0].lufs)); + assert.equal(m.timeline[2].narration, undefined); + const revs = await readdir(path.join(p.dir, "revisions")); + assert.equal(revs.filter((f) => f.includes("post-narration-import")).length, 1); + assert.match((await cli(["narrate", "imp", "--import"])).out, /nothing new to import/); + // The plan reads it: narrated, the read and the linger. + assert.equal(postItemPlan(m.timeline[0]).total, Math.round((0.4 + one.takes[0].seconds + 0.3 + 1.8) * 1000) / 1000); +}); + +test("importPatches merges by file: a take already there is kept, a new one appended, the pick only for a new item", async () => { + const m = { timeline: [item("1", { narration: { script: "mine", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 2 }], pick: 0 } })] }; + const { patches, takes } = await importPatches(m, [{ id: "1", script: "theirs", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav" }, { file: "narration/posts/1/take-2.orpheus-zac.wav" }], pick: 1 }], async () => ({ seconds: 3, lufs: -20 })); + assert.equal(takes, 1); + assert.deepEqual(patches.map((x) => Object.keys(x.patch)), [["addTake", "keepPick"]]); +}); + +test("the writers: the script, a take (picked), the pick and the approval -- a new script or pick takes the approval away", async () => { + const p = await project("w", [item("1")]); + await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); + const take = (n) => ({ file: `narration/posts/1/take-${n}.orpheus-zac.wav`, engine: "orpheus", voice: "zac", seconds: 2 + n, script: "s", at: "2026-11-02T00:00:00Z" }); + await updatePostNarration(p.dir, "p-1", { script: "first words", addTake: take(1) }); + await updatePostNarration(p.dir, "p-1", { addTake: take(2) }); + let n = (await manifest(p)).timeline[0].narration; + assert.equal(n.pick, 1); + assert.match((await cli(["narrate", "w", "p-1", "--pick", "1"])).out, /▶ #1/); + assert.equal((await cli(["narrate", "w", "p-1", "--approve"])).code, 0); + assert.equal((await manifest(p)).timeline[0].narration.approved, true); + await cli(["narrate", "w", "p-1", "--script", "new words <sigh>"]); + n = (await manifest(p)).timeline[0].narration; + assert.equal(n.script, "new words <sigh>"); + assert.equal(n.approved, undefined); + await cli(["narrate", "w", "p-1", "--approve"]); + await cli(["narrate", "w", "p-1", "--pick", "2"]); + assert.equal((await manifest(p)).timeline[0].narration.approved, undefined); + // Refused in the build's words, nothing written. + const bad = await cli(["narrate", "w", "p-1", "--script", "hi <whisper>"]); + assert.equal(bad.code, 1); + assert.match(bad.err, /<whisper> is not an expressive tag/); + // The mix's knobs, and off. + assert.equal((await cli(["narrate", "w", "p-1", "wet=0.2", "short=loop", "attach=after", "linger=3"])).code, 0); + n = (await manifest(p)).timeline[0].narration; + assert.deepEqual([n.wet, n.short, n.attach, n.linger], [0.2, "loop", "after", 3]); + await cli(["narrate", "w", "p-1", "--off"]); + assert.equal((await manifest(p)).timeline[0].narration.off, true); + await cli(["narrate", "w", "p-1", "--on"]); + assert.equal((await manifest(p)).timeline[0].narration.off, undefined); + assert.deepEqual(mixPatchOf(["fit=read:2"]), { linger: 2, clip: null }); + // The cut's mix. + assert.equal((await cli(["narrate", "w", "--cut", "wet=0.25", "clip=full"])).code, 0); + assert.deepEqual((await manifest(p)).render.postNarration, { wet: 0.25, clip: "full" }); +}); + +test("--all --draft-scripts: every post's words verbatim (cleaned to be spoken), in one write", async () => { + const p = await project("d", [item("1"), item("2", { text: "x ".repeat(120) })]); + const r = await cli(["narrate", "d", "--all", "--draft-scripts"]); + assert.equal(r.code, 0, r.err); + const m = await manifest(p); + assert.equal(m.timeline[0].narration.script, "post 1 and more with plans"); + assert.equal(m.timeline[1].narration.script.split(" ").length, 120); + assert.match((await cli(["narrate", "d", "--all", "--draft-scripts"])).out, /nothing to draft/); +}); + +test("a take with direction: asked of the editor (stubbed), written into the project's layout, appended and picked with its note", async () => { + const p = await project("t", [item("1", { narration: { script: "read me" } })]); + const asked = []; + const ask = async (body) => { + asked.push(body); + wav(body.out, 1.2); + return { jobId: "job-1", result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1.2 } }; + }; + const m = await manifest(p); + const r = await makeTake(p, m.timeline[0], { note: "angrier, a sigh first", script: "<sigh> read me", ask }); + assert.equal(asked[0].engine, "orpheus"); + assert.equal(asked[0].voice, "zac"); + assert.equal(asked[0].text, "<sigh> read me"); + assert.ok(asked[0].out.endsWith(path.join("narration", "posts", "1", "take-1.orpheus-zac.wav"))); + assert.equal(r.take.note, "angrier, a sigh first"); + const n = (await manifest(p)).timeline[0].narration; + assert.equal(n.script, "<sigh> read me"); + assert.equal(n.takes.length, 1); + assert.equal(n.pick, 0); + assert.equal(n.takes[0].jobId, "job-1"); + const r2 = await makeTake(p, (await manifest(p)).timeline[0], { ask }); + assert.equal(r2.take.file, "narration/posts/1/take-2.orpheus-zac.wav"); +}); + +test("THE BEST PART: the scorer prefers a loud burst in the middle over the start, and snaps to a cut near it", () => { + const rms = Array.from({ length: 120 }, (_, i) => (i >= 60 && i < 80 ? 0.5 : 0.01)); + const w = scoreWindows({ rms, duration: 12, L: 3 }); + assert.ok(w.start >= 5 && w.start <= 6.5, JSON.stringify(w)); + assert.match(w.reason, /dB/); + const snapped = scoreWindows({ rms, duration: 12, L: 3, cuts: [5.5] }); + assert.equal(snapped.start, 5.5); + assert.match(snapped.reason, /start on a scene cut/); + // Flat: the start wins (the early bias). + assert.equal(scoreWindows({ rms: Array(120).fill(0.1), duration: 12, L: 3 }).start, 0); + assert.equal(scoreWindows({ rms, duration: 2, L: 3 }).reason, "the whole attachment fits the read"); + assert.deepEqual(rmsFrames(new Float32Array([1, 1, 0, 0]), 20, 0.1), [1, 0]); +}); + +test("the scan of a real file: the burst wins; posts fit writes the window and why, in one write", async () => { + const p = await project("f", [item("1", { media: [{ src: "posts-media/subj-x/1/1_1.mp4", kind: "video", seconds: 12, width: 96, height: 64, audio: true }] })]); + await mkdir(path.join(p.dir, "posts-media", "subj-x", "1"), { recursive: true }); + burst(path.join(p.dir, "posts-media", "subj-x", "1", "1_1.mp4")); + const w = await scanAttachment(path.join(p.dir, "posts-media", "subj-x", "1", "1_1.mp4"), { duration: 12, L: 3.5 }); + assert.ok(w.start >= 4.4 && w.start <= 6.3, JSON.stringify(w)); + await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); + wav(path.join(p.dir, "narration", "posts", "1", "take-1.orpheus-zac.wav"), 1); + await updatePostNarration(p.dir, "p-1", { script: "x", addTake: { file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 1, engine: "orpheus", voice: "zac" } }, { token: await manifestToken(p.dir) }); + const before = postItemPlan((await manifest(p)).timeline[0]).total; + assert.equal(before, 3.5); + const fit = await fitPostItem((await manifest(p)).timeline[0], {}, p.dir); + assert.equal(fit.L, 3.5); + const r = await cli(["fit", "f", "--all"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /p-1 {2}3\.5 s -> 3\.5 s {2}window/); + const e = (await manifest(p)).timeline[0]; + assert.ok(e.media[0].start >= 4.4, JSON.stringify(e.media[0])); + assert.equal(e.narration.window.media, 0); + assert.ok(e.narration.window.reason.length > 10); + const plan = postItemPlan(e); + assert.equal(plan.steps[0].srcFrom, e.media[0].start); + assert.equal(plan.total, 3.5); + // set-item fit=read:<linger>: the same, on one item, with its linger. + assert.equal((await cli(["set-item", "f", "p-1", "fit=read:3"])).code, 0); + const e2 = (await manifest(p)).timeline[0]; + assert.equal(e2.narration.linger, 3); + assert.equal(postItemPlan(e2).total, 4.7); +}); + +test("the authors' pictures: posts avatar sets one (copied in), posts avatars copies the archive's", async () => { + const p = await project("av", [item("1", { post: "subj-x/1", parents: [{ id: "0", author: "Org", handle: "BigOrg", badge: "gold", text: "hi" }] })]); + const pic = path.join(ROOT, "pic.png"); + ff(["-f", "lavfi", "-i", "color=c=blue:s=32x32", "-frames:v", "1", pic]); + assert.equal((await cli(["avatar", "av", "Subject", pic])).code, 0); + let m = await manifest(p); + assert.deepEqual(m.postAvatars.Subject, { src: "posts-media/_avatars/Subject-manual.png", source: "manual" }); + const store = path.join(CH, "subj-x", "posts-media", "_avatars"); + await mkdir(store, { recursive: true }); + ff(["-f", "lavfi", "-i", "color=c=green:s=32x32", "-frames:v", "1", path.join(store, "BigOrg.png")]); + ff(["-f", "lavfi", "-i", "color=c=green:s=32x32", "-frames:v", "1", path.join(store, "subject.png")]); + await writeFile(path.join(store, "avatars.json"), JSON.stringify({ BigOrg: { file: "BigOrg.png", url: "https://pbs.twimg.com/x.png", capturedAt: "2026-11-02T00:00:00Z" }, subject: { file: "subject.png" } })); + const r = await cli(["avatars", "av"]); + assert.equal(r.code, 0, r.err); + m = await manifest(p); + assert.equal(m.postAvatars.BigOrg.source, "archive"); + assert.equal(m.postAvatars.BigOrg.src, "posts-media/_avatars/BigOrg.png"); + // The manual one is never replaced. + assert.equal(m.postAvatars.Subject.source, "manual"); + assert.equal((await cli(["avatar", "av", "BigOrg", "off"])).code, 0); + assert.equal((await manifest(p)).postAvatars.BigOrg, undefined); +}); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -0,0 +1,439 @@ +// `umtool posts narrate` (report-to-video/post-narration.mjs; umtool/docs/ +// report-video.md, "Narrated post items"): a post item's narration -- its +// script, its takes (synthesized by the EDITOR's tts op, never here), the +// one that plays, its approval, and the mix's knobs -- through the writers +// (updatePostNarration, updatePostNarrations, updatePostNarrationRender). +// +// umtool posts narrate <p> --import [--dry-run] narration/posts/index.json into the cut (one write) +// umtool posts narrate <p> --list every post item's script, takes and pick +// umtool posts narrate <p> <item> one item's +// umtool posts narrate <p> <item> --script "…" set (replace) the script +// umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"] +// a new take, asked of the editor (a job; waits) +// umtool posts narrate <p> <item> --pick <n> | --approve | --unapprove | --off | --on +// umtool posts narrate <p> <item> k=v … this post's mix: lead tail ramp linger clip wet lowpass duck short attach lufs +// umtool posts narrate <p> --all --draft-scripts [--force] scripts from the posts' words (verbatim) +// umtool posts narrate <p> --all --take [--limit N] every missing take, one at a time (resumable) +// umtool posts narrate <p> --cut k=v … the cut's mix (render.postNarration) +// +// Plain ESM: the CLI runs under bare node. +import { execFile } from "node:child_process"; +import { mkdir, readFile, readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { + NARRATION_INDEX, draftScript, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takesDirOf, +} from "umtool-report-to-video/post-narration"; +import { postItemPlan } from "umtool-report-to-video/post-item"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration, updatePostNarrationRender, updatePostNarrations } from "./manifest.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; + +export const NARRATE_USAGE = [ + "usage: umtool posts narrate <project> --import [--dry-run] [--json]", + " umtool posts narrate <project> --list [--json]", + " umtool posts narrate <project> <item> [--script \"…\"] [--take [--note \"…\"] [--voice v] [--engine e] [--speed s]]", + " [--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=…] [--json]", + " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", + " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… engine=… voice=…", + " A NARRATED POST ITEM: its script read by a stock synthetic voice, its attachment playing under the read (muffled,", + " then clean). Takes are files of the project (narration/posts/<postId>/take-<n>.<engine>-<voice>.wav) the EDITOR", + " writes (`pnpm ops tts`, a job on its tts queue; ARCHILYZER_EDITOR_URL + WORKER_TOKEN) -- umtool never synthesizes.", + " --import reads narration/posts/index.json ([{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]).", + " <item>: the post item's id or its post's id. --pick <n>: the take's number as --list shows it (1 = the first).", + " A new take is picked; a new script or pick takes the approval away. Scripts are the post VERBATIM (cleaned", + " for pronunciation only); add emotion with Orpheus's tags <sigh> <laugh> <chuckle> <groan> <gasp> ….", + " A narrated post lasts lead + its read + tail + linger (1.8 s); a longer video is cut to that -- its best part,", + " once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.", +].join("\n"); + +export class NarrateError extends Error {} + +const ON = new Set(["on", "true", "yes", "1"]); +const OFF = new Set(["off", "false", "no", "0", "none"]); + +/** A take's length (ffprobe) and loudness (ffmpeg ebur128), measured when it comes in. */ +export async function measureTake(file) { + const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file]); + const seconds = Number(String(stdout).trim()); + let lufs = null; + try { + const { stderr } = await execFileP(FFMPEG(), ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], { maxBuffer: 1 << 24 }); + const all = [...String(stderr).matchAll(/\bI:\s+(-?[\d.]+|-inf)\s+LUFS/g)]; + const v = all.length ? Number(all.at(-1)[1]) : NaN; + lufs = Number.isFinite(v) && v > -70 ? Math.round(v * 10) / 10 : null; + } catch { + lufs = null; + } + return { seconds: Number.isFinite(seconds) ? Math.round(seconds * 1000) / 1000 : null, lufs }; +} + +/** The post item `ref` names: its id, its post's id, or `p-<postId>`. */ +export function findPostItem(manifest, ref) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const r = String(ref ?? ""); + return tl.find((e) => e?.type === "post" && (e.id === r || postIdOf(e) === r || e.id === `p-${r}`)) ?? null; +} + +/** + * `--import`'s patches from the index's rows (pure but for `measure`): each + * row's takes merged into the item's by file (a take already there kept as + * it is), the script set when the item has none, the pick set when the item + * had no takes. Rows naming no post item of the cut come back in `missing`. + * + * @param {Record<string, any>} manifest + * @param {Array<Record<string, any>>} rows + * @param {(rel: string) => Promise<{ seconds: number|null, lufs: number|null, at?: string|null }>} measure + */ +export async function importPatches(manifest, rows, measure) { + const patches = []; + const missing = []; + let takes = 0; + for (const row of rows) { + const e = findPostItem(manifest, row?.entry) ?? findPostItem(manifest, row?.id); + if (!e) { + missing.push(String(row?.entry ?? row?.id ?? "?")); + continue; + } + const had = Array.isArray(e.narration?.takes) ? e.narration.takes : []; + const files = new Set(had.map((t) => t?.file)); + const add = []; + for (const t of Array.isArray(row.takes) ? row.takes : []) { + if (typeof t?.file !== "string" || files.has(t.file)) continue; + const m = await measure(t.file); + add.push({ + file: t.file, + engine: t.engine ?? "orpheus", + voice: t.voice ?? "zac", + seconds: Number.isFinite(m.seconds) ? m.seconds : Number(t.seconds), + script: typeof t.script === "string" ? t.script : String(row.script ?? ""), + at: typeof t.at === "string" ? t.at : m.at ?? new Date().toISOString(), + ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), + ...(typeof t.note === "string" ? { note: t.note } : {}), + // A take composed of parts (a long post, paragraph by paragraph): the row's, else take-<n>.parts.json beside it. + ...(() => { + const parts = normalizeParts(Array.isArray(t.parts) ? t.parts : m.parts); + return parts ? { parts } : {}; + })(), + }); + files.add(t.file); + } + const patch = {}; + if (typeof row.script === "string" && !(typeof e.narration?.script === "string" && e.narration.script)) patch.script = row.script; + // Each new take goes in; the row's pick holds only for an item that had none. + if (!add.length && !Object.keys(patch).length) continue; + const list = []; + if (patch.script !== undefined) list.push({ script: patch.script }); + for (const t of add) list.push({ addTake: t, keepPick: true }); + const total = had.length + add.length; + if (!had.length && total) list.push({ pick: Number.isInteger(row.pick) && row.pick >= 0 && row.pick < total ? row.pick : 0 }); + for (const p of list) patches.push({ id: e.id, patch: p }); + takes += add.length; + } + return { patches, missing, takes }; +} + +const fmtKnob = (k, v) => `${k}=${typeof v === "boolean" ? (v ? "on" : "off") : v}`; + +/** + * A take's PARTS as the batch writes them (`take-<n>.parts.json`: a list, or + * `{ parts: [...] }`), each `{ n, para, text, file, start, seconds, gapBefore }` + * -- only those keys, numbers rounded; null when there are none. + */ +export function normalizeParts(raw) { + const list = Array.isArray(raw) ? raw : Array.isArray(raw?.parts) ? raw.parts : null; + if (!list?.length) return null; + const r3 = (v) => Math.round(Number(v) * 1000) / 1000; + return list + .filter((p) => p && typeof p === "object" && Number.isFinite(Number(p.start)) && Number(p.seconds) > 0) + .map((p, k) => ({ + n: Number.isInteger(p.n) ? p.n : k + 1, + ...(Number.isInteger(p.para) ? { para: p.para } : {}), + ...(typeof p.text === "string" ? { text: p.text } : {}), + ...(typeof p.file === "string" ? { file: p.file } : {}), + start: r3(p.start), + seconds: r3(p.seconds), + ...(Number.isFinite(Number(p.gapBefore)) ? { gapBefore: r3(p.gapBefore) } : {}), + })); +} + +/** `take-<n>.parts.json` for a take file `narration/posts/<id>/take-<n>.<engine>-<voice>.wav`. */ +export const partsFileOf = (rel) => String(rel).replace(/(take-\d+)(?:-[a-z]+)?\.[^/]*\.wav$/, "$1.parts.json"); + +/** One item's narration as lines. */ +export function narrationLines(e, render) { + const n = e.narration ?? {}; + const t = pickedTake(e); + const plan = postItemPlan(e, render); + const lines = [ + `${e.id} ${isNarrated(e) ? "NARRATED" : n.off ? "narration off" : "not narrated"}${n.approved ? " · approved" : ""} ${plan.total.toFixed(2)} s`, + ` script: ${n.script ? JSON.stringify(n.script) : "(none)"}`, + ]; + (n.takes ?? []).forEach((tk, i) => { + lines.push(` ${t?.index === i ? "▶" : " "} #${i + 1} ${tk.file} ${Number(tk.seconds).toFixed(2)} s ${tk.engine ?? "?"} · ${tk.voice ?? "?"}${tk.parts?.length ? ` ${tk.parts.length} parts` : ""}${tk.note ? ` note: ${tk.note}` : ""}${tk.script && tk.script !== n.script ? " (an older script)" : ""}`); + }); + if (plan.narration) { + const k = postNarrationKnobs(e, render); + lines.push(` mix: ${["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs"].map((x) => fmtKnob(x, k[x])).join(" ")}`); + if (n.window) lines.push(` window: attachment ${n.window.media + 1} ${n.window.start}–${n.window.end} s (score ${n.window.score}): ${n.window.reason}`); + lines.push(` plays: voice ${plan.narration.at}–${(plan.narration.at + plan.narration.seconds).toFixed(2)} s, muffled to ${plan.narration.voiceEnd} s, clean from ${plan.narration.rampEnd} s; attachments ${plan.steps.map((s) => `${s.kind} ${s.at}+${s.seconds}`).join(", ") || "none"}${plan.held ? `, held ${plan.held} s` : ""}`); + } + return lines; +} + +/** `k=v` words as a narration patch (the post's mix, or with `cut` the cut's). */ +export function mixPatchOf(pairs, { cut = false } = {}) { + const out = {}; + for (const pair of pairs) { + const eq = pair.indexOf("="); + if (eq < 1) throw new NarrateError(`${pair}: a knob is key=value`); + const k = pair.slice(0, eq); + const raw = pair.slice(eq + 1); + const v = raw.toLowerCase(); + const clear = v === "" || v === "default"; + const num = () => { + const x = Number(raw); + if (!Number.isFinite(x)) throw new NarrateError(`${k}= takes a number`); + return x; + }; + if (["lead", "tail", "ramp", "linger", "wet", "lufs"].includes(k)) out[k] = clear ? null : num(); + else if (k === "clip") out.clip = clear ? null : v; + else if (k === "lowpass" || k === "lowpassHz") out.lowpassHz = clear ? null : num(); + else if (k === "duck") out.duck = clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("duck= takes on or off"); })(); + else if (k === "short") out.short = clear ? null : v; + else if (k === "attach" && !cut) out.attach = clear ? null : v; + else if ((k === "engine" || k === "voice") && cut) out[k] = clear ? null : raw; + else if (k === "fit" && !cut) { + // fit=read[:linger]: the item ends `linger` after the words (posts fit picks the clip's best part for it). + const m = /^read(?::([\d.]+))?$/.exec(v); + if (!m) throw new NarrateError("fit= takes read or read:<linger seconds>"); + out.linger = m[1] !== undefined ? Number(m[1]) : null; + out.clip = null; + } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, engine, voice" : "linger, clip, attach, lufs, fit"})`); + } + if (!Object.keys(out).length) throw new NarrateError("nothing to set"); + return out; +} + +/** + * Ask the editor for one take of `e` and keep it: the next take-<n> file in + * the project, measured, appended (and picked) through the writer. Returns + * the take and the write's result. + */ +export async function makeTake(project, e, { script = null, note = null, engine = null, voice = null, speed = null, render = {}, emit = () => {}, editor = null, ask = null } = {}) { + const k = postNarrationKnobs(e, render); + const words = String(script ?? e.narration?.script ?? "").trim(); + if (!words) throw new NarrateError(`${e.id} has no script to read (--script "…", or --all --draft-scripts)`); + const eng = engine ?? e.narration?.engine ?? k.engine; + const vox = voice ?? e.narration?.voice ?? k.voice; + const spd = speed ?? e.narration?.speed ?? null; + const pid = postIdOf(e); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const onDisk = await readdir(dir).catch(() => []); + const n = nextTakeNumber(e, onDisk); + const rel = takeFileOf(pid, n, eng, vox); + const out = path.join(project.dir, ...rel.split("/")); + const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts; + const body = { text: words, engine: eng, voice: vox, out, ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}) }; + const { jobId, result } = await askTts(body, { ...(editor ? { editor } : {}), emit }); + if (!(await stat(out).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there (its result names ${result?.wav ?? "no file"})`); + const m = await measureTake(out); + const take = { + file: rel, engine: result?.engine ?? eng, voice: result?.voice ?? vox, seconds: m.seconds ?? Number(result?.seconds), + script: words, at: new Date().toISOString(), ...(note ? { note } : {}), ...(spd !== null && eng !== "orpheus" ? { speed: spd } : {}), + ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), jobId, + }; + const patch = { addTake: take, ...(script !== null && script !== e.narration?.script ? { script: words } : {}) }; + const { result: wrote, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); + return { take, result: wrote, editNotes }; +} + +/** `umtool posts narrate …` (postsCli.mjs routes it here). */ +export async function narrateCommand(project, words, flags, { json = false, dryRun = false, out = (s) => console.log(s), str }) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new NarrateError(`${project.id} has no manifest`); + const render = manifest.render ?? {}; + const tl = (manifest.timeline ?? []).filter((e) => e?.type === "post"); + const pairs = words.filter((w) => /^[A-Za-z]+=/.test(w)); + const ref = words.find((w) => !/^[A-Za-z]+=/.test(w)) ?? null; + const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir))); + + if (flags.has("--import")) { + const idxFile = path.join(project.dir, ...NARRATION_INDEX.split("/")); + let rows; + try { + rows = JSON.parse(await readFile(idxFile, "utf8")); + } catch (e) { + throw new NarrateError(`no readable ${NARRATION_INDEX} in ${project.id}: ${e instanceof Error ? e.message : e}`); + } + if (!Array.isArray(rows)) throw new NarrateError(`${NARRATION_INDEX} must be a list of [{id, entry, script, takes, pick}]`); + const measure = async (rel) => { + const abs = path.join(project.dir, ...String(rel).split("/")); + const st = await stat(abs).catch(() => null); + if (!st?.isFile()) throw new NarrateError(`${rel} (named in ${NARRATION_INDEX}) is not in the project`); + const parts = await readFile(path.join(project.dir, ...partsFileOf(rel).split("/")), "utf8").then((t) => JSON.parse(t), () => null); + return { ...(await measureTake(abs)), at: new Date(st.mtimeMs).toISOString(), parts }; + }; + const { patches, missing, takes } = await importPatches(manifest, rows, measure); + const items = new Set(patches.map((p) => p.id)).size; + if (dryRun || !patches.length) { + if (json) out(JSON.stringify({ ok: true, dryRun, items, takes, missing, patches }, null, 2)); + else out(`${dryRun ? "would import" : "nothing new to import:"} ${takes} take(s) into ${items} post item(s)${missing.length ? `; ${missing.length} row(s) name no post item of the cut: ${missing.join(", ")}` : ""}`); + return 0; + } + const { result, editNotes } = await write((token) => updatePostNarrations(project.dir, patches, { token, op: "post-narration-import" })); + if (json) out(JSON.stringify({ ok: true, items, takes, missing, snapshot: result.snapshot, token: result.token, editNotes }, null, 2)); + else { + out(`imported ${takes} take(s) into ${items} post item(s) from ${NARRATION_INDEX}${missing.length ? `; ${missing.length} row(s) name no post item of the cut: ${missing.join(", ")}` : ""}`); + if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel} (umtool timeline ${project.id} undo)`); + } + return 0; + } + + if (flags.has("--cut")) { + const patch = mixPatchOf(pairs, { cut: true }); + const { result } = await write((token) => updatePostNarrationRender(project.dir, patch, { token })); + out(json ? JSON.stringify({ ok: true, postNarration: result.postNarration, token: result.token }, null, 2) : `the cut's narration mix: ${JSON.stringify(result.postNarration ?? "the defaults")}`); + return 0; + } + + if (flags.has("--list") || (!ref && !flags.has("--all"))) { + if (json) out(JSON.stringify({ ok: true, items: tl.map((e) => ({ id: e.id, narrated: isNarrated(e), narration: e.narration ?? null, seconds: postItemPlan(e, render).total })) }, null, 2)); + else { + const narrated = tl.filter(isNarrated).length; + out(`${project.id}: ${tl.length} post item(s), ${narrated} narrated, ${tl.filter((e) => e.narration?.approved).length} approved`); + for (const e of tl) out(narrationLines(e, render).join("\n")); + } + return 0; + } + + if (flags.has("--all")) { + if (flags.has("--draft-scripts")) { + const force = flags.has("--force"); + const patches = []; + for (const e of tl) { + if (!force && typeof e.narration?.script === "string" && e.narration.script) continue; + const d = draftScript(e.text); + if (!d.script) continue; + patches.push({ id: e.id, patch: { script: d.script, excerpt: null } }); + } + if (dryRun || !patches.length) { + out(json ? JSON.stringify({ ok: true, dryRun, patches }, null, 2) : `${dryRun ? "would draft" : "nothing to draft:"} ${patches.length} script(s)${patches.length ? "" : " (every post item has one; --force redrafts them)"}`); + return 0; + } + const { result } = await write((token) => updatePostNarrations(project.dir, patches, { token, op: "post-narration-scripts" })); + out(json ? JSON.stringify({ ok: true, drafted: patches.length, snapshot: result.snapshot }, null, 2) : `drafted ${patches.length} script(s) from the posts' words (verbatim); undo point: ${result.snapshot?.rel ?? "-"}`); + return 0; + } + if (flags.has("--take")) { + const limitRaw = str("--limit"); + const limit = limitRaw === null ? Infinity : Number(limitRaw); + const todo = tl.filter((e) => e.narration?.script && !(e.narration.takes ?? []).length); + out(`${todo.length} post item(s) have a script and no take${Number.isFinite(limit) ? ` (doing ${Math.min(limit, todo.length)})` : ""}`); + let made = 0; + for (const e0 of todo.slice(0, Number.isFinite(limit) ? limit : undefined)) { + // Read again: a take made since (an earlier run, another hand) is not made twice. + const now = findPostItem(await readManifest(project.dir), e0.id); + if (!now || (now.narration?.takes ?? []).length) continue; + out(`${now.id}: asking the editor…`); + const { take } = await makeTake(project, now, { render, emit: (_ev, f) => f?.message && out(f.message) }); + out(` ${take.file} ${take.seconds} s`); + made += 1; + } + out(`made ${made} take(s)`); + return 0; + } + throw new NarrateError("--all goes with --draft-scripts or --take"); + } + + const e = findPostItem(manifest, ref); + if (!e) throw new NarrateError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + if (flags.has("--take")) { + const speedRaw = str("--speed"); + const r = await makeTake(project, e, { + script: str("--script"), note: str("--note"), engine: str("--engine"), voice: str("--voice"), + speed: speedRaw === null ? null : Number(speedRaw), render, emit: (_ev, f) => !json && f?.message && out(f.message), + }); + if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, narration: r.result.narration, token: r.result.token }, null, 2)); + else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), picked${r.take.note ? ` — note: ${r.take.note}` : ""}`); + return 0; + } + const patch = pairs.length ? mixPatchOf(pairs) : {}; + const script = str("--script"); + if (script !== null) patch.script = script; + const pickRaw = str("--pick"); + if (pickRaw !== null) { + const n = Number(pickRaw); + if (!Number.isInteger(n) || n < 1) throw new NarrateError("--pick takes a take's number as --list shows it (1 = the first)"); + patch.pick = n - 1; + } + if (flags.has("--approve")) patch.approved = true; + if (flags.has("--unapprove")) patch.approved = null; + if (flags.has("--off")) patch.off = true; + if (flags.has("--on")) patch.off = null; + if (!Object.keys(patch).length) { + out(json ? JSON.stringify({ ok: true, id: e.id, narration: e.narration ?? null, plan: postItemPlan(e, render) }, null, 2) : narrationLines(e, render).join("\n")); + return 0; + } + const { result } = await write((token) => updatePostNarration(project.dir, e.id, patch, { token })); + if (json) out(JSON.stringify({ ok: true, id: e.id, narration: result.narration, token: result.token }, null, 2)); + else out(narrationLines(result.entry, render).join("\n")); + return 0; +} + +export const FIT_USAGE = [ + "usage: umtool posts fit <project> [--all | <item> …] [--linger <s>] [--dry-run] [--json]", + " NARRATED POSTS, NO LINGERING: each post read in full, then over `linger` (1.8 s) after the words; a video", + " attachment longer than that is cut to its BEST PART of that length -- a scored scan of its sound (loudness,", + " its peaks), its speech (when transcribed) and its scene cuts, the start snapped to a pause or a cut -- recorded", + " with why (narration.window). One undoable write; each post's old and new length and the window printed.", + " --linger <s> sets those posts' own linger too. A video no longer than the read is left as it is.", +].join("\n"); + +/** `umtool posts fit` (lib/report/postFit.mjs). */ +export async function fitCommand(project, refs, { all = false, linger = null, json = false, dryRun = false, out = (s) => console.log(s), scan = undefined } = {}) { + const { fitPostItem } = await import("./postFit.mjs"); + const { fitPostItems } = await import("./manifest.mjs"); + const manifest = await readManifest(project.dir); + if (!manifest) throw new NarrateError(`${project.id} has no manifest`); + const render = manifest.render ?? {}; + const items = all ? (manifest.timeline ?? []).filter((e) => e?.type === "post" && isNarrated(e)) : refs.map((r) => { + const e = findPostItem(manifest, r); + if (!e) throw new NarrateError(`no post item ${r} in ${project.id}`); + return e; + }); + if (!items.length) throw new NarrateError(all ? `${project.id} has no narrated post item` : "name the post items to fit, or --all"); + const fits = []; + const rows = []; + for (const e of items) { + const before = postItemPlan(e, render).total; + const f = await fitPostItem(e, render, project.dir, { linger, ...(scan ? { scan } : {}) }); + if (!f || f.untouched || !f.window) { + rows.push({ id: e.id, before, after: before, note: !f ? "not narrated, clip=full, or no video" : `its video (${f.duration} s) is no longer than the read (${f.L} s): as it is` }); + if (linger !== null && isNarrated(e)) fits.push({ id: e.id, media: {}, window: e.narration?.window ?? null, linger }); + continue; + } + const next = JSON.parse(JSON.stringify(e)); + for (const [k, mp] of Object.entries(f.media)) for (const [kk, v] of Object.entries(mp)) if (v === null) delete next.media[k][kk]; else next.media[k][kk] = v; + next.narration = { ...next.narration, window: f.window, ...(linger !== null ? { linger } : {}) }; + rows.push({ id: e.id, before, after: postItemPlan(next, render).total, window: f.window }); + fits.push({ id: e.id, media: f.media, window: f.window, ...(linger !== null ? { linger } : {}) }); + } + let result = null; + if (!dryRun && fits.length) ({ result } = await withEditNotes(project, async () => fitPostItems(project.dir, fits, { token: await manifestToken(project.dir) }))); + if (json) out(JSON.stringify({ ok: true, dryRun, rows, snapshot: result?.snapshot ?? null, token: result?.token ?? null }, null, 2)); + else { + for (const r of rows) { + out(`${r.id} ${r.before.toFixed(1)} s -> ${r.after.toFixed(1)} s${r.window ? ` window ${r.window.start}–${r.window.end} s: ${r.window.reason}` : ` (${r.note})`}`); + } + const saved = rows.reduce((n, r) => n + (r.before - r.after), 0); + out(`${dryRun ? "would fit" : "fitted"} ${fits.length} post item(s); the cut ${saved >= 0 ? "shorter" : "longer"} by ${Math.abs(saved).toFixed(1)} s${result?.snapshot?.rel && !result.snapshot.skipped ? `; undo point: ${result.snapshot.rel}` : ""}`); + } + return 0; +} diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs @@ -37,10 +37,11 @@ import { execFile } from "node:child_process"; import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; -import { POST_MEDIA_MAX, POST_PARENTS_MAX } from "umtool-report-to-video/post-item"; +import { POST_MEDIA_MAX, POST_PARENTS_MAX, authorRedaction, cardAuthors, subjectsOf } from "umtool-report-to-video/post-item"; +import { ARCHIVE_AVATARS_DIR, ARCHIVE_AVATARS_FILE, AVATARS_DIR, AVATAR_EXT_RE, avatarEntryOf, handleKey } from "umtool-report-to-video/post-avatars"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { insertEntries, manifestToken } from "./manifest.mjs"; +import { addArchiveAvatars, insertEntries, manifestToken } from "./manifest.mjs"; import { deckPlatformOf } from "./postsCli.mjs"; const execFileP = promisify(execFile); @@ -318,6 +319,70 @@ async function copyInto(projectDir, from, rel) { return rel; } +/** + * The archive's pictures (each channel's posts-media/_avatars/avatars.json, + * the editor's capture-posts store: `{ <handle>: { file, url, capturedAt } }`), + * by handle key, the newest when two channels hold one. + * + * @returns {Promise<Map<string, { handle: string, file: string, url: string | null, capturedAt: string | null }>>} + */ +export async function archiveAvatars(channelsDir, channels) { + const out = new Map(); + for (const slug of channels) { + const dir = path.join(channelsDir, slug, "posts-media", ARCHIVE_AVATARS_DIR); + let doc; + try { + doc = JSON.parse(await readFile(path.join(dir, ARCHIVE_AVATARS_FILE), "utf8")); + } catch { + continue; + } + if (!doc || typeof doc !== "object" || Array.isArray(doc)) continue; + for (const [h, a] of Object.entries(doc)) { + if (!a || typeof a !== "object" || typeof a.file !== "string" || a.file.includes("/") || a.file.includes("\\") || !AVATAR_EXT_RE.test(a.file)) continue; + const file = path.join(dir, a.file); + if (!(await stat(file).catch(() => null))?.isFile()) continue; + const had = out.get(handleKey(h)); + const at = typeof a.capturedAt === "string" ? a.capturedAt : null; + if (had && (had.capturedAt ?? "") >= (at ?? "")) continue; + out.set(handleKey(h), { handle: h.replace(/^@/, ""), file, url: typeof a.url === "string" ? a.url : null, capturedAt: at }); + } + } + return out; +} + +/** Every handle an entry's card draws UNBLURRED (a redacted author never gets a picture). */ +export function shownHandles(e) { + const out = []; + if (e?.type === "post") { + const subj = subjectsOf(e); + const o = { subjects: subj, redact: typeof e.redact === "boolean" ? e.redact : undefined }; + if (e.handle && !authorRedaction({ handle: e.handle, badge: e.badge }, o).redact) out.push(e.handle); + for (const a of cardAuthors(e)) if (!a.redact && a.handle) out.push(a.handle); + } + return out; +} + +/** + * The pictures to copy in for `entries` (and the cut's own, for a re-run): + * every handle drawn unblurred that the archive has a picture of and the + * project does not. `copy(fromFile, toRel)` puts one into the project. + * + * @returns {Promise<Record<string, { src: string, url?: string, capturedAt?: string }>>} + */ +export async function avatarsToCopy(manifest, entries, store, copy) { + const out = {}; + const handles = new Set(); + for (const e of [...(manifest?.timeline ?? []), ...entries]) for (const h of shownHandles(e)) handles.add(handleKey(h)); + for (const k of handles) { + const a = store.get(k); + if (!a || avatarEntryOf(manifest, k) || out[a.handle]) continue; + const ext = path.extname(a.file).toLowerCase(); + const src = await copy(a.file, `${AVATARS_DIR}/${a.handle}${ext}`); + out[a.handle] = { src, ...(a.url ? { url: a.url } : {}), ...(a.capturedAt ? { capturedAt: a.capturedAt } : {}) }; + } + return out; +} + /** Parse YYYY-MM-DD (or null); throws in words. */ function dayArg(v, what) { if (v === null || v === undefined || v === "") return null; @@ -402,10 +467,19 @@ export async function postsReel(project, o) { entries.push(made.entry); dropped += made.dropped; } - const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped }; - if (o.dryRun || !entries.length) return { ...summary, entries, dryRun: o.dryRun === true, result: null, editNotes: null }; + // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of. + const store = await archiveAvatars(channelsDir, channels); + const avatars = store.size ? await avatarsToCopy(manifest, entries, store, o.dryRun ? async (_f, rel) => rel : (from, rel) => copyInto(project.dir, from, rel)) : {}; + const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped, avatars: Object.keys(avatars) }; + if (o.dryRun) return { ...summary, entries, dryRun: true, result: null, editNotes: null }; + if (!entries.length) { + // Nothing new to add -- but the cut's authors may have pictures now. + if (!Object.keys(avatars).length) return { ...summary, entries, dryRun: false, result: null, editNotes: null }; + const { result, editNotes } = await withEditNotes(project, async () => addArchiveAvatars(project.dir, avatars, { token: await manifestToken(project.dir) })); + return { ...summary, entries, dryRun: false, result, editNotes }; + } const { result, editNotes } = await withEditNotes(project, async () => - insertEntries(project.dir, o.after ?? null, entries, { token: await manifestToken(project.dir), op: "posts-reel" }), + insertEntries(project.dir, o.after ?? null, entries, { token: await manifestToken(project.dir), op: "posts-reel", avatars }), ); return { ...summary, entries: result.entries, dryRun: false, result, editNotes }; } @@ -444,3 +518,26 @@ export async function postItemFromArchive(project, manifest, slug, postId, { id if (id) entry.id = id; return entry; } + +/** + * The archive's pictures of the authors `entries` draw unblurred that the + * cut has none of, copied into the project (`{ <handle>: { src, url?, + * capturedAt? } }` for insertEntries / addArchiveAvatars). + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} manifest + * @param {string[]} channels + * @param {Array<Record<string, any>>} entries + * @param {{ channelsDir?: string | null }} [o] + */ +export async function archiveAvatarsFor(project, manifest, channels, entries, { channelsDir = null } = {}) { + const dir = channelsDir ?? channelsDirFor(project.dir, manifest); + const store = await archiveAvatars(dir, channels); + if (!store.size) return {}; + return avatarsToCopy(manifest, entries, store, (from, rel) => copyInto(project.dir, from, rel)); +} + +/** The archive channels a cut's post items came from (`post: "<channel>/<postId>"`). */ +export function postChannelsOf(manifest) { + return [...new Set((manifest?.timeline ?? []).filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter(Boolean))]; +} diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -33,7 +33,7 @@ import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { PostsRefused, StaleToken, StructureRefused, manifestToken, updatePostItem, updatePosts, upsertPost } from "./manifest.mjs"; +import { PostsRefused, StaleToken, StructureRefused, addArchiveAvatars, manifestToken, setPostAvatar, updatePostItem, updatePosts, upsertPost } from "./manifest.mjs"; import { postWarnings } from "./postCards.mjs"; export const POSTS_USAGE = [ @@ -60,10 +60,20 @@ export const POSTS_USAGE = [ " [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]", " [media.<i>.push=on|off] [media.<i>.trim=off] [--json]", " a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,", - " an attachment's trim, sound, crop (fractions of its picture) and push-in.", + " an attachment's trim, sound, crop (fractions of its picture) and push-in; fit=read[:linger] (a narrated post: its", + " video cut to its best part for the read, `posts fit`).", + " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", + " (umtool posts narrate --help)", + " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", + " umtool posts 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.", + " umtool posts avatars <project> [--dry-run] [--json]", + " every author the cut's cards draw unblurred, their picture from the archive's store (the channels' posts-media/", + " _avatars/, capture-posts') copied in where the cut has none; a manual one is never replaced.", ].join("\n"); -const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after"]); +const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -336,6 +346,27 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out }); + if (verb === "narrate") { + const { NARRATE_USAGE, narrateCommand } = await import("./postNarrationCli.mjs"); + if (!projectArg || flags.has("--help")) { + err(NARRATE_USAGE); + return 2; + } + return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str }); + } + if (verb === "fit") { + const { FIT_USAGE, fitCommand } = await import("./postNarrationCli.mjs"); + if (!projectArg || flags.has("--help") || (!flags.has("--all") && words.length < 3)) { + err(FIT_USAGE); + return 2; + } + const lingerRaw = str("--linger"); + const linger = lingerRaw === null ? null : Number(lingerRaw); + if (lingerRaw !== null && !(Number.isFinite(linger) && linger >= 0 && linger <= 30)) throw new CliError("--linger takes seconds, 0-30"); + return await fitCommand(await projectOf(projectArg, root), words.slice(2), { all: flags.has("--all"), linger, json, dryRun, out }); + } + if (verb === "avatar" && projectArg && !flags.has("--help")) return await avatarCommand(projectArg, words.slice(2), { root, json, out }); + if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out }); if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); return 2; @@ -408,7 +439,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con return 1; } err(`umtool posts: ${e instanceof Error ? e.message : String(e)}`); - return e instanceof CliError ? 2 : 1; + return e instanceof CliError || e?.constructor?.name === "NarrateError" ? 2 : 1; } } @@ -529,8 +560,16 @@ export function postItemPatchOf(pairs) { return out; } -/** `posts set-item`: a post item's knobs, through updatePostItem. */ +/** `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 }) { + const fitPair = pairs.find((p) => /^fit=/.test(p)); + if (fitPair) { + if (pairs.length > 1) throw new CliError("fit= goes alone (it is posts fit on this item)"); + const m = /^fit=read(?::([\d.]+))?$/.exec(fitPair); + if (!m) throw new CliError("fit= takes read or read:<linger seconds>"); + const { fitCommand } = await import("./postNarrationCli.mjs"); + return fitCommand(await projectOf(projectArg, root), [ref], { linger: m[1] !== undefined ? Number(m[1]) : null, json, out }); + } const patch = postItemPatchOf(pairs); const project = await projectOf(projectArg, root); const manifest = await readManifest(project.dir); @@ -546,3 +585,76 @@ async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { out(`set ${hit.id}: ${postItemSeconds(result.entry).toFixed(1)} s${result.entry.hold ? ` (hold)` : ""}`); return 0; } + +/** `posts avatar`: an author's picture for every card that draws them (setPostAvatar), or the list. */ +async function avatarCommand(projectArg, rest, { root, json, out }) { + const project = await projectOf(projectArg, root); + const [handle, file] = rest; + if (!handle) { + const m = await readManifest(project.dir); + const map = m?.postAvatars && typeof m.postAvatars === "object" ? m.postAvatars : {}; + if (json) out(JSON.stringify({ ok: true, postAvatars: map }, null, 2)); + else if (!Object.keys(map).length) out(`${project.id} has no authors' pictures (umtool posts avatar ${project.id} <handle> <image>, or capture-posts' avatars and umtool posts avatars)`); + else for (const [h, a] of Object.entries(map)) out(`@${h} ${a.src} (${a.source ?? "manual"}${a.capturedAt ? `, captured ${String(a.capturedAt).slice(0, 10)}` : ""})`); + return 0; + } + const h = String(handle).replace(/^@/, ""); + if (!/^[A-Za-z0-9_.-]{1,64}$/.test(h)) throw new CliError(`"${handle}" is not a handle`); + if (!file) throw new CliError(`name the picture: umtool posts avatar ${project.id} ${h} <image-file> (or off)`); + if (OFF.has(String(file).toLowerCase())) { + const { result, editNotes } = await withEditNotes(project, async () => setPostAvatar(project.dir, h, null, { token: await manifestToken(project.dir) })); + if (json) out(JSON.stringify({ ok: true, ...result, token: result.token, editNotes }, null, 2)); + else out(`cleared @${result.handle}'s picture (its cards draw the initial again)`); + return 0; + } + const { AVATARS_DIR, AVATAR_EXT_RE } = await import("umtool-report-to-video/post-avatars"); + const from = path.resolve(String(file)); + const st = await stat(from).catch(() => null); + if (!st?.isFile()) throw new CliError(`${from} is not a file`); + if (!AVATAR_EXT_RE.test(from)) throw new CliError(`${from}: a picture is a jpg, png, webp or gif`); + const rel = `${AVATARS_DIR}/${h}-manual${path.extname(from).toLowerCase()}`; + const to = path.join(project.dir, ...rel.split("/")); + await mkdir(path.dirname(to), { recursive: true }); + const real = await realpath(path.dirname(to)); + const proj = await realpath(project.dir); + if (!real.startsWith(proj + path.sep)) throw new CliError(`${path.dirname(rel)} leads out of ${project.id} (a link) — not copying through it`); + await copyFile(from, to); + const { result, editNotes } = await withEditNotes(project, async () => setPostAvatar(project.dir, h, { src: rel, source: "manual" }, { token: await manifestToken(project.dir) })); + if (json) { + out(JSON.stringify({ ok: true, ...result, token: result.token, editNotes }, null, 2)); + return 0; + } + out(`@${result.handle}'s picture is ${rel}${result.replaced ? ` (was ${result.replaced})` : ""} — on every card that draws them unblurred`); + return 0; +} + +/** `posts avatars`: every author the cut draws unblurred, their archive picture copied in where it has none (one write). */ +async function avatarsCommand(projectArg, { root, json, dryRun, out }) { + const project = await projectOf(projectArg, root); + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const { archiveAvatars, avatarsToCopy, postChannelsOf, shownHandles } = await import("./postReel.mjs"); + const { channelsDirFor } = await import("../projects/report.mjs"); + const channels = postChannelsOf(manifest); + const store = await archiveAvatars(channelsDirFor(project.dir, manifest), channels); + const pics = store.size + ? await avatarsToCopy(manifest, [], store, dryRun ? async (_f, rel) => rel : async (from, rel) => { + const to = path.join(project.dir, ...rel.split("/")); + await mkdir(path.dirname(to), { recursive: true }); + await copyFile(from, to); + return rel; + }) + : {}; + const drawn = [...new Set((manifest.timeline ?? []).flatMap((e) => shownHandles(e)).map((h) => h.toLowerCase()))]; + const have = Object.keys(manifest.postAvatars ?? {}).map((h) => h.toLowerCase()); + const without = drawn.filter((h) => !have.includes(h) && !Object.keys(pics).some((p) => p.toLowerCase() === h)); + let result = null; + if (!dryRun && Object.keys(pics).length) ({ result } = await withEditNotes(project, async () => addArchiveAvatars(project.dir, pics, { token: await manifestToken(project.dir) }))); + if (json) { + out(JSON.stringify({ ok: true, dryRun, channels, copied: pics, without, snapshot: result?.snapshot ?? null }, null, 2)); + return 0; + } + out(`${dryRun ? "would copy" : "copied"} ${Object.keys(pics).length} picture(s) from ${channels.join(" + ") || "no channel"}'s store${Object.keys(pics).length ? `: ${Object.keys(pics).map((h) => `@${h}`).join(", ")}` : ""}`); + if (without.length) out(` no picture yet for ${without.map((h) => `@${h}`).join(", ")} (pnpm ops capture-posts … "avatars": true, or umtool posts avatar ${project.id} <handle> <image>)`); + return 0; +} diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -546,6 +546,13 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } else { ({ result, editNotes } = await write((token) => insertEntry(project.dir, after, entry, { token, at }))); } + // Its authors' pictures (post-avatars.mjs), from the channel's store, when the cut has none of them yet. + const { archiveAvatarsFor } = await import("./postReel.mjs"); + const pics = await archiveAvatarsFor(project, manifest, [m[1]], [entry]).catch(() => ({})); + if (Object.keys(pics).length) { + const { addArchiveAvatars } = await import("./manifest.mjs"); + await write((token) => addArchiveAvatars(project.dir, pics, { token })); + } break; } const c = parseClipSpec(spec); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -212,6 +212,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 { avatarUrls } from "./post-avatars.mjs"; export { snap }; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; @@ -6399,6 +6400,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly box: df ? { width: df.box.width, height: df.box.height } : { width: render.width, height: render.height }, place: df ? df.place : [`fps=${render.fps}`], encode: encodeArgs(render), exec: execFileP, ffmpeg: FFMPEG, emit: (ev, f) => EMIT(ev, f), + // The authors' pictures (post-avatars.mjs), as files of the project. + avatars: avatarUrls(manifest, (src) => path.resolve(manifestDir, src)), }); if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr }); return seg; diff --git a/umtool/report-to-video/deck-band-fit.test.mjs b/umtool/report-to-video/deck-band-fit.test.mjs @@ -0,0 +1,38 @@ +// deck.mjs deckLayout: a crowded band (two rows of marker labels and the +// section title) keeps its title and byline INSIDE the band -- the byline was +// cut off at the frame's foot in the mr-obvious cut (2 Nov) -- and the +// section title's line keeps clear of them; an uncrowded band is as it was. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { deckLayout, deckSchedule, estimatedDuration, markerRowsOf } from "./deck.mjs"; + +const post = (i) => ({ type: "post", id: `p-${i}`, post: `c-x/${i}`, platform: "x", author: "A", handle: "a", date: "2026-10-30T04:00:00Z", text: "six words of a short post" }); +const timeline = Array.from({ length: 40 }, (_, i) => post(i + 1)); +const render = (deck) => ({ + width: 1920, height: 1080, fps: 30, transition: 0.4, palette: { bg: "#000", fg: "#fff", muted: "#888", accent: "#c8752a" }, + chrome: { engine: "hyperframes", layout: "deck", deck }, +}); +// Five sections whose labels crowd each other: they stagger into two rows. +const markers = [["p-3", "Joins the story"], ["p-6", "Strawb, Kirsche's fans"], ["p-8", "A Dox for a Dox"], ["p-10", "Answering critics"], ["p-12", "One Dox away"]].map(([after, label]) => ({ after, label })); + +test("a crowded band: two rows of labels and the section title -- the byline stays inside the band, the line clear of it", () => { + const r = render({ markers, sectionTitle: { first: "Before the story" } }); + const durs = timeline.map((e) => estimatedDuration(e, r)); + const schedule = deckSchedule({ entries: timeline, durs, D: 0.4, render: r, estimated: true }); + assert.equal(markerRowsOf(schedule, r), 2); + const L = deckLayout(r, { schedule }); + assert.ok(L.text.subtitleY + L.text.subtitleBox <= L.height, `${L.text.subtitleY + L.text.subtitleBox} > ${L.height}`); + assert.ok(L.text.titleY > L.pipTrack.y); + // The line stands right of the title column (at most 36% of the width) and keeps centred. + assert.ok(L.sectionTitle.x >= L.text.x + Math.round(1920 * 0.36), JSON.stringify(L.sectionTitle)); + assert.equal(L.sectionTitle.x + L.sectionTitle.width / 2, 960); +}); + +test("an uncrowded band lays out as it did", () => { + const r = render({ markers: [], sectionTitle: { first: "Before the story" } }); + const L = deckLayout(r, {}); + assert.equal(L.sectionTitle.x, 268); + assert.equal(L.sectionTitle.width, 1384); + const plain = deckLayout(render({}), {}); + assert.equal(plain.text.titleY, 49); +}); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -472,6 +472,11 @@ export function threadsGeometry(render) { * * @param {{ tally?: string[] | null, schedule?: any }} [opts] */ +/** The air the band keeps under its text block, px. */ +export const BAND_FOOT = 0; +/** In a crowded band, the share of the width the title and byline keep at the left (the section title stays out of it). */ +export const BAND_TEXT_RESERVE = 0.36; + export function deckLayout(render, { tally = null, schedule = null } = {}) { const { W, deck: rect } = deckGeometry(render); const d = resolveDeck(render); @@ -548,9 +553,22 @@ export function deckLayout(render, { tally = null, schedule = null } = {}) { if (tallyBox.x < W / 2) lo = Math.max(lo, tallyBox.x + tallyBox.width + 24); else hi = Math.min(hi, tallyBox.x - 24); } - const half = Math.max(0, Math.floor(Math.min(W / 2 - lo, hi - W / 2))); - sectionTitle = { x: Math.round(W / 2 - half), y, width: 2 * half, height, size: st.size }; + let half = Math.max(0, Math.floor(Math.min(W / 2 - lo, hi - W / 2))); titleY = Math.max(titleY, y + height + 2); + // A CROWDED BAND (two rows of marker labels and the section title; the + // operator's byline was cut off at the frame's foot, 2 Nov): the text block + // never runs past the band. It rises to fit -- level with the section + // title's line -- and the line keeps to the middle, clear of the left + // column the title and byline stand in (at most BAND_TEXT_RESERVE of the + // width), so the two never meet. + const over = titleY + block + BAND_FOOT - rect.height; + if (over > 0) { + titleY = Math.max(trackY + Math.ceil(d.pip.activeSize / 2) + 4, titleY - over); + const reserve = Math.min(textRight - textX, Math.round(W * BAND_TEXT_RESERVE)); + lo = Math.max(lo, textX + reserve + 24); + half = Math.max(0, Math.floor(Math.min(W / 2 - lo, hi - W / 2))); + } + sectionTitle = { x: Math.round(W / 2 - half), y, width: 2 * half, height, size: st.size }; } return { width: W, @@ -962,7 +980,7 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render)) } if (entry.type === "image") return Number(entry.seconds ?? 4); // A post item (post-item.mjs): its reading time and its attachments, or its `hold`. - if (entry.type === "post") return postItemSeconds(entry); + if (entry.type === "post") return postItemSeconds(entry, render); // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default). if (entry.type === "intro") return Number(entry.seconds ?? INTRO_SECONDS); // A teaser's dip makes its segment longer by the dissolve and the black (`teaserLead`). diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -85,6 +85,8 @@ import { validateClipAudioEntries } from "./clip-audio.mjs"; import { validateClipBlurEntries } from "./clip-blur.mjs"; import { validateGapEntries } from "./gaps.mjs"; import { postItemFiles, validatePostItems } from "./post-item.mjs"; +import { postAvatarFiles, validatePostAvatars } from "./post-avatars.mjs"; +import { validatePostNarrationRender } from "./post-narration.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -262,6 +264,8 @@ export function imageSrcsOf(manifest, { only = null } = {}) { }); } } + // The authors' pictures a post item's card draws (post-avatars.mjs). + if (!only || (manifest.timeline ?? []).some((e) => e?.id === only && e.type === "post")) out.push(...postAvatarFiles(manifest)); if (deckOn(manifest.render) && Array.isArray(manifest.posts)) { for (const p of manifest.posts) { if (!p || (only && p.attachTo !== only)) continue; @@ -321,6 +325,9 @@ export function validatorErrors(whole) { ...validateGapEntries(whole), // A post as a timeline item (post-item.mjs): its archived words, its attachments, its hold. ...validatePostItems(whole), + ...validatePostAvatars(whole), + // A narrated post item's mix (post-narration.mjs): the cut's knobs. + ...validatePostNarrationRender(whole.render), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -211,6 +211,76 @@ export async function narrateCut({ narrations, dir, editor = editorFromEnv(), em return records; } +/** + * ONE ASK, waited for (a narrated post item's take: `umtool posts narrate + * --take`): `POST /api/ops/tts` with `body` -- `{ text, engine, voice, + * speed?, out? }`, `out` an absolute .wav the editor copies its result to -- + * then the job followed to its end. Returns `{ jobId, result }`, the + * `@@tts-result` of its log. `onJob(jobId)` is told the job's id as soon as + * the editor answers (a caller that is stopped can say where it runs). + * + * @param {{ text: string, engine?: string, voice?: string, speed?: number, out?: string }} body + * @param {{ editor?: { url: string, token: string }, emit?: (ev: string, f?: object) => void, pollMs?: number, onJob?: (id: string) => void }} [o] + */ +export async function askEditorTts(body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {} } = {}) { + const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" }; + const reach = async (url, init) => { + try { + return await fetch(url, init); + } catch (err) { + throw new Error(`could not reach the editor at ${editor.url}: ${err?.message ?? err}`); + } + }; + const clean = Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined && v !== null)); + const res = await reach(`${editor.url}/api/ops/tts`, { method: "POST", headers, body: JSON.stringify(clean) }); + const j = await res.json().catch(() => ({})); + if (!res.ok || !j.ok || typeof j.jobId !== "string") throw new Error(`the editor refused the take (HTTP ${res.status}): ${j.error ?? "no reason given"}`); + const jobId = j.jobId; + onJob(jobId); + emit("note", { message: ` asked the editor as job ${jobId} (${clean.engine ?? "its default"} · ${clean.voice ?? "its default"})` }); + let last = ""; + let place = ""; + let failures = 0; + for (;;) { + let r; + try { + r = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}`, { headers }); + } catch (err) { + failures += 1; + if (failures >= MAX_POLL_FAILURES) throw new Error(`lost contact with the editor at ${editor.url} while job ${jobId} ran (${err?.message ?? err}); it may still be running there`); + await sleep(Math.min(MAX_BACKOFF_MS, pollMs * 2 ** failures)); + continue; + } + failures = 0; + const st = await r.json().catch(() => ({})); + if (!r.ok || !st.ok) throw new Error(`polling editor job ${jobId} failed (HTTP ${r.status}): ${st.error ?? ""}`); + const status = st.job?.status ?? "unknown"; + if (status !== last) emit("note", { message: ` editor job ${jobId}: ${status}` }); + last = status; + const q = st.job?.queue; + if (status === "queued" && q && Number(q.position) > 0) { + const line = `queued — position ${q.position}${Number(q.queued) > 0 ? ` of ${q.queued}` : ""}`; + if (line !== place) emit("note", { message: ` editor job ${jobId}: ${line}` }); + place = line; + } + if (status === "queued" || status === "running") { + await sleep(pollMs); + continue; + } + let tail = []; + for (let i = 0; i <= RESULT_RETRIES; i += 1) { + const d = await reach(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}?tail=${TAIL_LINES}`, { headers }); + tail = ((await d.json().catch(() => ({}))).tail ?? []); + if (status !== "done" || ttsResultIn(tail)) break; + await sleep(Math.max(pollMs, 100)); + } + if (status !== "done") throw new Error(`editor job ${jobId} ${status}${tail.length ? ` — ${tail.slice(-3).join(" / ")}` : ""}`); + const result = ttsResultIn(tail); + if (!result) throw new Error(`editor job ${jobId} is done, but its log carries no ${TTS_RESULT_MARKER.trim()} line`); + return { jobId, result }; + } +} + async function main() { const argv = process.argv.slice(2); const flag = (n) => { diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs @@ -18,7 +18,8 @@ import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/ import path from "node:path"; import { promisify } from "node:util"; -import { disclosureLine, narrationDisclosure, narrationsOf } from "./narration.mjs"; +import { disclosureLine, disclosureLines, narrationsOf } from "./narration.mjs"; +import { postNarrationDisclosure } from "./post-narration.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -141,5 +142,11 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { */ export async function readCutDisclosure(dir, manifest, sep = "\n") { const records = await readNarrationRecords(dir, narrationsOf(manifest)); - return narrationDisclosure(manifest, records, sep); + const lines = disclosureLines(manifest, records); + // A narrated post item's (post-narration.mjs): its picked take's engine and voice. + for (const e of manifest?.timeline ?? []) { + const line = e?.type === "post" ? postNarrationDisclosure(e) : null; + if (line && !lines.includes(line)) lines.push(line); + } + return lines.length ? lines.join(sep) : null; } diff --git a/umtool/report-to-video/narration.mjs b/umtool/report-to-video/narration.mjs @@ -202,9 +202,10 @@ export function validateNarration(whole) { for (const [i, e] of (whole?.timeline ?? []).entries()) { if (!e) continue; const where = `timeline[${i}] ${e.id ?? "?"}`; - if (e.narration !== undefined && e.narration !== null) { + // A post item's narration is post-narration.mjs's (its own shape and validator). + if (e.narration !== undefined && e.narration !== null && e.type !== "post") { if (e.type !== "card") { - errors.push(`${where}: narration is on cards only (this is a ${e.type ?? "typeless"} entry)`); + errors.push(`${where}: narration is on cards and post items only (this is a ${e.type ?? "typeless"} entry)`); continue; } if (!isObj(e.narration)) { diff --git a/umtool/report-to-video/narration.test.mjs b/umtool/report-to-video/narration.test.mjs @@ -65,7 +65,7 @@ test("the keys, the engine, the voice, the settings and their bounds", () => { test("narration on cards only; seconds \"auto\" only with one", () => { const e = validateNarration(M([{ type: "clip", id: "c1", narration: { text: "No." } }, { type: "card", id: "k2", seconds: "auto" }])); assert.equal(e.length, 2, e.join("\n")); - assert.match(e[0], /timeline\[0\] c1: narration is on cards only \(this is a clip entry\)/); + assert.match(e[0], /timeline\[0\] c1: narration is on cards and post items only \(this is a clip entry\)/); assert.match(e[1], /timeline\[1\] k2: seconds "auto" is the narration's length, and this entry has no narration/); assert.match(validateNarration(M([card({ seconds: "long" })]))[0], /seconds must be a number of seconds or "auto"/); assert.deepEqual(validateNarration(M([card({ seconds: 6 })])), []); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -53,13 +53,16 @@ "./modules": "./modules/index.mjs", "./modules/*": "./modules/*.mjs", "./mute": "./mute.mjs", + "./narrate-via-editor": "./narrate-via-editor.mjs", "./narration": "./narration.mjs", "./narration-review": "./narration-review.mjs", "./narration-store": "./narration-store.mjs", "./package.json": "./package.json", "./pauses": "./pauses.mjs", "./post-links": "./post-links.mjs", + "./post-avatars": "./post-avatars.mjs", "./post-item": "./post-item.mjs", + "./post-narration": "./post-narration.mjs", "./post-render": "./post-render.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.mjs", diff --git a/umtool/report-to-video/post-avatars.mjs b/umtool/report-to-video/post-avatars.mjs @@ -0,0 +1,80 @@ +// THE AUTHORS' PICTURES of a cut's post items and threads (umtool/docs/ +// report-video.md, "Avatars"): the manifest's `postAvatars`, one picture per +// handle, used by every card that draws that author -- +// +// "postAvatars": { "ObviousRises": { "src": "posts-media/_avatars/ObviousRises.jpg", +// "source": "archive" | "manual", +// "url": "https://pbs.twimg.com/…_400x400.jpg", "capturedAt": "…" } } +// +// `source: "archive"`: copied in from the posts archive's own store when a post +// of that author went in (a channel's `posts-media/_avatars/avatars.json`, +// written by the editor's capture-posts); `"manual"`: `umtool posts avatar`, +// which an archive copy never replaces. The file is IN the project (never a +// link out of it). A REDACTED author never shows one, whatever is here: the +// card draws a blurred stand-in (post-item.mjs avatarHtml). +// +// PURE: the validator, the files the lint checks, and the map a card is drawn +// with. The copying is lib/report/postReel.mjs's. + +/** Where a project keeps the pictures, and where a channel's posts archive keeps its own. */ +export const AVATARS_DIR = "posts-media/_avatars"; +/** The archive's store, inside a channel's posts-media/ (the editor's capture-posts writes it). */ +export const ARCHIVE_AVATARS_DIR = "_avatars"; +export const ARCHIVE_AVATARS_FILE = "avatars.json"; +export const AVATAR_SOURCES = Object.freeze(["archive", "manual"]); +export const AVATAR_EXT_RE = /\.(?:jpe?g|png|webp|gif)$/i; +const HANDLE_RE = /^[A-Za-z0-9_.-]{1,64}$/; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** A handle as a key: no `@`, compared without regard to case. */ +export const handleKey = (h) => String(h ?? "").replace(/^@/, "").toLowerCase(); + +/** The manifest's entry for `handle` (`[key, value]`, matched without regard to case), or null. */ +export function avatarEntryOf(manifest, handle) { + const map = isObj(manifest?.postAvatars) ? manifest.postAvatars : {}; + const k = handleKey(handle); + for (const [h, v] of Object.entries(map)) if (handleKey(h) === k && isObj(v)) return [h, v]; + return null; +} + +/** Every reason `postAvatars` cannot be built (the writers' check and the build's lint). */ +export function validatePostAvatars(manifest) { + const v = manifest?.postAvatars; + if (v === undefined) return []; + if (!isObj(v)) return ["postAvatars must be { <handle>: { src, source } }"]; + const errors = []; + const seen = new Set(); + for (const [h, a] of Object.entries(v)) { + const w = `postAvatars.${h}`; + if (!HANDLE_RE.test(h.replace(/^@/, ""))) errors.push(`${w}: "${h}" is not a handle`); + if (seen.has(handleKey(h))) errors.push(`${w}: a second picture for the same handle (handles are matched without regard to case)`); + seen.add(handleKey(h)); + if (!isObj(a)) { + errors.push(`${w} must be { src, source }`); + continue; + } + if (typeof a.src !== "string" || !a.src.startsWith(`${AVATARS_DIR}/`) || a.src.split("/").includes("..") || !AVATAR_EXT_RE.test(a.src)) { + errors.push(`${w}.src must be a picture under ${AVATARS_DIR}/ (jpg, png, webp or gif), got ${JSON.stringify(a.src)}`); + } + if (a.source !== undefined && !AVATAR_SOURCES.includes(a.source)) errors.push(`${w}.source must be ${AVATAR_SOURCES.join(" or ")}`); + if (a.url !== undefined && (typeof a.url !== "string" || !/^https?:\/\//.test(a.url))) errors.push(`${w}.url must be an http(s) link`); + } + return errors; +} + +/** The files `postAvatars` names, as `{ where, src }` (the lint checks each is there). */ +export function postAvatarFiles(manifest) { + const map = isObj(manifest?.postAvatars) ? manifest.postAvatars : {}; + return Object.entries(map) + .filter(([, a]) => isObj(a) && typeof a.src === "string") + .map(([h, a]) => ({ where: `postAvatars.${h}`, src: a.src })); +} + +/** `{ <handle>: url }` for a card: each picture's `src` through `toUrl` (a file url, a route's). */ +export function avatarUrls(manifest, toUrl) { + const out = {}; + const map = isObj(manifest?.postAvatars) ? manifest.postAvatars : {}; + for (const [h, a] of Object.entries(map)) if (isObj(a) && typeof a.src === "string") out[h] = toUrl(a.src); + return out; +} diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -22,6 +22,10 @@ // the validator, the duration rule, the plan of what plays when, the layout // and the card's HTML. +import { + isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration, +} from "./post-narration.mjs"; + /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); export const POST_MEDIA_KINDS = Object.freeze(["image", "video", "gif"]); @@ -136,33 +140,101 @@ export function mediaSteps(entry) { return indexed.map((m) => ({ kind: m.kind, items: [m], seconds: mediaSeconds(m) })); } +/** + * THE ONE LAYOUT AND THE PACING RULE (operator, 2 Nov: "the gallery cycle + * needs to be shown like a video and text stays on the screen the whole + * time"; "read out every post, and not linger too long after finishing the + * read"). Every post item is its card -- the full text, on screen for the + * item's whole length -- and, beside it, its attachments played as ONE + * sequence, like a video, WHILE the words are read: + * + * the read = narrated: lead + the take + tail + linger (post-narration.mjs); + * not: the reading time (readingSeconds) + * a video = from the item's first frame, from its in point (or the best + * part `posts fit` chose) for the read -- cut to it; an out point + * set is kept as the choice; `clip: "full"` plays it whole + * pictures = the read's time left after the videos, shared out: a GIF + * looped, the images cycling (crossfaded), each at least + * POST_PICTURE_MIN s; a grid of 2-4 images is one picture + * total = max(the read, the attachments) -- or `hold` + * + * A video shorter than the read holds its last frame (`short: "hold"`) or + * loops (`short: "loop"`). Narrated with `attach: "after"`, the narration is + * read over the card first and the attachments play after it, whole. + */ +export const POST_PICTURE_MIN = 1.5; +/** The crossfade from one picture to the next, in seconds. */ +export const POST_PICTURE_XFADE = 0.3; + /** The item's length by the rule, before `hold`. */ -export function ruleSeconds(entry) { - return round3(readingSeconds(entry) + mediaSteps(entry).reduce((n, s) => n + s.seconds, 0)); +export function ruleSeconds(entry, render = undefined) { + return planOf(entry, render, null).total; } -/** The item's length in the cut: `hold` when it is set, else the rule. */ -export function postItemSeconds(entry) { - return fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : ruleSeconds(entry); +/** The item's length in the cut: `hold` when it is set, else the rule. `render` the cut's (its `postNarration` knobs). */ +export function postItemSeconds(entry, render = undefined) { + if (fin(entry?.hold) && entry.hold > 0) return round3(entry.hold); + return ruleSeconds(entry, render); } /** * WHAT PLAYS WHEN inside a post item, in its own seconds (0 is its first - * frame): the reading span, then each step of the attachments. A step is - * `{ kind, items, at, seconds, srcFrom, srcTo, loop, sound }` -- a video's - * source span and whether its sound plays, a GIF's loop. With `hold` the plan - * is cut (or extended) to it: a step past the end is dropped, the last one - * cut at it; a longer hold holds the last step up (`held`). Both the render - * and Play the cut play this plan. + * frame): each step of the attachments, from the first frame (the rule + * above). A step is `{ kind, items, at, seconds, srcFrom, srcTo, loop, + * sound }` -- a video's source span and whether its sound plays, a GIF's + * loop. `reading` is 0 (the words are on screen throughout) but for a + * narration read before the attachments (`attach: "after"`). With `hold` the + * plan is cut (or extended) to it. A narrated item's plan carries its mix + * (`narration`: narrationSchedule). The render and Play both play this plan. * - * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number }} + * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number, narration?: Record<string, any> }} */ -export function postItemPlan(entry) { - const reading = readingSeconds(entry); - const total = postItemSeconds(entry); +export function postItemPlan(entry, render = undefined) { + const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null; + return planOf(entry, render, hold); +} + +function planOf(entry, render, hold) { + const narrated = isNarrated(entry); + const k = postNarrationKnobs(entry, render); + const sch = narrated ? narrationSchedule(entry, render) : null; + const extra = sch ? { narration: sch } : {}; + if (sch && k.attach === "after") { + const voiceOnly = round3(sch.at + sch.seconds + k.tail); + const all = mediaSteps(entry); + const media = all.reduce((n, s) => n + s.seconds, 0); + const total = hold ?? round3(voiceOnly + media + (all.length ? 0 : k.linger)); + const plan = planSteps(all, voiceOnly, total); + return { ...plan, reading: round3(Math.min(voiceOnly, total)), total, ...extra }; + } + const span = sch ? round3(sch.at + sch.seconds + k.tail + k.linger) : readingSeconds(entry); + const all = mediaSteps(entry).map((s) => { + if (s.kind !== "video" || k.clip === "full") return s; + // An out point the operator (or posts fit) set is kept: that span is the choice. + return fin(s.items[0].end) ? s : { ...s, seconds: round3(Math.min(s.seconds, span)) }; + }); + const videos = all.filter((s) => s.kind === "video").reduce((n, s) => n + s.seconds, 0); + const pics = all.filter((s) => s.kind !== "video"); + const share = pics.length ? Math.max(POST_PICTURE_MIN, (span - videos) / pics.length) : 0; + const steps = all.map((s) => (s.kind === "video" ? s : { ...s, seconds: round3(share) })); + const media = round3(steps.reduce((n, s) => n + s.seconds, 0)); + const total = hold ?? round3(Math.max(span, media)); + const plan = planSteps(steps, 0, total); + // A video shorter than the read: looped to the end, or (the default) its last frame held. + const last = plan.steps[plan.steps.length - 1]; + if (k.short === "loop" && last?.kind === "video" && plan.held > 0.05) { + last.seconds = round3(last.seconds + plan.held); + last.loop = true; + plan.held = 0; + } + return { ...plan, reading: 0, total, ...extra }; +} + +/** Steps placed from `at0`, cut at `total` (postItemPlan's walk). */ +function planSteps(stepsIn, at0, total) { const steps = []; - let at = reading; - for (const s of mediaSteps(entry)) { + let at = at0; + for (const s of stepsIn) { if (at >= total - 0.05) break; const seconds = round3(Math.min(s.seconds, total - at)); const m = s.items[0]; @@ -178,9 +250,7 @@ export function postItemPlan(entry) { }); at += seconds; } - // A text-only post reads for the whole; one with attachments holds its last up to `hold`. - const held = steps.length ? round3(Math.max(0, total - at)) : 0; - return { reading: round3(Math.min(reading, total)), total, steps, held }; + return { steps, held: steps.length ? round3(Math.max(0, total - at)) : 0 }; } /** The step on screen at item second `s` (null in the reading span). */ @@ -194,7 +264,7 @@ export function stepAt(plan, s) { export function mediaTimeAt(step, s) { if (!step || (step.kind !== "video" && step.kind !== "gif")) return null; const local = Math.max(0, s - step.at); - if (step.kind === "gif") { + if (step.kind === "gif" || (step.loop && step.kind === "video")) { const pass = Math.max(0.1, step.srcTo - step.srcFrom); return round3(step.srcFrom + (local % pass)); } @@ -350,6 +420,8 @@ export function validatePostItem(e) { e.media.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.media[${i}]`))); } } + // Its narration (post-narration.mjs): the script, the takes, the mix's knobs. + errors.push(...validatePostNarration(e)); return errors; } @@ -398,6 +470,7 @@ export function postItemFiles(entry) { if (typeof m?.src === "string") out.push({ where: `${w}.media[${i}]`, src: m.src }); }); if (typeof entry?.parentShot === "string") out.push({ where: `${w}.parentShot`, src: entry.parentShot }); + out.push(...postNarrationFiles(entry)); return out; } @@ -461,10 +534,12 @@ export function postLayout(entry, { width, height }) { } const cardW = Math.round((width - 3 * pad) * 0.42); const side = fitSize(words, cardW - 2 * pad, height - 4 * pad - chrome, k); - if (side.fits && side.size >= POST_SIDE_MIN * k) { + // ONE LAYOUT (operator, 2 Nov): the words stay beside the attachments the whole time, at the size that fits + // (the page shrinks them further if it must) -- never the card alone, then the attachments under a strip. + if (side.fits || steps.length) { const card = { x: pad, y: pad, width: cardW, height: height - 2 * pad }; const slot = { x: 2 * pad + cardW, y: pad, width: width - 3 * pad - cardW, height: height - 2 * pad }; - return { mode: "side", card, slot, strip: null, size: side.size, fits: true, pad }; + return { mode: "side", card, slot, strip: null, size: side.size, fits: side.fits, pad }; } const t = textCard(width - 2 * pad); const stripH = Math.round(92 * k); @@ -507,8 +582,8 @@ export function stepBoxes(step, slot, gap = 12) { } /** A string inside a quoted CSS url(): a <style> is raw text, so HTML entities would be read literally. */ -const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => (c === "<" ? "\\3c " : c === ">" ? "\\3e " : `\\${c === "\n" ? "a " : c}`)); -const esc = (s) => +export const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => (c === "<" ? "\\3c " : c === ">" ? "\\3e " : `\\${c === "\n" ? "a " : c}`)); +export const esc = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); function rgb(hex) { @@ -522,7 +597,7 @@ export function mixHex(a, b, t) { const y = rgb(b); return `#${x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, "0")).join("")}`; } -const rgbaOf = (hex, a) => `rgba(${rgb(hex).join(", ")}, ${a})`; +export const rgbaOf = (hex, a) => `rgba(${rgb(hex).join(", ")}, ${a})`; const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** The card's date line: "Oct 30, 2026 · 04:00 UTC" (UTC: the same card on every machine). */ @@ -546,7 +621,7 @@ export function countText(n) { if (n < 1e6) return `${Math.round(n / 1000)}K`; return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`; } -const PLATFORM_NAME = { x: "X", bluesky: "Bluesky", web: "Web" }; +export const PLATFORM_NAME = { x: "X", bluesky: "Bluesky", web: "Web" }; /** The deck's title and subtitle for a post item (deck.mjs deckText). */ export function postDeckText(entry, formatDate = (d) => d) { @@ -559,14 +634,14 @@ export function postDeckText(entry, formatDate = (d) => d) { }; } -const hueOf = (s) => { +export const hueOf = (s) => { let h = 0; for (const c of String(s ?? "")) h = (h * 31 + c.charCodeAt(0)) % 360; return h; }; /** The words with @mentions of the blurred authors blurred (their handle never in the page). */ -function wordsHtml(text, blurred) { +export function wordsHtml(text, blurred) { const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase())); return esc(text) .replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`)) @@ -574,14 +649,33 @@ function wordsHtml(text, blurred) { .replace(/\n/g, "<br>"); } -function avatarHtml(who, { redact, size, accent }) { +/** + * The url of `handle`'s avatar in `avatars` (`{ <handle>: url }`, the + * project's `postAvatars` resolved by the caller), matched without regard to + * case, or null. + */ +export function avatarUrlOf(avatars, handle) { + const h = str(handle).replace(/^@/, "").toLowerCase(); + if (!h || !isObj(avatars)) return null; + for (const [k, v] of Object.entries(avatars)) if (k.replace(/^@/, "").toLowerCase() === h && typeof v === "string" && v) return v; + return null; +} + +/** + * An author's round avatar: their picture when one is known (`img`), else the + * initial on a colour of their handle. A REDACTED author never shows a + * picture -- a blurred stand-in, whatever is known. + */ +export function avatarHtml(who, { redact, size, accent, img = null }) { const name = str(who?.author) || str(who?.handle) || "?"; const initial = esc((name.replace(/^@/, "")[0] ?? "?").toUpperCase()); const bg = accent ?? `hsl(${hueOf(who?.handle)}, 38%, 42%)`; - return `<div class="avatar${redact ? " redact" : ""}" style="width:${size}px;height:${size}px;font-size:${Math.round(size * 0.46)}px;background:${bg}">${redact ? "" : initial}</div>`; + const pic = !redact && typeof img === "string" && img; + const inner = redact ? "" : pic ? `<img src="${esc(img)}" alt="" style="width:100%;height:100%;border-radius:50%;object-fit:cover;display:block">` : initial; + return `<div class="avatar${redact ? " redact" : ""}" data-post-avatar="${redact ? "redacted" : pic ? "image" : "initial"}" style="width:${size}px;height:${size}px;font-size:${Math.round(size * 0.46)}px;background:${bg}">${inner}</div>`; } -function nameHtml(who, { redact, cls = "" }) { +export function nameHtml(who, { redact, cls = "" }) { if (redact) return `<span class="who ${cls}"><span class="name redact">xxxxxxxxxxxx</span> <span class="handle redact">@xxxxxxxx</span></span>`; const h = str(who?.handle).replace(/^@/, ""); return `<span class="who ${cls}"><span class="name">${esc(str(who?.author) || h)}</span>${h ? ` <span class="handle">@${esc(h)}</span>` : ""}</span>`; @@ -595,13 +689,16 @@ function nameHtml(who, { redact, cls = "" }) { * "media" in a stack layout the strip over the slot. `fonts` are urls for * the regular and bold faces; with none, the page falls back to sans-serif. * `parentShotUrl`: the capture's thread shot, drawn as the context when the - * post it answers is not archived. + * post it answers is not archived. `avatars`: `{ <handle>: url }`, the + * authors' pictures (the project's `postAvatars`, post-avatars.mjs); an + * author with none is drawn as the initial, a redacted one never shows one. * * @param {Record<string, any>} entry * @param {{ width: number, height: number, palette?: Record<string, string>, fonts?: { regular?: string, bold?: string }, - * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean }} o + * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean, avatars?: Record<string, string> }} o */ -export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false }) { +export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {} }) { + const pic = (who) => avatarUrlOf(avatars, who?.handle); const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; const L = postLayout(entry, { width, height }); const k = height / 1080; @@ -627,7 +724,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p const r = red(`parents[${i}]`); const subject = !r && subjectsOf(entry).some((h) => String(h).toLowerCase() === String(p.handle ?? "").replace(/^@/, "").toLowerCase()); ctx.push( - `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span></div><div class="ptext">${wordsHtml(str(p.text) || (p.url ? "(not archived)" : ""), blurred)}</div></div></div>`, + `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span></div><div class="ptext">${wordsHtml(str(p.text) || (p.url ? "(not archived)" : ""), blurred)}</div></div></div>`, ); } if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`); @@ -636,16 +733,16 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p } const q = isObj(entry.quoted) ? entry.quoted : null; const quoted = q - ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span></div><div class="qtext">${wordsHtml(str(q.text), blurred)}</div></div>` + ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span></div><div class="qtext">${wordsHtml(str(q.text), blurred)}</div></div>` : ""; const repost = entry.repostedBy ? `<div class="repost" data-post-repost="">&#x21bb; ${esc(str(entry.repostedBy.author) || `@${entry.repostedBy.handle}`)} reposted</div>` : ""; - const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`; + const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`; // A card alone (text, or a stack's reading) is as tall as its words, centred in its box; beside the attachments, the box's height. const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${wordsHtml(cardText(entry), blurred)}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`; const stripHtml = L.strip - ? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: ownRed, size: Math.round(56 * k), accent: ownRed ? undefined : pal.accent })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>` + ? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: ownRed, size: Math.round(56 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>` : ""; const slot = L.slot && (L.mode === "side" || strip) ? `<div class="slot" data-post-slot="" style="left:${L.slot.x}px;top:${L.slot.y}px;width:${L.slot.width}px;height:${L.slot.height}px"></div>` : ""; const body = strip ? `${stripHtml}${slot}` : `${card(L.card)}${slot}`; diff --git a/umtool/report-to-video/post-item.test.mjs b/umtool/report-to-video/post-item.test.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { - POST_GIF, POST_IMAGE_SECONDS, POST_READ, authorRedaction, cardAuthors, cardText, mediaSeconds, mediaTimeAt, postCardHtml, + POST_GIF, POST_IMAGE_SECONDS, POST_PICTURE_MIN, POST_READ, authorRedaction, cardAuthors, cardText, mediaSeconds, mediaTimeAt, postCardHtml, postDeckText, postItemPlan, postItemSeconds, postLayout, readingSeconds, ruleSeconds, stepAt, stepBoxes, validatePostItem, wordCount, } from "./post-item.mjs"; import { deckText, estimatedDuration, deckQrUrl, resolveDeck, validateDeckMarkers } from "./deck.mjs"; @@ -33,7 +33,7 @@ test("a valid post item passes; each field is refused in words", () => { assert.ok(validatePostItem(base({ media: [video(), video(), video(), video(), video()] })).some((e) => e.includes("at most 4 attachments"))); }); -test("the duration rule: reading time (words / wps + lead, clamped) plus the attachments; hold overrides", () => { +test("the pacing rule: the item is its read; a long video is cut to it, pictures share it; hold overrides", () => { assert.equal(wordCount(" a b\nc "), 3); // Six words: 1 + 6/3 = 3 s (the floor). assert.equal(readingSeconds(base()), POST_READ.min); @@ -44,39 +44,51 @@ test("the duration rule: reading time (words / wps + lead, clamped) plus the att assert.equal(cardText(base({ text: "RT @ObviousRises: hello there", repostedBy: { handle: "ObviousRises" } })), "hello there"); // A parent and a quote add their own reading, clamped 1–4. assert.equal(readingSeconds(base({ parents: [{ text: "a" }], quoted: { text: Array.from({ length: 60 }, () => "q").join(" ") } })), 3 + 1 + 4); - // Attachments in sequence. + // Each attachment's own length (what a sequence of them would take). assert.equal(mediaSeconds(video({ start: 1, end: 4 })), 3); assert.equal(mediaSeconds(image()), POST_IMAGE_SECONDS); assert.equal(mediaSeconds({ kind: "gif", seconds: 1.2 }), 3.6); // looped to ≥ 3 s: three passes assert.equal(mediaSeconds({ kind: "gif", seconds: 25 }), POST_GIF.max); - assert.equal(ruleSeconds(base({ media: [video(), image()] })), 3 + 6.2 + 3.5); + // A 6.2 s video under a 3 s read is cut to the read; an image beside it gets the minimum. + assert.equal(ruleSeconds(base({ media: [video()] })), 3); + assert.equal(ruleSeconds(base({ media: [video(), image()] })), 3 + POST_PICTURE_MIN); + // An out point set is kept as the choice: its span plays. + assert.equal(ruleSeconds(base({ media: [video({ start: 1, end: 5 })] })), 4); assert.equal(postItemSeconds(base({ media: [video()], hold: 5 })), 5); - // A grid of images is one step: 3.5 + 1 per extra. - assert.equal(ruleSeconds(base({ mediaLayout: "grid", media: [image(), image(), image()] })), 3 + 5.5); + // Pictures share the read, each at least the minimum. + assert.equal(ruleSeconds(base({ media: [image(), image(), image(), image()] })), 4 * POST_PICTURE_MIN); + assert.equal(ruleSeconds(base({ text: long.text, media: [image(), image()] })), 11); + // A grid of images is one picture: the read. + assert.equal(ruleSeconds(base({ mediaLayout: "grid", media: [image(), image(), image()] })), 3); // The deck's estimate is the rule. - assert.equal(estimatedDuration(base({ media: [video()] })), 9.2); + assert.equal(estimatedDuration(base({ media: [video()] })), 3); }); -test("the plan: the words first, then each attachment; a hold cuts it short or holds the last", () => { - const p = postItemPlan(base({ media: [video({ start: 1, end: 3 }), image()] })); - assert.equal(p.reading, 3); - assert.equal(p.total, 3 + 2 + 3.5); - assert.deepEqual(p.steps.map((s) => [s.kind, s.at, s.seconds]), [["video", 3, 2], ["image", 5, 3.5]]); +test("the plan: the attachments from the first frame, like a video, while the words stay; a hold cuts or holds", () => { + const p = postItemPlan(base({ text: Array.from({ length: 30 }, () => "w").join(" "), media: [video({ start: 1, end: 3 }), image()] })); + assert.equal(p.reading, 0); + assert.equal(p.total, 11); + assert.deepEqual(p.steps.map((s) => [s.kind, s.at, s.seconds]), [["video", 0, 2], ["image", 2, 9]]); assert.equal(p.steps[0].srcFrom, 1); assert.equal(p.steps[0].srcTo, 3); assert.equal(p.steps[0].sound, true); - assert.equal(stepAt(p, 1), null); - assert.equal(stepAt(p, 4).kind, "video"); - assert.equal(mediaTimeAt(p.steps[0], 4), 2); - const cut = postItemPlan(base({ media: [video(), image()], hold: 5 })); + assert.equal(stepAt(p, 1).kind, "video"); + assert.equal(stepAt(p, 4).kind, "image"); + assert.equal(mediaTimeAt(p.steps[0], 1), 2); + const cut = postItemPlan(base({ media: [video(), image()], hold: 2 })); assert.deepEqual(cut.steps.map((s) => [s.kind, s.seconds]), [["video", 2]]); assert.equal(cut.steps[0].srcTo, 2); const held = postItemPlan(base({ media: [image()], hold: 12 })); - assert.equal(held.held, 12 - 6.5); + assert.equal(held.steps[0].seconds, 3); + assert.equal(held.held, 9); assert.equal(postItemPlan(base({ media: [video({ mute: true })] })).steps[0].sound, false); const gif = postItemPlan(base({ media: [{ src: "g.mp4", kind: "gif", seconds: 1.2 }] })); assert.equal(gif.steps[0].loop, true); - assert.equal(mediaTimeAt(gif.steps[0], 3 + 1.5), 0.3); + assert.equal(mediaTimeAt(gif.steps[0], 1.5), 0.3); + // A short video under a long read: held (or looped). + const short = postItemPlan(base({ text: Array.from({ length: 30 }, () => "w").join(" "), media: [video({ seconds: 4 })] })); + assert.equal(short.total, 11); + assert.equal(short.held, 7); }); test("the privacy rule: another author is blurred unless the subject, gold/grey verified, or redact:false", () => { @@ -103,16 +115,15 @@ test("the privacy rule: another author is blurred unless the subject, gold/grey assert.ok(postCardHtml(base({ replyingTo: "private_person" }), { width: 1440, height: 810 }).includes("Replying to <span class=\"redact\">")); }); -test("the layout: text alone; the words beside the attachments when they fit; else read first, then the media large", () => { +test("ONE LAYOUT: the text alone, or the words beside the attachments the whole time -- never a stack", () => { const box = { width: 1440, height: 810 }; assert.equal(postLayout(base(), box).mode, "text"); const side = postLayout(base({ media: [video()] }), box); assert.equal(side.mode, "side"); assert.ok(side.slot.x > side.card.x + side.card.width); const words = Array.from({ length: 480 }, () => "word").join(" "); - const stack = postLayout(base({ text: words, media: [video()] }), box); - assert.equal(stack.mode, "stack"); - assert.ok(stack.strip && stack.slot.y > stack.strip.y); + const long = postLayout(base({ text: words, media: [video()] }), box); + assert.equal(long.mode, "side"); // A media box keeps its aspect inside the slot; a grid of two lays them side by side. const [b] = stepBoxes({ items: [{ i: 0, width: 1920, height: 1080 }] }, side.slot); assert.ok(Math.abs(b.width / b.height - 16 / 9) < 0.02); diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -0,0 +1,453 @@ +// A NARRATED POST ITEM (umtool/docs/report-video.md, "Narrated post items"): +// a post item (post-item.mjs) read aloud by a stock synthetic voice, its own +// attachment playing under the read -- its sound low-passed and quiet while +// the narrator speaks, then crossfaded back to the clean, full sound. The +// operator's demo (2 Nov 2026, narr-demo/mix.sh) is the reference: these +// defaults ARE its numbers. +// +// entry.narration = { +// script: "what is read (Orpheus tags <sigh> <laugh> … allowed)", +// excerpt?: true, // drafted as an excerpt of a longer post +// engine?, voice?, speed?, // the next take's (default: render.postNarration's) +// takes: [{ file: "narration/posts/<postId>/take-<n>.<engine>-<voice>.wav", +// engine, voice, seconds, script, at, note?, speed?, lufs?, jobId? }], +// pick?: <index into takes>, // absent: the first +// approved?: true, // the picked take on this script, approved +// off?: true, // kept, but the item plays un-narrated +// // the mix, per post (absent: render.postNarration's, else the defaults): +// lead?, tail?, ramp?, linger?, clip?, wet?, lowpassHz?, duck?, short?, attach?, lufs? +// window?: { media, start, end, score, reason, at } // why `posts fit` chose the attachment's span +// } +// +// The takes are FILES OF THE PROJECT (`narration/posts/<postId>/`), written by +// the editor's tts op (`pnpm ops tts`, its `out`) -- umtool never synthesizes. +// `narration/posts/index.json` is the hand-made batch's list of them, which +// `umtool posts narrate <p> --import` reads into the manifest. +// +// PURE and dependency-free (the build, Play, the bench, the writers and the +// lint read it): the knobs and their defaults, the validator, which take +// plays, the mix's schedule, the ffmpeg filters of the mix, a script drafted +// from the post's words. The plan of what plays when is post-item.mjs's +// (postItemPlan's narrated branch), which reads these. + +/** The engines a post's narration may name (the editor's tts op). */ +export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]); +/** A take's engine: one of those, or `recorded` -- a person's own voice, recorded on the post bench (never synthesized). */ +export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "recorded"]); + +/** + * THE MIX's KNOBS and their defaults (`render.postNarration`, and the same + * keys on one post's `narration`): the demo's numbers. + * + * lead 0.4 the narrator starts this far into the item + * tail 0.3 the attachment stays muffled this long after the words + * ramp 0.8 then crossfades back to its clean, full sound over this + * linger 1.8 THE ITEM ENDS THIS LONG AFTER THE WORDS (operator, 2 Nov: "read out + * every post, and not linger too long after finishing the read"): + * the ramp back to the clean sound happens inside it + * clip read an attachment longer than lead + read + tail + linger is cut to + * that (its in point, or the best part `posts fit` chose); "full" + * plays it whole (the demo's way) + * wet 0.30 the muffled sound's level under the narrator + * lowpassHz 650 the muffle: a low-pass at this frequency, twice + * duck true muffle the attachment under the read (false: full under it) + * short hold a video shorter than the read: its last frame held, or looped + * attach under the attachments start with the read (under), or after it + * (one post's knob only: it decides the card's layout) + * lufs -21 the voice is levelled to this before the narrator's + * compressor (-21 LUFS is where Orpheus `zac` reads: the + * demo's chain was tuned there) + * engine orpheus, voice zac what a new take is synthesized with + */ +export const POST_NARRATION_DEFAULTS = Object.freeze({ + lead: 0.4, + tail: 0.3, + ramp: 0.8, + linger: 1.8, + clip: "read", + wet: 0.3, + lowpassHz: 650, + duck: true, + short: "hold", + attach: "under", + lufs: -21, + engine: "orpheus", + voice: "zac", +}); + +export const POST_NARRATION_LIMITS = Object.freeze({ + lead: [0, 5], + tail: [0, 5], + ramp: [0, 5], + linger: [0, 30], + wet: [0, 1], + lowpassHz: [100, 8000], + lufs: [-40, -10], + speed: [0.5, 2], + /** A script is a post read aloud: past this many characters it is a podcast. */ + scriptChars: 4000, + takes: 50, +}); +export const POST_NARRATION_SHORT = Object.freeze(["hold", "loop"]); +export const POST_NARRATION_ATTACH = Object.freeze(["under", "after"]); + +/** + * THE NARRATOR's CHAIN after the levelling gain: the demo's compressor and + * make-up gain, then (over the whole mix) its limiter. + */ +export const POST_NARRATOR_COMPRESSOR = "acompressor=threshold=0.1:ratio=3:attack=5:release=120"; +export const POST_NARRATOR_MAKEUP = 1.5; +export const POST_NARRATION_LIMIT = 0.95; + + +export const POST_NARRATION_CLIP = Object.freeze(["read", "full"]); + +const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs"]; +// `attach` is one post's (it decides the card's layout, which is drawn from the entry alone). +const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice"]); +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"]); +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId"]); +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"]; + +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 round3 = (v) => Math.round(v * 1000) / 1000; + +/** `render.postNarration` with every default filled in. */ +export function resolvePostNarrationRender(render) { + const r = isObj(render?.postNarration) ? render.postNarration : {}; + return { ...POST_NARRATION_DEFAULTS, ...Object.fromEntries(Object.entries(r).filter(([k, v]) => RENDER_KEYS.has(k) && v !== undefined && v !== null)) }; +} + +/** One post's mix knobs: its own, else the cut's, else the defaults. */ +export function postNarrationKnobs(entry, render) { + const base = resolvePostNarrationRender(render); + const n = isObj(entry?.narration) ? entry.narration : {}; + const out = { ...base, attach: POST_NARRATION_DEFAULTS.attach }; + for (const k of [...MIX_KEYS, "engine", "voice"]) if (n[k] !== undefined && n[k] !== null) out[k] = n[k]; + return out; +} + +/** The take that plays (the picked one, else the first), or null. */ +export function pickedTake(entry) { + const n = entry?.narration; + if (!isObj(n) || !Array.isArray(n.takes) || !n.takes.length) return null; + const i = Number.isInteger(n.pick) ? n.pick : 0; + const t = n.takes[i]; + return isObj(t) && typeof t.file === "string" && fin(t.seconds) && t.seconds > 0 ? { ...t, index: i } : null; +} + +/** Is the item narrated -- a take picked, and not switched off? */ +export const isNarrated = (entry) => entry?.type === "post" && entry?.narration?.off !== true && !!pickedTake(entry); + +/** Narrated, its attachments starting WITH the read (the demo's way)? */ +export const narratedUnder = (entry, render) => isNarrated(entry) && postNarrationKnobs(entry, render).attach !== "after"; + +/** + * The seconds a narrated item plays to by its read (`clip: "read"`): lead + + * the take + tail + linger. An attachment longer than this is cut to it. + */ +export function readSpanSeconds(entry, render) { + const t = pickedTake(entry); + if (!t) return null; + const k = postNarrationKnobs(entry, render); + return round3(k.lead + t.seconds + k.tail + k.linger); +} + +/** The postId a post item names (`<channel>/<postId>`). */ +export const postIdOf = (entry) => String(entry?.post ?? "").split("/")[1] ?? ""; + +/** Where a post's takes live in the project. */ +export const takesDirOf = (postId) => `narration/posts/${postId}`; +/** The project-relative file of take `n` (1-based) of a post. */ +export const takeFileOf = (postId, n, engine, voice) => `${takesDirOf(postId)}/take-${n}.${engine}-${voice}.wav`; +/** The index of the hand-made batch. */ +export const NARRATION_INDEX = "narration/posts/index.json"; + +/** The next take's number for a post: one past the highest `take-<n>.` already named. */ +export function nextTakeNumber(entry, files = []) { + let hi = 0; + const names = [...(entry?.narration?.takes ?? []).map((t) => t?.file), ...files]; + for (const f of names) { + const m = /take-(\d+)\./.exec(String(f ?? "")); + if (m) hi = Math.max(hi, Number(m[1])); + } + return hi + 1; +} + +/** + * THE MIX's SCHEDULE on the item's clock, for a narrated item: when the + * voice starts and ends, when the muffle ends and the clean sound is back. + * `seconds` the take's length. The render and Play both read this. + * + * @returns {{ at: number, seconds: number, voiceEnd: number, rampEnd: number, wet: number, lowpassHz: number, duck: boolean, attach: string, lufs: number }} + */ +export function narrationSchedule(entry, render) { + const t = pickedTake(entry); + const k = postNarrationKnobs(entry, render); + const seconds = t ? t.seconds : 0; + const voiceEnd = round3(k.lead + seconds + k.tail); + return { + at: round3(k.lead), + seconds: round3(seconds), + voiceEnd, + rampEnd: round3(voiceEnd + k.ramp), + wet: k.wet, + lowpassHz: k.lowpassHz, + // After the read, nothing plays under the voice: nothing to muffle. + duck: k.duck !== false && k.attach !== "after", + attach: k.attach, + lufs: k.lufs, + }; +} + +/** The muffled sound's gain at item second `t` (the wet branch). */ +export function wetGainAt(sch, t) { + if (!sch.duck) return 0; + if (t < sch.voiceEnd) return sch.wet; + const r = sch.rampEnd - sch.voiceEnd; + if (r > 0 && t < sch.rampEnd) return sch.wet * (1 - (t - sch.voiceEnd) / r); + return 0; +} + +/** The clean sound's gain at item second `t` (the dry branch). */ +export function dryGainAt(sch, t) { + if (!sch.duck) return 1; + if (t < sch.voiceEnd) return 0; + const r = sch.rampEnd - sch.voiceEnd; + if (r > 0 && t < sch.rampEnd) return (t - sch.voiceEnd) / r; + return 1; +} + +/** "muffled" | "ramp" | "clean": what Play and the bench say of the attachment's sound at `t`. */ +export function mixPhaseAt(sch, t) { + if (!sch.duck) return "clean"; + if (t < sch.voiceEnd) return "muffled"; + if (t < sch.rampEnd) return "ramp"; + return "clean"; +} + +/** A number for a filter argument: 6 decimals, no trailing zeros. */ +const f6 = (v) => { + const s = (Math.round(Number(v) * 1e6) / 1e6).toFixed(6).replace(/\.?0+$/, ""); + return s === "-0" ? "0" : s; +}; + +/** The levelling gain: the take measured at `measured` LUFS to the knob's `target`, held to ±12 dB; 0 unmeasured. */ +export function narrationLevelDb(measured, target) { + if (!fin(measured) || !fin(target)) return 0; + return Math.round(Math.max(-12, Math.min(12, target - measured)) * 100) / 100; +} + +/** + * THE MIX's FILTERS, pure (the mix.sh chain, inside the segment's graph): + * `media` the label of the item's own sound (its attachments' audio over + * silence, the item's length), `voice` the label of the take's input, `out` + * the label of the result. Returns the filter_complex parts. + * + * media -> asplit -> wet: lowpass F twice, gain W until voiceEnd, ramping to 0 over the ramp + * -> dry: 0 until voiceEnd, ramping to 1 over the ramp + * voice -> resampled, stereo, levelled, the narrator's compressor and make-up gain, delayed by lead + * wet + dry + voice -> amix (no normalising, the item's length) -> limiter + * + * Without `duck`, the media's sound plays as it is under the voice. + */ +export function postNarrationFilters({ media, voice, out, sch, gainDb = 0, audioRate = 48000 }) { + const E = f6(sch.voiceEnd); + const R = f6(Math.max(0.001, sch.rampEnd - sch.voiceEnd)); + const W = f6(sch.wet); + const F = Math.round(sch.lowpassHz); + const ms = Math.round(sch.at * 1000); + const parts = [ + `[${voice}]aresample=${audioRate},aformat=sample_fmts=fltp:channel_layouts=stereo,volume=${f6(gainDb)}dB,${POST_NARRATOR_COMPRESSOR},volume=${f6(POST_NARRATOR_MAKEUP)},adelay=${ms}:all=1[pnv]`, + ]; + if (sch.duck) { + parts.push( + `[${media}]asplit=2[pnd][pnw]`, + `[pnw]lowpass=f=${F},lowpass=f=${F},volume='if(lt(t,${E}),${W},if(lt(t,${E}+${R}),${W}*(1-(t-${E})/${R}),0))':eval=frame[pnwet]`, + `[pnd]volume='if(lt(t,${E}),0,if(lt(t,${E}+${R}),(t-${E})/${R},1))':eval=frame[pndry]`, + `[pnwet][pndry][pnv]amix=inputs=3:normalize=0:duration=first,alimiter=limit=${f6(POST_NARRATION_LIMIT)}[${out}]`, + ); + } else { + parts.push(`[${media}][pnv]amix=inputs=2:normalize=0:duration=first,alimiter=limit=${f6(POST_NARRATION_LIMIT)}[${out}]`); + } + return parts; +} + +// --------------------------------------------------------------------------- +// A script, drafted from the post's words. +// --------------------------------------------------------------------------- + +/** + * The post's words AS A VOICE READS THEM -- verbatim (operator, 2 Nov: "stick + * to the script!"), cleaned only for pronunciation: a repost's "RT @x:", + * @handles, links and emoji dropped; "plan(s)" read "plans", "w/" "with", + * "&" "and"; the spacing tidied. Nothing is cut: a shorter read is only ever + * the operator's own edit. + */ +export function speakableText(text) { + return String(text ?? "") + .replace(/^RT @[A-Za-z0-9_]+:\s*/, "") + .replace(/https?:\/\/\S+/g, " ") + .replace(/(^|[\s(])@[A-Za-z0-9_]{1,30}\b/g, "$1") + .replace(/[\p{Extended_Pictographic}\u{1F1E6}-\u{1F1FF}\u{FE0F}\u{200D}\u{20E3}]/gu, "") + .replace(/\b(\w+)\(s\)/g, "$1s") + .replace(/(^|\s)w\/(?=\s|$)/gi, "$1with") + .replace(/(^|\s)w\/(?=\S)/gi, "$1with ") + .replace(/\s&\s/g, " and ") + .replace(/&amp;/g, "and") + .replace(/[ \t]+/g, " ") + .replace(/\s*\n\s*/g, "\n") + .split("\n") + .map((l) => l.trim()) + .filter(Boolean) + // A line break is a pause: a line that ends unpunctuated gets its full stop. + .map((l, i, all) => (i < all.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(l) ? `${l}.` : l)) + .join(" ") + .replace(/\s+([,.!?;:])/g, "$1") + .replace(/^[,.;:]\s*/, "") + .trim(); +} + +/** + * A DRAFT SCRIPT from the post's words: the whole post (speakableText), never + * an excerpt. Emotion is the operator's to add (Orpheus's tags, <sigh> …). + * + * @returns {{ script: string, words: number }} + */ +export function draftScript(text) { + const script = speakableText(text); + return { script, words: script ? script.split(/\s+/).length : 0 }; +} + +// --------------------------------------------------------------------------- +// The validator. +// --------------------------------------------------------------------------- + +function relFile(v, what) { + if (typeof v !== "string" || !v.trim()) return `${what} must be a file path relative to the manifest`; + if (v.startsWith("/") || v.startsWith("~") || /^[A-Za-z]:[\\/]/.test(v) || v.split(/[\\/]/).includes("..")) return `${what} must stay inside the project: ${v}`; + if (!/\.(wav|mp3|m4a|flac|ogg)$/i.test(v)) return `${what} must be a sound file (wav, mp3, m4a, flac, ogg): ${v}`; + return null; +} + +function scriptErrors(s, where) { + if (typeof s !== "string") return [`${where} must be the words to read (a string)`]; + const errors = []; + if (s.length > POST_NARRATION_LIMITS.scriptChars) errors.push(`${where} is longer than ${POST_NARRATION_LIMITS.scriptChars} characters`); + for (const m of s.matchAll(/<([^<>]*)>/g)) { + if (!TAGS.includes(m[1])) errors.push(`${where}: <${m[1]}> is not an expressive tag (${TAGS.map((t) => `<${t}>`).join(" ")})`); + } + return errors; +} + +function mixErrors(o, where) { + const errors = []; + for (const k of ["lead", "tail", "ramp", "linger", "wet", "lowpassHz", "lufs"]) { + if (o[k] !== undefined && !numIn(o[k], POST_NARRATION_LIMITS[k])) errors.push(`${where}.${k} must be ${POST_NARRATION_LIMITS[k][0]}–${POST_NARRATION_LIMITS[k][1]}`); + } + if (o.duck !== undefined && typeof o.duck !== "boolean") errors.push(`${where}.duck must be true or false`); + if (o.clip !== undefined && !POST_NARRATION_CLIP.includes(o.clip)) errors.push(`${where}.clip must be ${POST_NARRATION_CLIP.join(" or ")}`); + if (o.short !== undefined && !POST_NARRATION_SHORT.includes(o.short)) errors.push(`${where}.short must be ${POST_NARRATION_SHORT.join(" or ")}`); + if (o.attach !== undefined && !POST_NARRATION_ATTACH.includes(o.attach)) errors.push(`${where}.attach must be ${POST_NARRATION_ATTACH.join(" or ")}`); + if (o.engine !== undefined && !POST_NARRATION_ENGINES.includes(o.engine)) errors.push(`${where}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); + if (o.voice !== undefined && (typeof o.voice !== "string" || !VOICE_RE.test(o.voice))) errors.push(`${where}.voice must be a stock voice's id`); + return errors; +} + +/** Every reason `render.postNarration` cannot be built. */ +export function validatePostNarrationRender(render) { + const r = render?.postNarration; + if (r === undefined || r === null) return []; + if (!isObj(r)) return ["render.postNarration must be an object of the mix's knobs"]; + const errors = []; + for (const k of Object.keys(r)) if (!RENDER_KEYS.has(k)) errors.push(`render.postNarration.${k} is not a knob (${[...RENDER_KEYS].join(", ")})`); + return [...errors, ...mixErrors(r, "render.postNarration")]; +} + +/** Every reason one post item's `narration` cannot be built (empty: it can). */ +export function validatePostNarration(e) { + const n = e?.narration; + if (n === undefined) return []; + const w = `timeline ${e?.id ?? "?"}.narration`; + if (!isObj(n)) return [`${w} must be an object ({ script, takes, pick, … })`]; + const errors = []; + for (const k of Object.keys(n)) if (!ITEM_KEYS.has(k)) errors.push(`${w}.${k} is not a narration key`); + if (n.script !== undefined) errors.push(...scriptErrors(n.script, `${w}.script`)); + for (const k of ["excerpt", "approved", "off"]) if (n[k] !== undefined && typeof n[k] !== "boolean") errors.push(`${w}.${k} must be true or false`); + if (n.speed !== undefined && !numIn(n.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${w}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); + if (n.window !== undefined) { + const x = n.window; + if (!isObj(x) || !Number.isInteger(x.media) || !fin(x.start) || !fin(x.end) || x.end <= x.start || (x.score !== undefined && !fin(x.score)) || (x.reason !== undefined && typeof x.reason !== "string")) { + errors.push(`${w}.window must be { media, start, end, score?, reason?, at? } (posts fit's choice)`); + } + } + errors.push(...mixErrors(n, w)); + if (n.takes !== undefined) { + if (!Array.isArray(n.takes)) errors.push(`${w}.takes must be a list`); + else { + if (n.takes.length > POST_NARRATION_LIMITS.takes) errors.push(`${w}.takes: at most ${POST_NARRATION_LIMITS.takes}`); + n.takes.forEach((t, i) => { + const tw = `${w}.takes[${i}]`; + if (!isObj(t)) { + errors.push(`${tw} must be an object`); + return; + } + for (const k of Object.keys(t)) if (!TAKE_KEYS.has(k)) errors.push(`${tw}.${k} is not a take key`); + const fe = relFile(t.file, `${tw}.file`); + if (fe) errors.push(fe); + if (!(fin(t.seconds) && t.seconds > 0 && t.seconds <= 600)) errors.push(`${tw}.seconds must be its length (measured when it came in)`); + if (t.engine !== undefined && !POST_TAKE_ENGINES.includes(t.engine)) errors.push(`${tw}.engine must be one of ${POST_TAKE_ENGINES.join(", ")}`); + if (t.voice !== undefined && (typeof t.voice !== "string" || !VOICE_RE.test(t.voice))) errors.push(`${tw}.voice must be a stock voice's id`); + if (t.script !== undefined && typeof t.script !== "string") errors.push(`${tw}.script must be the words it read`); + for (const k of ["note", "at", "jobId"]) if (t[k] !== undefined && typeof t[k] !== "string") errors.push(`${tw}.${k} must be a string`); + if (t.lufs !== undefined && t.lufs !== null && !fin(t.lufs)) errors.push(`${tw}.lufs must be a number`); + if (t.speed !== undefined && !numIn(t.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${tw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")}`); + if (t.label !== undefined && (typeof t.label !== "string" || !VOICE_RE.test(t.label))) errors.push(`${tw}.label must be a short name (a recorded voice's)`); + if (t.parts !== undefined) { + // A take COMPOSED OF PARTS (a long post read paragraph by paragraph): the joined file is the take's. + if (!Array.isArray(t.parts) || t.parts.length > 200) errors.push(`${tw}.parts must be a list (at most 200)`); + else t.parts.forEach((p, k) => { + const pw = `${tw}.parts[${k}]`; + if (!isObj(p)) return errors.push(`${pw} must be an object`); + for (const key of Object.keys(p)) if (!PART_KEYS.has(key)) errors.push(`${pw}.${key} is not a part key`); + if (p.file !== undefined) { + const pe = relFile(p.file, `${pw}.file`); + if (pe) errors.push(pe); + } + 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 (n.pick !== undefined && !(Number.isInteger(n.pick) && n.pick >= 0 && Array.isArray(n.takes) && n.pick < n.takes.length)) { + errors.push(`${w}.pick must be the index of one of its takes (0–${Math.max(0, (n.takes?.length ?? 1) - 1)})`); + } + return errors; +} + +/** The take files a post item's narration names, as `{ where, src }` (the lint checks each is there). */ +export function postNarrationFiles(entry) { + const takes = Array.isArray(entry?.narration?.takes) ? entry.narration.takes : []; + const w = `timeline ${entry?.id ?? "?"}.narration`; + // Only the one that plays must be there to build; the rest may have been pruned. + const t = takes.length && isNarrated(entry) ? pickedTake(entry) : null; + return t ? [{ where: `${w}.takes[${t.index}]`, src: t.file }] : []; +} + +/** The disclosure line a narrated post item's cut carries (narration.mjs's wording). */ +export function postNarrationDisclosure(entry) { + const t = pickedTake(entry); + if (!t || !isNarrated(entry)) return null; + // A recorded take is a person's own voice: nothing synthetic to disclose. + if (t.engine === "recorded") return null; + const label = { orpheus: "Orpheus", kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG" }[t.engine] ?? t.engine ?? "a stock voice"; + return `Narration: synthetic voice (${label} · ${t.voice ?? "?"})`; +} diff --git a/umtool/report-to-video/post-narration.test.mjs b/umtool/report-to-video/post-narration.test.mjs @@ -0,0 +1,200 @@ +// post-narration.mjs + post-item.mjs's narrated branch: the knobs, the plan +// of a narrated post (the demo's timings), the mix's schedule and its +// ffmpeg filters, the verbatim script, the validator. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + POST_NARRATION_DEFAULTS, draftScript, dryGainAt, isNarrated, mixPhaseAt, narrationLevelDb, narrationSchedule, + nextTakeNumber, pickedTake, postNarrationDisclosure, postNarrationFilters, postNarrationKnobs, readSpanSeconds, speakableText, takeFileOf, + validatePostNarration, validatePostNarrationRender, wetGainAt, +} from "./post-narration.mjs"; +import { POST_PICTURE_MIN, mediaTimeAt, postItemFiles, postItemPlan, postItemSeconds, postLayout, ruleSeconds, validatePostItem } from "./post-item.mjs"; +import { postSegmentArgs } from "./post-render.mjs"; +import { estimatedDuration } from "./deck.mjs"; + +const post = (o = {}) => ({ + type: "post", id: "p-1", post: "someone-x/2117259673917386879", platform: "x", + author: "MR. OBVIOUS", handle: "ObviousRises", date: "2026-11-02T14:16:57.000Z", + text: "I'm tired of hearing about it. Do I need to make an example of her? I'm so irritated.", ...o, +}); +const video = (o = {}) => ({ src: "posts-media/x/1/1_1.mp4", kind: "video", seconds: 9.293, width: 1280, height: 720, audio: true, ...o }); +const image = (o = {}) => ({ src: "posts-media/x/1/1_1.jpg", kind: "image", width: 1200, height: 900, ...o }); +const narr = (seconds, o = {}) => ({ script: "words", takes: [{ file: "narration/posts/2117259673917386879/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds }], pick: 0, ...o }); +/** The demo's knobs (narr-demo/mix.sh): the whole clip, 0.4 s clean after the ramp. */ +const DEMO = { postNarration: { clip: "full", linger: 1.2 } }; + +test("the defaults are the demo's numbers, and a post's own knobs win over the cut's", () => { + assert.deepEqual( + { lead: POST_NARRATION_DEFAULTS.lead, tail: POST_NARRATION_DEFAULTS.tail, ramp: POST_NARRATION_DEFAULTS.ramp, wet: POST_NARRATION_DEFAULTS.wet, lowpassHz: POST_NARRATION_DEFAULTS.lowpassHz }, + { lead: 0.4, tail: 0.3, ramp: 0.8, wet: 0.3, lowpassHz: 650 }, + ); + assert.equal(POST_NARRATION_DEFAULTS.engine, "orpheus"); + assert.equal(POST_NARRATION_DEFAULTS.voice, "zac"); + assert.equal(POST_NARRATION_DEFAULTS.short, "hold"); + const e = post({ narration: narr(10, { wet: 0.2 }) }); + const k = postNarrationKnobs(e, { postNarration: { wet: 0.5, lead: 1 } }); + assert.equal(k.wet, 0.2); + assert.equal(k.lead, 1); + assert.equal(k.attach, "under"); +}); + +test("which take plays: the picked one, else the first; off or none is not narrated", () => { + const two = narr(5); + two.takes.push({ file: "narration/posts/2117259673917386879/take-2.orpheus-zac.wav", seconds: 7 }); + assert.equal(pickedTake(post({ narration: { ...two, pick: 1 } })).seconds, 7); + assert.equal(pickedTake(post({ narration: { ...two, pick: undefined } })).seconds, 5); + assert.equal(isNarrated(post({ narration: { ...two, off: true } })), false); + assert.equal(isNarrated(post({ narration: { script: "x", takes: [] } })), false); + assert.equal(isNarrated(post()), false); + assert.equal(nextTakeNumber(post({ narration: two }), ["take-7.kokoro-af_heart.wav"]), 8); + assert.equal(takeFileOf("123", 2, "orpheus", "zac"), "narration/posts/123/take-2.orpheus-zac.wav"); +}); + +test("THE DEMO's TIMINGS: with clip full and linger 1.2 the plans are mix.sh's segments, the video at once", () => { + // narr-demo: 30.03 s video under a 13.71 s read; 9.293 s video under 18.42 s (held); 17.926 s under 11.58 s. + const a = postItemPlan(post({ media: [video({ seconds: 30.03 })], narration: narr(13.71) }), DEMO); + assert.equal(a.total, 30.03); + assert.equal(a.reading, 0); + assert.equal(a.steps[0].at, 0); + const b = postItemPlan(post({ media: [video()], narration: narr(18.42) }), DEMO); + assert.equal(b.total, 20.32); + assert.equal(b.held, 11.027); + assert.deepEqual([b.narration.at, b.narration.voiceEnd, b.narration.rampEnd], [0.4, 19.12, 19.92]); + const c = postItemPlan(post({ media: [video({ seconds: 17.926 })], narration: narr(11.58) }), DEMO); + assert.equal(c.total, 17.926); +}); + +test("NO LINGERING (the default): the item ends linger after the words; a longer video is cut to the read", () => { + const e = post({ media: [video({ seconds: 30.03 })], narration: narr(13.71) }); + const p = postItemPlan(e); + assert.equal(readSpanSeconds(e), 16.21); + assert.equal(p.total, 16.21); + assert.equal(p.steps[0].seconds, 16.21); + assert.equal(p.steps[0].srcFrom, 0); + // Its in point (or posts fit's best window) is where it plays from; an out point set is kept as the choice. + const w = postItemPlan(post({ media: [video({ seconds: 30.03, start: 12, end: 28.2 })], narration: narr(13.71) })); + assert.deepEqual([w.steps[0].srcFrom, w.steps[0].seconds, w.total], [12, 16.2, 16.21]); + assert.equal(postItemSeconds(e), 16.21); + assert.equal(estimatedDuration(e, {}), 16.21); + // A per-post linger. + assert.equal(postItemPlan(post({ media: [video({ seconds: 30.03 })], narration: narr(13.71, { linger: 4 }) })).total, 18.41); +}); + +test("a short video holds its last frame, or loops (short: loop)", () => { + const held = postItemPlan(post({ media: [video()], narration: narr(18.42) })); + assert.equal(held.total, 20.92); + assert.ok(held.held > 11); + const looped = postItemPlan(post({ media: [video()], narration: narr(18.42, { short: "loop" }) })); + assert.equal(looped.held, 0); + assert.equal(looped.steps[0].loop, true); + assert.equal(looped.steps[0].seconds, 20.92); + // On its clock it comes round again. + assert.equal(mediaTimeAt(looped.steps[0], 10), 0.707); +}); + +test("PICTURES RUN WITH THE READ: shared out over its span, each at least the minimum, not 3.5 s after it", () => { + const one = post({ media: [image()], narration: narr(6) }); + const un = post({ media: [image()] }); + assert.ok(ruleSeconds(un) > 6.4); + const p = postItemPlan(one); + assert.equal(p.total, 8.5); + assert.deepEqual(p.steps.map((s) => [s.at, s.seconds]), [[0, 8.5]]); + const four = postItemPlan(post({ media: [image(), image(), image(), image()], narration: narr(2) })); + assert.equal(four.steps.length, 4); + for (const s of four.steps) assert.equal(s.seconds, POST_PICTURE_MIN); + assert.equal(four.total, 4 * POST_PICTURE_MIN); + // A text-only post: the read and the linger. + assert.equal(postItemPlan(post({ narration: narr(5) })).total, 7.5); +}); + +test("the words stay on screen: a post with attachments is laid out beside them, narrated or not", () => { + const long = "word ".repeat(220).trim(); + const box = { width: 1574, height: 886 }; + assert.equal(postLayout(post({ text: long, media: [image()] }), box).mode, "side"); + assert.equal(postLayout(post({ text: long, media: [image()], narration: narr(30) }), box).mode, "side"); +}); + +test("attach after: the read over the card, then the attachments clean", () => { + const p = postItemPlan(post({ media: [video()], narration: narr(5, { attach: "after" }) })); + assert.equal(p.reading, 5.7); + assert.equal(p.steps[0].at, 5.7); + assert.equal(p.total, 14.993); + assert.equal(p.narration.duck, false); +}); + +test("the mix's schedule: muffled under the read, a linear ramp back, clean after", () => { + const sch = narrationSchedule(post({ media: [video()], narration: narr(10) })); + assert.deepEqual([sch.at, sch.voiceEnd, sch.rampEnd], [0.4, 10.7, 11.5]); + assert.equal(wetGainAt(sch, 1), 0.3); + assert.equal(dryGainAt(sch, 1), 0); + assert.equal(mixPhaseAt(sch, 1), "muffled"); + assert.ok(Math.abs(wetGainAt(sch, 11.1) - 0.15) < 1e-9); + assert.ok(Math.abs(dryGainAt(sch, 11.1) - 0.5) < 1e-9); + assert.equal(mixPhaseAt(sch, 11.1), "ramp"); + assert.equal(wetGainAt(sch, 12), 0); + assert.equal(dryGainAt(sch, 12), 1); + assert.equal(mixPhaseAt(sch, 12), "clean"); + const flat = narrationSchedule(post({ media: [video()], narration: narr(10, { duck: false }) })); + assert.equal(dryGainAt(flat, 1), 1); + assert.equal(mixPhaseAt(flat, 1), "clean"); +}); + +test("THE MIX's FILTERS are mix.sh's chain: lowpass 650 twice at 0.30, the ramp, the narrator delayed by the lead", () => { + const sch = narrationSchedule(post({ media: [video()], narration: narr(18.42) })); + const f = postNarrationFilters({ media: "pm", voice: "5:a", out: "a", sch, gainDb: 0.3 }); + assert.deepEqual(f, [ + "[5:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,volume=0.3dB,acompressor=threshold=0.1:ratio=3:attack=5:release=120,volume=1.5,adelay=400:all=1[pnv]", + "[pm]asplit=2[pnd][pnw]", + "[pnw]lowpass=f=650,lowpass=f=650,volume='if(lt(t,19.12),0.3,if(lt(t,19.12+0.8),0.3*(1-(t-19.12)/0.8),0))':eval=frame[pnwet]", + "[pnd]volume='if(lt(t,19.12),0,if(lt(t,19.12+0.8),(t-19.12)/0.8,1))':eval=frame[pndry]", + "[pnwet][pndry][pnv]amix=inputs=3:normalize=0:duration=first,alimiter=limit=0.95[a]", + ]); + assert.equal(narrationLevelDb(-21.3, -21), 0.3); + assert.equal(narrationLevelDb(null, -21), 0); + assert.equal(narrationLevelDb(-50, -21), 12); +}); + +test("the segment's argv carries the take as an input and the mix after the item's own sound", () => { + const e = post({ media: [video()], narration: narr(18.42) }); + const plan = postItemPlan(e); + const box = { width: 1574, height: 886 }; + const argv = postSegmentArgs({ + entry: e, box, plan, layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: ["/p/v.mp4"], + render: { fps: 30, audioRate: 48000 }, outPath: "/o.mp4", narration: { file: "/p/take.wav", gainDb: 0 }, + }); + const fc = argv[argv.indexOf("-filter_complex") + 1]; + assert.ok(argv.includes("/p/take.wav")); + assert.match(fc, /amix=inputs=2:normalize=0:duration=first\[pm\]/); + assert.match(fc, /\[pnwet\]\[pndry\]\[pnv\]amix=inputs=3/); + assert.equal(argv[argv.indexOf("-t", argv.indexOf("-map")) + 1], String(plan.total)); + // Un-narrated: as it was. + const bare = postSegmentArgs({ entry: post({ media: [video()] }), box, plan: postItemPlan(post({ media: [video()] })), layout: postLayout(post({ media: [video()] }), box), cards: { read: "/c/read.png" }, files: ["/p/v.mp4"], render: { fps: 30 }, outPath: "/o.mp4" }); + assert.doesNotMatch(bare[bare.indexOf("-filter_complex") + 1], /pnv|lowpass/); +}); + +test("SCRIPTS ARE THE POST, VERBATIM: cleaned for pronunciation only, never an excerpt", () => { + assert.equal(speakableText("@KorriiNami Trust me & you w/ my plan(s) 😂 https://t.co/x\n\nI hate the weak"), "Trust me and you with my plans. I hate the weak"); + const long = Array.from({ length: 150 }, (_, i) => `w${i}`).join(" ") + ". The end."; + const d = draftScript(long); + assert.equal(d.words, 152); + assert.ok(d.script.endsWith("The end.")); + assert.equal(draftScript("RT @someone: hello there").script, "hello there"); +}); + +test("the validator: shapes, tags, takes, the pick, the cut's knobs; the build's files", () => { + assert.deepEqual(validatePostNarration(post({ narration: narr(5) })), []); + const bad = validatePostNarration(post({ narration: { script: "hi <whisper>", takes: [{ file: "/abs.wav", seconds: -1 }], pick: 3, wet: 2, short: "freeze", bogus: 1 } })); + assert.ok(bad.some((e) => e.includes("<whisper> is not an expressive tag"))); + assert.ok(bad.some((e) => e.includes("takes[0].file must stay inside the project"))); + assert.ok(bad.some((e) => e.includes("takes[0].seconds"))); + assert.ok(bad.some((e) => e.includes(".pick must be the index"))); + assert.ok(bad.some((e) => e.includes(".wet must be 0–1"))); + assert.ok(bad.some((e) => e.includes(".short must be hold or loop"))); + assert.ok(bad.some((e) => e.includes(".bogus is not a narration key"))); + assert.ok(validatePostItem(post({ narration: { script: 3 } })).some((e) => e.includes("narration.script"))); + assert.deepEqual(validatePostNarrationRender({ postNarration: { wet: 0.2, linger: 2, clip: "full" } }), []); + assert.ok(validatePostNarrationRender({ postNarration: { attach: "after" } }).some((e) => e.includes("attach is not a knob"))); + assert.deepEqual(postItemFiles(post({ narration: narr(5) })).map((f) => f.src), ["narration/posts/2117259673917386879/take-1.orpheus-zac.wav"]); + assert.deepEqual(postItemFiles(post({ narration: narr(5, { off: true }) })), []); + assert.equal(postNarrationDisclosure(post({ narration: narr(5) })), "Narration: synthetic voice (Orpheus · zac)"); +}); diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -18,7 +18,8 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; +import { POST_PICTURE_XFADE, POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; +import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters } from "./post-narration.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); @@ -61,7 +62,7 @@ export function stepCaptions(step, cues) { * * @returns {string[]} */ -export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath }) { +export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null }) { const fps = render.fps ?? 30; const T = plan.total; const inputs = []; @@ -85,9 +86,14 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render lay("mc", 0, 0, plan.steps[0].at, T); } const audio = []; + const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif"); plan.steps.forEach((step, si) => { const last = si === plan.steps.length - 1; - const until = last ? T : step.at + step.seconds; + // Pictures cycle like a video: the next one crossfades in over this one, which stays up under it. + const xfIn = si > 0 && picture(step) && picture(plan.steps[si - 1]) ? POST_PICTURE_XFADE : 0; + const xfOut = !last && picture(step) && picture(plan.steps[si + 1]) ? POST_PICTURE_XFADE : 0; + const until = last ? T : Math.min(T, step.at + step.seconds + xfOut); + const fadeIn = (from) => (xfIn ? `,format=rgba,fade=t=in:st=${num(from)}:d=${num(xfIn)}:alpha=1` : ""); // Beside the card, the first attachment is up from the first frame (its first frame while the words are read). const shownFrom = si === 0 && layout.mode === "side" ? 0 : step.at; const boxes = stepBoxes(step, layout.slot); @@ -96,18 +102,18 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render const file = files[m.i]; const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : ""; const label = `m${si}_${j}`; - if (step.kind === "image") { + if (step.kind === "image" || step.kind === "grid") { if (m.push === true) { const frames = Math.max(1, Math.round((until - shownFrom) * fps)); const k = add(["-i", file]); parts.push( `[${k}:v]${crop}scale=${b.width * 2}:${b.height * 2},setsar=1,` + `zoompan=z='1+${POST_PUSH}*on/${frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${b.width}x${b.height}:fps=${fps},` + - `setpts=PTS-STARTPTS+${num(shownFrom)}/TB[${label}]`, + `setpts=PTS-STARTPTS+${num(shownFrom)}/TB${fadeIn(shownFrom)}[${label}]`, ); } else { const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]); - parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}[${label}]`); + parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${label}]`); } } else { // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays. @@ -142,10 +148,16 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render } 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"; 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[a]`); - } else parts.push(`[${sil}:a]anull[a]`); + parts.push(`[${sil}:a]${audio.map((a) => `[${a.label}]`).join("")}amix=inputs=${audio.length + 1}:normalize=0:duration=first[${media}]`); + } else parts.push(`[${sil}:a]anull[${media}]`); + if (media === "pm") { + const vi = add(["-i", narration.file]); + parts.push(...postNarrationFilters({ media: "pm", voice: `${vi}:a`, out: "a", sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 })); + } return [ "-nostdin", "-v", "error", "-y", ...inputs, @@ -174,7 +186,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 }) { +export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {} }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -189,7 +201,10 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); for (const phase of phases) { - const html = postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl }); + const html = postCardHtml(entry, { + width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl, + avatars: Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])), + }); const file = path.join(dir, `${phase}.html`); await writeFile(file, html, "utf8"); await page.goto(pathToFileURL(file).href, { waitUntil: "load" }); @@ -207,25 +222,30 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la /** * Build post item `entry`'s segment. `ctx`: `{ render, outDir, manifestDir, - * box, place, encode, exec, ffmpeg, emit }` -- the box it fills (the deck's - * footage box, or the frame), the deck's framing after it, build-video's - * encode args and ffmpeg runner. Returns the segment's path. + * box, place, encode, exec, ffmpeg, emit, avatars }` -- the box it fills (the + * deck's footage box, or the frame), the deck's framing after it, + * build-video's encode args and ffmpeg runner, the authors' pictures + * (`{ <handle>: absolute file }`, post-avatars.mjs). Returns the segment's path. */ -export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {} }) { +export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {} }) { const seg = path.join(outDir, "segments", `${entry.id}.mp4`); - const plan = postItemPlan(entry); + const plan = postItemPlan(entry, render); const layout = postLayout(entry, box); const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src)); for (const [i, f] of files.entries()) { if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: media[${i}] is not on disk: ${f} (src: ${entry.media[i].src})`); } const wordFiles = (entry.media ?? []).map((m) => (typeof m.words === "string" ? path.resolve(manifestDir, m.words) : null)); - const stamps = await Promise.all([...files, ...wordFiles.filter(Boolean), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => { + // Its narration's picked take (post-narration.mjs): a file of the project, levelled by its measured loudness. + const take = isNarrated(entry) ? pickedTake(entry) : null; + const takeFile = take ? path.resolve(manifestDir, take.file) : null; + if (takeFile && !(await stat(takeFile).catch(() => null))) throw new Error(`${entry.id}: its narration take is not on disk: ${takeFile} (${take.file})`); + const stamps = await Promise.all([...files, ...wordFiles.filter(Boolean), ...Object.values(avatars), ...(takeFile ? [takeFile] : []), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => { const st = await stat(f).catch(() => null); return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`; })); const key = createHash("sha256") - .update(JSON.stringify({ v: 1, entry, box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps })) + .update(JSON.stringify({ v: 1, entry, box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}) })) .digest("hex"); const record = postRecordPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); @@ -234,7 +254,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box return seg; } const cardDir = path.join(outDir, "cards", `post-${entry.id}`); - const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout }); + const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars }); // Its video attachments' words, when transcribed: one textfile per cue. const captions = []; for (const [si, step] of plan.steps.entries()) { @@ -249,7 +269,12 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box } } const tmp = seg.replace(/\.mp4$/, ".post-tmp.mp4"); - const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp }); + let narration = null; + if (take) { + const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg }); + narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs }; + } + const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { @@ -257,7 +282,23 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box throw new Error(`${entry.id}: ffmpeg failed on the post item\n${detail}`); } await rename(tmp, seg); - await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length }, null, 2) + "\n", "utf8"); - emit("note", { message: `${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)` : ""})` }); + await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs } } : {}) }, null, 2) + "\n", "utf8"); + emit("note", { + message: narration + ? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)` + : `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`, + }); return seg; } + +/** A sound's integrated loudness (EBU R128, LUFS) by ffmpeg's ebur128 through `exec`; null when silent or unread. */ +export async function measureLufsOf(file, { exec, ffmpeg = "ffmpeg" }) { + try { + const r = await exec(ffmpeg, ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], { maxBuffer: 1 << 24 }); + const all = [...String(r?.stderr ?? "").matchAll(/\bI:\s+(-?[\d.]+|-inf)\s+LUFS/g)]; + const v = all.length ? Number(all.at(-1)[1]) : NaN; + return Number.isFinite(v) && v > -70 ? v : null; + } catch { + return null; + } +} diff --git a/umtool/report-to-video/post-render.test.mjs b/umtool/report-to-video/post-render.test.mjs @@ -24,39 +24,46 @@ const argsOf = (e) => { return { plan, layout, argv, graph: argv[argv.indexOf("-filter_complex") + 1] }; }; -test("the render plan: the card, the video from its trim with its sound delayed to its step, the image after it, the deck's framing", () => { +test("the render plan: the card the whole time, the video from its trim at once with its sound, the image after it, the deck's framing", () => { const { plan, argv, graph } = argsOf(entry()); - assert.equal(plan.total, 3 + 3 + 3.5); - // The card for the whole item, the video's trimmed span, the image held to the end, silence under all. - assert.deepEqual(argv.slice(argv.indexOf("-i") - 6, argv.indexOf("-i") + 2), ["-loop", "1", "-framerate", "30", "-t", "9.5", "-i", "/c/read.png"]); + // A 3 s read: the video's 3 s trim, then the image at the minimum. + assert.equal(plan.total, 3 + 1.5); + assert.deepEqual(argv.slice(argv.indexOf("-i") - 6, argv.indexOf("-i") + 2), ["-loop", "1", "-framerate", "30", "-t", "4.5", "-i", "/c/read.png"]); const v = argv.indexOf("/m/v.mp4"); assert.deepEqual(argv.slice(v - 5, v + 1), ["-ss", "1", "-t", "3", "-i", "/m/v.mp4"]); assert.ok(argv.includes("/m/i.jpg")); - // Beside the card, the video's first frame is up while the words are read; it plays at 3 s. - assert.match(graph, /tpad=start_duration=3:start_mode=clone/); - assert.match(graph, /overlay=x=\d+:y=\d+:enable='between\(t,0,6\)'/); - assert.match(graph, /overlay=x=\d+:y=\d+:enable='between\(t,6,9.5\)'/); - // Its sound from the step's start, mixed over the silence. - assert.match(graph, /adelay=3000\|3000\[a0\]/); + // The video plays from the first frame, beside the card. + assert.match(graph, /tpad=start_duration=0:start_mode=clone/); + assert.match(graph, /overlay=x=\d+:y=\d+:enable='between\(t,0,3\)'/); + assert.match(graph, /overlay=x=\d+:y=\d+:enable='between\(t,3,4.5\)'/); + assert.match(graph, /adelay=0\|0\[a0\]/); assert.match(graph, /amix=inputs=2:normalize=0:duration=first\[a\]/); assert.match(graph, /pad=1920:1080:240:10:color=#000,setsar=1,fps=30\[v\];/); - assert.deepEqual(argv.slice(-3), ["-t", "9.5", "/o/p1.mp4"]); + assert.deepEqual(argv.slice(-3), ["-t", "4.5", "/o/p1.mp4"]); }); -test("a muted video plays silent; a text-only post is the card alone; a stack lays the media page over the card when the media starts", () => { +test("a muted video plays silent; a text-only post is the card alone; a long post keeps its words beside the media; pictures crossfade", () => { const muted = argsOf(entry({ media: [{ src: "m/v.mp4", kind: "video", seconds: 6, width: 1920, height: 1080, mute: true }] })); assert.match(muted.graph, /\[\d+:a\]anull\[a\]/); const text = argsOf(entry({ media: undefined })); assert.equal(text.argv.filter((a) => a === "-i").length, 2); // the card and the silence const long = Array.from({ length: 480 }, () => "word").join(" "); - const stack = argsOf(entry({ text: long })); - assert.equal(stack.layout.mode, "stack"); - assert.ok(stack.argv.includes("/c/media.png")); - assert.match(stack.graph, new RegExp(`\\[mc\\]overlay=x=0:y=0:enable='between\\(t,${stack.plan.reading},`)); + const side = argsOf(entry({ text: long })); + assert.equal(side.layout.mode, "side"); + assert.ok(!side.argv.includes("/c/media.png")); + // Four pictures cycle: each after the first fades in over the one before, which stays up under it. + const img = (n) => ({ src: `m/${n}.jpg`, kind: "image", width: 1000, height: 1000 }); + const e = entry({ media: [img(1), img(2), img(3), img(4)] }); + const plan = postItemPlan(e); + const argv = postSegmentArgs({ entry: e, box, plan, layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: ["/m/1.jpg", "/m/2.jpg", "/m/3.jpg", "/m/4.jpg"], render, outPath: "/o.mp4" }); + const g = argv[argv.indexOf("-filter_complex") + 1]; + assert.equal((g.match(/fade=t=in/g) ?? []).length, 3); + assert.match(g, /fade=t=in:st=1.5:d=0.3:alpha=1/); + assert.match(g, /enable='between\(t,0,1.8\)'/); }); test("a video attachment's transcript, on the item's clock", () => { const plan = postItemPlan(entry()); const caps = stepCaptions(plan.steps[0], [{ start: 0, end: 1.5, text: "before" }, { start: 1.5, end: 2.5, text: "said" }, { start: 5, end: 6, text: "after" }]); - assert.deepEqual(caps.map((c) => [c.text, c.from, c.to]), [["before", 3, 3.5], ["said", 3.5, 4.5]]); + assert.deepEqual(caps.map((c) => [c.text, c.from, c.to]), [["before", 0, 0.5], ["said", 0.5, 1.5]]); });