Archilyzer · Source

archilyzer

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

commit 4a428b2be0375d340e279c0c2039034101c5be30
parent b52059487aa60616520f0c1e12428b61e9aa932a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue,  3 Nov 2026 01:26:51 -0500

Merge lane/post-narration: narrated post items -- the recording session (record the narration part by part over a teleprompter, resumable, joined, levelled and picked), the narration mixed inside the build (the attachment muffled under the read), one layout (the text up the whole item, media beside it as one sequence), the read-paced timing and the best-window fit, avatars on cards, takes as a source plus steps (derived takes), posts narrate/fit/avatar(s)

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

Diffstat:
Mplans/post-videos.md | 24+++++++++++++++++++++++-
Mumtool/app/api/report/file/route.ts | 2+-
Mumtool/app/api/report/post-item/route.ts | 5++++-
Aumtool/app/api/report/post-narration/record/route.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/post-narration/route.ts | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 7+++++++
Mumtool/components/projects/PostBench.tsx | 46+++++++++++++++++++++++++++++++++++++++-------
Mumtool/components/projects/PostBenchPage.tsx | 3++-
Aumtool/components/projects/PostNarrationPanel.tsx | 706+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ProjectView.tsx | 3+++
Aumtool/components/projects/RecordPage.tsx | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/RecordSession.tsx | 401+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/bench/benchMedia.ts | 26++++++++++++++++++++++++++
Mumtool/components/projects/report/CutTab.tsx | 8+++++++-
Mumtool/components/projects/review/PostItemPlayer.tsx | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aumtool/components/projects/useMic.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 5++++-
Mumtool/docs/knobs.md | 34++++++++++++++++++++++++++++++++--
Mumtool/docs/report-video.md | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/e2e/fixtures/editor-stub.mjs | 12+++++++++---
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/post-narration-fixture.mjs | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/post-items.spec.ts | 31+++++++++++++++++--------------
Aumtool/e2e/post-narration.spec.ts | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 5+++++
Mumtool/lib/report/manifest.mjs | 226++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/playView.mjs | 6+++---
Aumtool/lib/report/postFit.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postNarration.test.mjs | 320+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postNarrationCli.mjs | 536+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postRecord.mjs | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postReel.mjs | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/postsCli.mjs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/report/recordSession.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 | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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 | 187++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mumtool/report-to-video/post-item.test.mjs | 55+++++++++++++++++++++++++++++++++----------------------
Aumtool/report-to-video/post-narration.mjs | 585+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-narration.test.mjs | 201+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mumtool/report-to-video/post-render.test.mjs | 41++++++++++++++++++++++++-----------------
51 files changed, 5485 insertions(+), 172 deletions(-)

diff --git a/plans/post-videos.md b/plans/post-videos.md @@ -14,7 +14,7 @@ for this whole post video flow"; for now the videos come first and code waits. | 2. Select | a date window and which posts belong | `posts reel --since/--until/--own/--replies` | the story / conduct / out classification as a generation task with reasons, reviewed Yes/No on a page (done by hand for mr-obvious: `classified.jsonl`) | | 3. Storyline | sections in time order, labelled | `timeline section-add`, `deck.sectionTitle` | a storyline draft from the classification (sections + a STORYLINE.md) offered for review | | 4. Threads | a reply chain as one scrolling card, attachments paused-on and played | lane/post-threads (paused mid-docs: thread items, `posts thread/unthread`, `--threads`) | finish + merge | -| 5. Narration | a script per post (verbatim; excerpt ≤ ~70 words), Orpheus takes, the attachment muffled under the read then clean | by hand: `narr-demo/mix.sh` + `narrate-all.sh` (ops `tts` orpheus/zac; lowpass 650 Hz ×2 at 0.30, 0.8 s back to clean) | lane/post-narration (paused at the start): `narration` on post items, the mix inside build-video, Play muffling live, re-takes with direction on the narration review, `posts narrate` | +| 5. Narration | a script per post (VERBATIM, paragraphs kept), the operator's own recorded read (Orpheus takes as timing placeholders), the attachment muffled under the read then clean | lane/post-narration: `narration` on post items (post-narration.mjs), the mix inside build-video (the demo's numbers; levels within 0.2 dB of it), Play muffling live, the post bench's recording session (part by part, teleprompter, Keep → a recorded take, picked), re-takes with direction (the editor's tts op), parts, `posts narrate` (`--import`, `--take`, `--all --draft-scripts`, knobs), `posts fit` (the attachment's best part) | the card following the read on very long posts (scroll/page to the part being read); recording with the muffled attachment in headphones | | 6. Privacy pass | other accounts blurred | card blur rule (non-subject authors, @mentions) | blur boxes on attachments that are screenshots of other accounts; the capture-posts quoted-author blur | | 7. Render + trailer | the take, the trailer reel | takes, reels (beat reels, reel bench) | — | @@ -34,6 +34,28 @@ for this whole post video flow"; for now the videos come first and code waits. - Known: a read longer than its clip holds the last frame (the rail freezes with it); the rail does not run on in a held frame. Fixed properly by the narration lane's in-build mix. +## The dedicated UI (lane/post-narration's plan, 2 Nov) + +One page per post video, `/projects/<p>/posts-flow`, a vertical stepper of the seven steps above. Each step +shows its STATE (counts, what is missing) and its NEXT ACTION as one button; nothing on it is only an agent's. +It is a view over the writers that exist -- it adds no second way to change the manifest. + +| Step | State shown | Next action (the writer it runs) | Exists | To build | +|---|---|---|---|---| +| 1. Archive | per channel: posts archived, back to when, captures (media, thread shots, avatars) missing | Fetch older · Capture missing (editor ops `fetch-posts`, `capture-posts` `"avatars": true`) | the ops; `posts avatars` | the per-account archive panel (editor channel page has parts of it) | +| 2. Select | the date window; posts in it by class (story / conduct / out) with each reason; reviewed Yes / No | Classify (a generation task, `/gen`) · Review (Y/N walk) · Reel (`posts reel`) | `posts reel`; a hand `classified.jsonl` | the classification task + its review page; the reel from the Yes set | +| 3. Storyline | sections with labels, the posts in each | Draft sections (from the classes, by time) · Edit (`timeline section-add`, deck markers) | the writers; deck markers | a storyline draft task and its review | +| 4. Threads | runs of replies that should be one card | Thread (`posts thread/unthread`) | lane/post-threads | merge it | +| 5. Narration | recorded n of N, placeholders, approved; the next post to record | Record (the post bench's session, walking N / P) · Draft scripts · Placeholders (`--all --take`) · Fit (`posts fit --all`) | lane/post-narration (all of it) | the card following the read for long posts; a "record the whole cut" mode that opens on the first unrecorded post and moves on Keep | +| 6. Privacy | cards: other authors blurred (the rule); attachments: screenshots of other accounts unblurred | Blur box on an attachment (a new `media[i].blur` box, drawn on the post bench like the clip blur) | the card rule | the attachment blur boxes (clip-blur.mjs's shape on post media) | +| 7. Render | the last take, its length, what changed since | Take (`umtool take --full`) · Trailer (beat reels) | takes, reels | the step's view of them | + +Build order: (a) the stepper page reading state only (counts from the manifest + the narration route's +progress + the archive's channel snapshot), each next action a link to the surface that does it; (b) the +classification task and its Y/N review (step 2), then the storyline draft (step 3); (c) attachment blur boxes +(step 6); (d) "record the whole cut" (step 5's walk opening on the first unrecorded post); (e) the card following +the read. Each is a lane of its own, merged in that order. + ## Narration sources (operator, 2 Nov: "pure AI voice, record voice, and run AI on recorded voice (and re-run or re-record)") A take = a source (TTS, a recording, or another take) + a chain of steps; derived takes never overwrite their source. The model and UI are in lane/post-narration. Still to build (a follow-up lane): editor ops with local engines, through 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/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts @@ -0,0 +1,104 @@ +import { readFile, stat } from "node:fs/promises"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; +import { discardPart, finishSession, partFile, readSession, savePart } from "@/lib/report/recordSession.mjs"; + +export const dynamic = "force-dynamic"; + +// THE RECORDING SESSION (lib/report/recordSession.mjs; /projects/<p>/narration/record): +// a person's read of one post item, part by part, each part on disk the moment it is kept. +// +// GET ?project&id[&label] the session: the parts kept so far (a reload resumes) +// GET ?project&id&n[&label] one kept part's audio (play it back) +// POST multipart {project, id, n, count, text, para, label?, part} keep part n of count +// POST {project, op: "discard", id, n, label?} drop part n (redo it) +// POST {project, op: "finish", id, label?, script?} every part in: one recorded +// take, trimmed, joined, levelled, PICKED + +const noStore = { "cache-control": "no-store" }; +type Entry = Record<string, unknown> & { id: string; type?: string }; + +const fail = (e: unknown) => { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + const status = (e as { status?: number }).status ?? 400; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); +}; + +function itemOf(manifest: Record<string, unknown>, id: string): Entry | null { + const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[]; + return tl.find((e) => e?.type === "post" && e.id === id) ?? null; +} + +const TYPES: Record<string, string> = { webm: "audio/webm", ogg: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4" }; + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const e = itemOf(r.manifest as Record<string, unknown>, q.get("id") ?? ""); + if (!e) return Response.json({ error: `no post item ${q.get("id")}` }, { status: 404 }); + const label = q.get("label") ?? "operator"; + try { + const n = q.get("n"); + if (n !== null) { + const f = await partFile(r.project.dir, e, Number(n), label); + if (!f || !(await stat(f).catch(() => null))) return new Response("no such part", { status: 404 }); + const body = await readFile(f); + return new Response(new Uint8Array(body), { headers: { "content-type": TYPES[f.split(".").pop() ?? ""] ?? "application/octet-stream", ...noStore } }); + } + return Response.json({ ok: true, session: await readSession(r.project.dir, e, label) }, { headers: noStore }); + } catch (err) { + return fail(err); + } +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/post-narration/record"); + if (refused) return refused; + if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) { + let form: FormData; + try { + form = await request.formData(); + } catch { + return Response.json({ error: "expected a multipart part" }, { status: 400 }); + } + const r = await resolveReport(String(form.get("project") ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const e = itemOf(r.manifest as Record<string, unknown>, String(form.get("id") ?? "")); + if (!e) return Response.json({ error: `no post item ${String(form.get("id"))}` }, { status: 404 }); + const blob = form.get("part"); + if (!blob || typeof blob === "string") return Response.json({ error: "no part" }, { status: 400 }); + try { + const session = await savePart(r.project.dir, e, { + n: Number(form.get("n")), count: Number(form.get("count")), text: String(form.get("text") ?? ""), para: Number(form.get("para")), + bytes: new Uint8Array(await blob.arrayBuffer()), type: blob.type || "audio/webm", label: String(form.get("label") ?? "operator").toLowerCase(), + }); + return Response.json({ ok: true, session }, { headers: noStore }); + } catch (err) { + return fail(err); + } + } + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON or a part" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const e = itemOf(r.manifest as Record<string, unknown>, String(body.id ?? "")); + if (!e) return Response.json({ error: `no post item ${String(body.id)}` }, { status: 404 }); + const label = String(body.label ?? "operator").toLowerCase(); + try { + if (body.op === "discard") return Response.json({ ok: true, session: await discardPart(r.project.dir, e, Number(body.n), label) }, { headers: noStore }); + if (body.op === "finish") { + const kept = await finishSession(r.project, e, { label, manifest: r.manifest as Record<string, unknown>, script: typeof body.script === "string" ? body.script : null }); + return Response.json({ ok: true, take: kept.take, gain: kept.gain, entry: kept.result.entry, token: kept.result.token }, { headers: noStore }); + } + return Response.json({ error: "op is discard or finish" }, { status: 400 }); + } catch (err) { + return fail(err); + } +} diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -0,0 +1,258 @@ +import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, isNarrated, nextTakeNumber, pickedTake, postIdOf, postNarrationKnobs, takeFileOf, takeIdOf, takesDirOf, +} from "umtool-report-to-video/post-narration"; +import { postItemPlan } from "umtool-report-to-video/post-item"; +import { jobState, resultLine, startJob } from "@/lib/research/case-editor"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, fitPostItems, manifestToken, undoStructural, updatePostNarration } from "@/lib/report/manifest.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; +import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; +import { fitPostItem } from "@/lib/report/postFit.mjs"; + +export const dynamic = "force-dynamic"; + +// A NARRATED POST ITEM's bench (report-to-video/post-narration.mjs; knobs.md, +// "A narrated post item"): the recording session, the takes, the mix's knobs. +// +// GET ?project the cut's narration progress: each post item, +// what plays (recorded, synthesized, none), approved +// GET ?project&id&job&file[&note][&script] a synthesized take's job; once done, the take is +// kept (measured, appended and picked) +// POST multipart {project, id, label, script?, note?, part[] (audio), text[], para[]} +// a RECORDING, part by part: trimmed, joined, +// levelled, kept as take-<n>.recorded-<label>.wav +// POST {project, op: "set", id, patch, token} updatePostNarration (script, pick, approved, off, the mix) +// POST {project, op: "take", id, note?, voice?, engine?, speed?, script?} +// a new take asked of the EDITOR's tts op (a job) +// POST {project, op: "fit", id, linger?} the attachment's best part for the read (posts fit) +// POST {project, op: "derive", id, from, op2: enhance|convert, engine?, voice?} +// a NEW take made from take `from` by the editor's voice op +// (a job; kept by GET ?job&derive=<from>); `installed: false` +// when the editor has no engine for it +// POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) +// POST {project, op: "undo"} the last structural write undone + +const noStore = { "cache-control": "no-store" }; +type Entry = Record<string, unknown> & { id: string; type?: string; narration?: Record<string, unknown> }; + +const fail = (e: unknown) => { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + const status = (e as { status?: number }).status ?? 400; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); +}; + +const postsOf = (m: Record<string, unknown>) => ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).filter((e) => e?.type === "post"); + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as Record<string, unknown>; + const render = (m.render ?? {}) as Record<string, unknown>; + const id = q.get("id"); + const job = q.get("job"); + if (id && job) { + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const rel = q.get("file") ?? ""; + if (!rel.startsWith(`${takesDirOf(postIdOf(e))}/take-`) || rel.includes("..") || !rel.endsWith(".wav")) return Response.json({ error: "not a take of this post" }, { status: 400 }); + try { + const st = await jobState(job); + if (!st.done) return Response.json({ state: "running", status: st.status }, { headers: noStore }); + if (st.status !== "done") return Response.json({ state: "failed", status: st.status, error: st.tail.slice(-3).join(" / ") }, { headers: noStore }); + const had = ((e.narration?.takes ?? []) as Array<{ file?: string }>).some((t) => t.file === rel); + if (!had) { + const abs = path.join(r.project.dir, ...rel.split("/")); + if (!(await stat(abs).catch(() => null))?.isFile()) { + const res = resultLine<{ wav?: string }>(st.tail, "@@tts-result "); + return Response.json({ state: "failed", error: `the job is done but ${rel} is not there (it wrote ${res?.wav ?? "nothing"})` }, { headers: noStore }); + } + const res = resultLine<{ engine?: string; voice?: string }>(st.tail, "@@tts-result ") ?? {}; + const meas = await measureTake(abs); + const note = q.get("note"); + const script = q.get("script") ?? String(e.narration?.script ?? ""); + const derive = q.get("derive"); + if (derive !== null) { + // A derived take: source the take it came from, its step recorded, its parts (renamed) kept. + const takes = (e.narration?.takes ?? []) as Array<{ file: string; voice?: string; script?: string; parts?: Array<{ n: number }> }>; + const from = takes[Number(derive)]; + if (!from) return Response.json({ state: "failed", error: `no take ${derive}` }, { headers: noStore }); + const op = String(q.get("op") ?? ""); + const engine = q.get("engine"); + const voice = q.get("voice"); + const partsRel = rel.replace(/\.wav$/, ".parts"); + const derived = { + file: rel, engine: "derived", voice: voice ?? from.voice ?? "?", seconds: meas.seconds, source: { kind: "take", from: takeIdOf(from) }, + steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ranAt: new Date().toISOString(), job }], + script: from.script ?? script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), + ...(Array.isArray(from.parts) ? { parts: from.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) } : {}), + }; + const { result } = await withEditNotes(r.project, async () => updatePostNarration(r.project.dir, id, { addTake: derived }, { token: await manifestToken(r.project.dir) })); + return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token }, { headers: noStore }); + } + const take = { + file: rel, engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", seconds: meas.seconds, + source: { kind: "tts", engine: res.engine ?? q.get("engine") ?? "orpheus", voice: res.voice ?? q.get("voice") ?? "zac", script }, + script, at: new Date().toISOString(), jobId: job, ...(Number.isFinite(meas.lufs) ? { lufs: meas.lufs } : {}), ...(note ? { note } : {}), + }; + const { result } = await withEditNotes(r.project, async () => + updatePostNarration(r.project.dir, id, { addTake: take, ...(script !== e.narration?.script ? { script } : {}) }, { token: await manifestToken(r.project.dir) }), + ); + return Response.json({ state: "done", file: rel, entry: result.entry, token: result.token }, { headers: noStore }); + } + return Response.json({ state: "done", file: rel }, { headers: noStore }); + } catch (err) { + return fail(err); + } + } + // The progress of the cut's reading: what each post item plays. + const items = postsOf(m).map((e, i) => { + const t = pickedTake(e); + return { + id: e.id, n: i + 1, postId: postIdOf(e), narrated: isNarrated(e), script: !!e.narration?.script, + plays: !t || !isNarrated(e) ? "none" : t.engine === "recorded" ? "recorded" : "synthesized", + approved: e.narration?.approved === true, takes: ((e.narration?.takes ?? []) as unknown[]).length, + seconds: postItemPlan(e, render).total, + }; + }); + return Response.json({ + ok: true, items, + counts: { posts: items.length, recorded: items.filter((x) => x.plays === "recorded").length, synthesized: items.filter((x) => x.plays === "synthesized").length, none: items.filter((x) => x.plays === "none").length, approved: items.filter((x) => x.approved).length }, + }, { headers: noStore }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/post-narration"); + if (refused) return refused; + if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) return record(request); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON or a recording" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as Record<string, unknown>; + const id = String(body.id ?? ""); + const token = body.token === undefined || body.token === null ? null : String(body.token); + try { + if (body.op === "undo") { + const { result } = await withEditNotes(r.project, () => undoStructural(r.project.dir, { token })); + return Response.json({ ok: true, ...result }, { headers: noStore }); + } + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + if (body.op === "set") { + const { result, editNotes } = await withEditNotes(r.project, () => updatePostNarration(r.project.dir, id, (body.patch ?? {}) as Record<string, unknown>, { token })); + return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "take") { + // The EDITOR synthesizes (its tts op, a job on its queue); the take is kept when the job is done (GET ?job). + const k = postNarrationKnobs(e, (m.render ?? {}) as Record<string, unknown>); + const script = String(body.script ?? e.narration?.script ?? "").trim(); + if (!script) return Response.json({ error: `${id} has no script to read` }, { status: 400 }); + const engine = String(body.engine ?? e.narration?.engine ?? k.engine); + const voice = String(body.voice ?? e.narration?.voice ?? k.voice); + const pid = postIdOf(e); + const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const rel = takeFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), engine, voice); + const speed = body.speed === undefined || body.speed === null || engine === "orpheus" ? undefined : Number(body.speed); + const jobId = await startJob("/api/ops/tts", { text: script, engine, voice, out: path.join(r.project.dir, ...rel.split("/")), ...(speed ? { speed } : {}) }); + return Response.json({ ok: true, jobId, file: rel, engine, voice, script }, { headers: noStore }); + } + if (body.op === "derive") { + const takes = (e.narration?.takes ?? []) as Array<{ file: string; parts?: Array<{ n: number; file?: string }> }>; + const from = Number(body.from); + const t = takes[from]; + if (!t) return Response.json({ error: `${id} has no take ${from + 1}` }, { status: 404 }); + const op = String(body.op2 ?? ""); + if (!(POST_DERIVE_OPS as readonly string[]).includes(op)) return Response.json({ error: `op2 is one of ${POST_DERIVE_OPS.join(", ")}` }, { status: 400 }); + const engine = body.engine ? String(body.engine) : null; + const voice = body.voice ? String(body.voice) : null; + const pid = postIdOf(e); + const dir = path.join(r.project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), op, engine ?? voice ?? "default"); + const abs = (x: string) => path.join(r.project.dir, ...x.split("/")); + const partsRel = rel.replace(/\.wav$/, ".parts"); + const parts = Array.isArray(t.parts) && t.parts.every((p) => typeof p.file === "string") + ? t.parts.map((p) => ({ file: abs(String(p.file)), out: abs(`${partsRel}/p${String(p.n).padStart(2, "0")}.wav`) })) + : null; + try { + const jobId = await startJob(POST_DERIVE_ROUTES[op as keyof typeof POST_DERIVE_ROUTES], { file: abs(t.file), out: abs(rel), ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...(parts ? { parts } : {}) }); + return Response.json({ ok: true, jobId, file: rel, from, op: op, engine, voice }, { headers: noStore }); + } catch (err) { + const status = (err as { status?: number }).status ?? 502; + const msg = err instanceof Error ? err.message : String(err); + // The editor has no engine for it yet (a follow-up lane adds voice-enhance / voice-convert): say so, plainly. + if (status === 404 || /not installed|no engine|unknown|not found|404/i.test(msg)) return Response.json({ ok: false, installed: false, error: `the editor has no ${op} engine yet (not installed)` }, { status: 200, headers: noStore }); + return Response.json({ error: msg }, { status }); + } + } + if (body.op === "delete") { + const { result } = { result: await deleteTake(r.project, e, Number(body.take)) }; + return Response.json({ ok: true, entry: result.entry, token: result.token }, { headers: noStore }); + } + if (body.op === "fit") { + const linger = body.linger === undefined || body.linger === null ? null : Number(body.linger); + const f = await fitPostItem(e, (m.render ?? {}) as Record<string, unknown>, r.project.dir, { linger }); + if (!f || f.untouched || !f.window) return Response.json({ ok: true, untouched: true, why: !f ? "not narrated, clip=full, or no video" : "its video is no longer than the read" }, { headers: noStore }); + const { result } = await withEditNotes(r.project, async () => fitPostItems(r.project.dir, [{ id, media: f.media, window: f.window, ...(linger !== null ? { linger } : {}) }], { token: await manifestToken(r.project.dir) })); + const after = ((await readManifest(r.project.dir)) ?? {}) as Record<string, unknown>; + const now = postsOf(after).find((x) => x.id === id); + return Response.json({ ok: true, window: f.window, entry: now ?? null, token: result.token }, { headers: noStore }); + } + return Response.json({ error: "op is set, take, derive, delete, fit or undo" }, { status: 400 }); + } catch (err) { + return fail(err); + } +} + +/** A recording, part by part: the uploads kept beside the post's takes until they are made into one. */ +async function record(request: Request) { + let form: FormData; + try { + form = await request.formData(); + } catch { + return Response.json({ error: "expected a multipart recording" }, { status: 400 }); + } + const r = await resolveReport(String(form.get("project") ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as Record<string, unknown>; + const id = String(form.get("id") ?? ""); + const e = postsOf(m).find((x) => x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const label = String(form.get("label") ?? "operator").trim().toLowerCase() || "operator"; + if (!RECORD_LABEL_RE.test(label)) return Response.json({ error: `"${label}" is not a voice label (a-z, 0-9, - and _)` }, { status: 400 }); + const blobs = form.getAll("part").filter((x): x is File => typeof x === "object" && x !== null && "arrayBuffer" in x); + if (!blobs.length) return Response.json({ error: "nothing was recorded" }, { status: 400 }); + const texts = form.getAll("text").map(String); + const paras = form.getAll("para").map((x) => Number(x)); + const up = path.join(r.project.dir, ...takesDirOf(postIdOf(e)).split("/"), `.upload-${Date.now()}`); + await mkdir(up, { recursive: true }); + try { + const parts = []; + for (const [k, b] of blobs.entries()) { + if (b.size > 200 * 1024 * 1024) return Response.json({ error: "a part is larger than 200 MB" }, { status: 413 }); + const f = path.join(up, `p${k + 1}.${/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm"}`); + await writeFile(f, new Uint8Array(await b.arrayBuffer())); + parts.push({ file: f, text: texts[k] ?? "", para: Number.isInteger(paras[k]) ? paras[k] : k }); + } + const script = form.get("script"); + const note = form.get("note"); + const kept = await keepRecording(r.project, e, parts, { label, manifest: m, note: note ? String(note) : null, script: script === null ? null : String(script) }); + return Response.json({ ok: true, take: kept.take, gain: kept.gain, target: kept.target, token: kept.result.token, entry: kept.result.entry }, { headers: noStore }); + } catch (err) { + return fail(err); + } finally { + await rm(up, { recursive: true, force: true }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -112,6 +112,9 @@ // set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] the Posts table's writer // reel <project> --channel <slug>… [--since/--until/--own/--with-media/--replies/--order/--limit] post items // set-item <project> <item> hold=… media.<i>.start=… a post item's knobs +// narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration +// fit <project> --all | <item>… narrated posts' videos cut to their best part +// avatar <project> <handle> <image> | avatars <project> the authors' pictures // umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel import process from "node:process"; import { @@ -1029,6 +1032,10 @@ function usage() { " a re-run adds only posts not already in the cut", " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [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] [--json]", + " umtool posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"]] [--pick n] [--approve] [k=v …]", + " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)", + " umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", + " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards", " umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>", " the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;", " Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's", diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -8,6 +8,7 @@ import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; import { POST_HOLD, POST_MEDIA_MIN_SPAN, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item"; import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; +import PostNarrationPanel from "./PostNarrationPanel"; // --------------------------------------------------------------------------- // THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its @@ -36,7 +37,7 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [ ]; export default function PostBench({ - project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, + project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, }: { project: string; entry: Entry; @@ -47,6 +48,8 @@ export default function PostBench({ prev: string | null; next: string | null; fromPlay: boolean; + /** The cut's render block (its `postNarration` knobs). */ + render?: Record<string, unknown>; }) { const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); @@ -54,7 +57,7 @@ export default function PostBench({ const [token, setToken] = useState(initialToken); const [status, setStatus] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); - const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry) as PostPlan)), [entry, initial, initialPlan]); + const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render) as PostPlan)), [entry, initial, initialPlan, render]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -86,10 +89,18 @@ export default function PostBench({ ev.preventDefault(); setPlaying((p) => (s >= total ? (setS(0), true) : !p)); } + // N / P: the next or previous post of the cut (the recording session walks the cut). + if ((ev.key === "n" || ev.key === "p") && !ev.metaKey && !ev.ctrlKey && !ev.altKey) { + const to = ev.key === "n" ? next : prev; + if (to) { + ev.preventDefault(); + router.push(postBenchHref(project, to, fromPlay ? { play: { at: 0 } } : {})); + } + } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [s, total]); + }, [s, total, next, prev, project, fromPlay, router]); const dirty = JSON.stringify(entry) !== JSON.stringify(saved); const media = entry.media ?? []; @@ -215,9 +226,11 @@ export default function PostBench({ </div> {/* The plan, as a strip: the reading span, then each attachment's step. */} <div className="relative h-6 w-full overflow-hidden rounded bg-[var(--color-panel)] text-[10.5px]" data-post-bench-plan=""> - <div className="absolute inset-y-0 left-0 flex items-center bg-white/10 px-1" style={{ width: `${(plan.reading / total) * 100}%` }}> - read {plan.reading.toFixed(1)} s - </div> + {plan.reading > 0 && ( + <div className="absolute inset-y-0 left-0 flex items-center bg-white/10 px-1" style={{ width: `${(plan.reading / total) * 100}%` }}> + read {plan.reading.toFixed(1)} s + </div> + )} {plan.steps.map((st, k) => ( <div key={k} className="absolute inset-y-0 flex items-center border-l border-black/40 bg-[var(--color-sel)]/25 px-1" style={{ left: `${(st.at / total) * 100}%`, width: `${(st.seconds / total) * 100}%` }} data-post-bench-step={st.kind}> {st.kind} {st.seconds.toFixed(1)} s @@ -225,13 +238,32 @@ export default function PostBench({ ))} <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} /> </div> + <PostNarrationPanel + project={project} + entry={entry} + token={token} + plan={plan} + render={render} + onEntry={(e, t) => { + setEntry(e); + setSaved(e); + setToken(t); + }} + s={s} + setS={setS} + setPlaying={setPlaying} + prev={prev} + next={next} + fromPlay={fromPlay} + /> </section> <aside className="space-y-3 text-[12.5px]"> <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> <h2 className="micro mb-2">length</h2> <p className="m-0 text-text-2"> - the rule: {reading.toFixed(1)} s to read{media.length ? ` + the attachments` : ""} = <b data-post-bench-rule="">{ruleSeconds(entry).toFixed(1)} s</b> + {plan.narration ? `the read (${plan.narration.seconds.toFixed(1)} s) and its linger` : `${reading.toFixed(1)} s to read`} + {media.length ? `, the attachments beside it` : ""} = <b data-post-bench-rule="">{ruleSeconds(entry, render).toFixed(1)} s</b> </p> <label className="mt-2 flex items-center gap-2"> hold diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -44,7 +44,8 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj entry={entry} token={await manifestToken(project.dir)} box={{ width: box.width, height: box.height }} - plan={postItemPlan(entry) as unknown as PostPlan} + plan={postItemPlan(entry, render) as unknown as PostPlan} + render={render} back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }} prev={k > 0 ? neighbours[k - 1] : null} next={k < neighbours.length - 1 ? neighbours[k + 1] : null} diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx @@ -0,0 +1,706 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import Waveform from "@/components/Waveform"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { postBenchHref } from "@/lib/hrefs"; +import { POST_DERIVE_OPS, POST_NARRATION_DEFAULTS, mixPhaseAt, pickedTake, postNarrationKnobs, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration"; +import { projectFileMedia } from "./bench/benchMedia"; +import { usePeaks } from "./bench/usePeaks"; +import { useNotes } from "@/lib/annotations/useNotes"; +import { MIC_KEY, ls, useMic } from "./useMic"; +import type { PostPlan } from "./review/PostItemPlayer"; + +// --------------------------------------------------------------------------- +// A POST's NARRATION ON THE BENCH (report-to-video/post-narration.mjs; +// knobs.md, "A narrated post item"), beside the post bench's player: +// +// the lanes the attachment's whole waveform with its window (the in/out +// handles; Re-pick best: posts fit's scan), and the read on the +// item's clock -- the take's waveform from its lead (drag it), +// the muffle under it, the ramp back to clean +// record THE RECORDING SESSION (operator, 2 Nov: "I think I'll record my +// voice"): the mic, a level meter, a 3-2-1 count-in, the script as +// a teleprompter PART BY PART (Record / Stop / Redo part / Next +// part), play back, Keep -- saved as a recorded take and picked +// takes each take (play it, its parts, Pick, its note), Approve, the +// script, Re-take with direction (the EDITOR's tts op, a job) +// the mix wet, lead, tail, ramp, linger, short, attach, clip, duck +// +// Every change is one write (POST /api/report/post-narration), the writer +// `umtool posts narrate` runs; the bench takes the entry it returns. +// --------------------------------------------------------------------------- + +type Step = { op: string; engine?: string; voice?: string }; +type Take = { file: string; engine?: string; voice?: string; seconds: number; note?: string; script?: string; label?: string; source?: { kind: string; from?: string; voice?: string; engine?: string }; steps?: Step[]; parts?: Array<{ n: number; para?: number; text?: string; start: number; seconds: number; file?: string }> }; +type Narration = { script?: string; takes?: Take[]; pick?: number; approved?: boolean; off?: boolean; window?: { media: number; start: number; end: number; score?: number; reason?: string } } & Record<string, unknown>; +type Entry = Record<string, unknown> & { id: string; narration?: Narration; media?: Array<Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number }> }; +type Progress = { items: Array<{ id: string; n: number; plays: string; approved: boolean }>; counts: { posts: number; recorded: number; synthesized: number; none: number; approved: number } }; + +const fileUrl = (project: string, rel: string) => `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`; +const LABEL_KEY = "umtool.post-narration.label"; + +export default function PostNarrationPanel({ + project, entry, token, plan, render, onEntry, s, setS, setPlaying, prev, next, fromPlay, +}: { + project: string; + entry: Entry; + token: string | null; + plan: PostPlan; + render: Record<string, unknown>; + /** The writer's answer: the entry as it is now, and the manifest's token. */ + onEntry: (e: Entry, token: string | null) => void; + s: number; + setS: (s: number) => void; + setPlaying: (p: boolean) => void; + prev: string | null; + next: string | null; + fromPlay: boolean; +}) { + const n = entry.narration ?? {}; + const takes = n.takes ?? []; + const picked = pickedTake(entry) as (Take & { index: number }) | null; + const k = postNarrationKnobs(entry, render) as typeof POST_NARRATION_DEFAULTS & Record<string, unknown>; + const [error, setError] = useState<string | null>(null); + const [status, setStatus] = useState<string | null>(null); + const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); + + const post = useCallback( + async (body: Record<string, unknown>) => { + setError(null); + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id: entry.id, token, ...body }) }); + const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[]; jobId?: string; file?: string; untouched?: boolean; why?: string; window?: Narration["window"] }; + if (!res.ok) { + setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); + return null; + } + if (j.entry) onEntry(j.entry, j.token ?? null); + return j; + }, + [project, entry.id, token, onEntry], + ); + const set = (patch: Record<string, unknown>) => post({ op: "set", patch }).then((j) => j && setStatus("saved")); + + // ---- the cut's reading progress ------------------------------------------- + const [progress, setProgress] = useState<Progress | null>(null); + useEffect(() => { + let live = true; + fetch(`/api/report/post-narration?project=${encodeURIComponent(project)}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : null)) + .then((j) => live && j && setProgress(j as Progress)) + .catch(() => {}); + return () => { + live = false; + }; + }, [project, entry]); + const nextToRecord = progress?.items.find((x) => x.plays !== "recorded" && x.id !== entry.id) ?? null; + + // ---- the operator's notes on the cut's posts (the notes system: an entry's, a moment's in it) ---- + const notesApi = useNotes({ project }); + const noteEntry = (a: { kind: string; entry?: string }) => (a.kind === "entry" || a.kind === "cut" || a.kind === "moment" || a.kind === "edit" ? a.entry ?? null : null); + const openNotes = notesApi.notes.filter((x) => x.status === "open"); + const mine = openNotes.filter((x) => noteEntry(x.anchor as { kind: string; entry?: string }) === entry.id); + const withNotes = progress ? progress.items.filter((x) => openNotes.some((nn) => noteEntry(nn.anchor as { kind: string; entry?: string }) === x.id)) : []; + const nextWithNote = withNotes.find((x) => x.n > (progress?.items.find((y) => y.id === entry.id)?.n ?? 0)) ?? withNotes[0] ?? null; + const [noteText, setNoteText] = useState(""); + + // ---- the recording session -------------------------------------------------- + const mic = useMic(); + const [label, setLabel] = useState("operator"); + useEffect(() => setLabel(ls.get(LABEL_KEY) ?? "operator"), []); + const [script, setScript] = useState(n.script ?? ""); + useEffect(() => setScript(entry.narration?.script ?? ""), [entry.id, entry.narration?.script]); + const parts = useMemo(() => scriptParts(script), [script]); + const [part, setPart] = useState(0); + const [blobs, setBlobs] = useState<Array<{ blob: Blob; url: string } | null>>([]); + const [phase, setPhase] = useState<"idle" | "count" | "recording" | "saving">("idle"); + const [count, setCount] = useState(0); + useEffect(() => { + setPart(0); + setBlobs([]); + setPhase("idle"); + }, [entry.id]); + const record = async () => { + if (phase !== "idle" || !parts.length) return; + setPhase("count"); + for (const c of [3, 2, 1]) { + setCount(c); + await new Promise((r) => setTimeout(r, 700)); + } + setCount(0); + if (!(await mic.start())) { + setPhase("idle"); + return; + } + setPhase("recording"); + }; + const stop = async () => { + if (phase !== "recording") return; + const blob = await mic.stop(); + setPhase("idle"); + if (!blob) return; + setBlobs((b) => { + const out = [...b]; + if (out[part]) URL.revokeObjectURL(out[part]!.url); + out[part] = { blob, url: URL.createObjectURL(blob) }; + return out; + }); + // Auto-advance to the next part not yet recorded. + setPart((p) => (p < parts.length - 1 ? p + 1 : p)); + }; + const allIn = parts.length > 0 && parts.every((_, i) => !!blobs[i]); + const keep = async () => { + if (!allIn) return; + setPhase("saving"); + setError(null); + const fd = new FormData(); + fd.set("project", project); + fd.set("id", entry.id); + fd.set("label", label); + if (script !== (n.script ?? "")) fd.set("script", script); + parts.forEach((p, i) => { + fd.append("part", blobs[i]!.blob, `p${i + 1}.webm`); + fd.append("text", p.text); + fd.append("para", String(p.para)); + }); + const res = await fetch("/api/report/post-narration", { method: "POST", body: fd }); + const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; take?: Take }; + setPhase("idle"); + if (!res.ok || !j.entry) { + setError(j.error ?? `HTTP ${res.status}`); + return; + } + onEntry(j.entry, j.token ?? null); + setBlobs([]); + setPart(0); + setStatus(`kept ${j.take?.file ?? "the recording"} (picked)`); + // Re-record, then re-run the chain: the steps the last recording's derived takes applied, on the new one. + if (rerunChain) { + const newIndex = (j.entry.narration?.takes ?? []).length - 1; + const lastRecorded = [...takes.keys()].reverse().find((i) => takeSourceOf(takes[i]).kind === "recorded"); + const steps = lastRecorded === undefined ? [] : (tree.kids.get(lastRecorded) ?? []).flatMap((k) => takes[k].steps ?? []); + if (steps.length) setChain(steps.map((step) => ({ from: newIndex, step }))); + } + }; + // R records, S stops (Space is the bench's play). + useEffect(() => { + const onKey = (ev: KeyboardEvent) => { + const tgt = ev.target as HTMLElement | null; + if (tgt?.closest("input, textarea, select")) return; + if (ev.key === "r" && !ev.metaKey && !ev.ctrlKey) { + ev.preventDefault(); + void record(); + } else if (ev.key === "s" && !ev.metaKey && !ev.ctrlKey) { + ev.preventDefault(); + void stop(); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }); + + // ---- a re-take with direction (the editor's tts op) -------------------------- + const [dir, setDir] = useState({ note: "", voice: "", speed: "" }); + const [job, setJob] = useState<{ id: string; file: string; note: string; script: string; state: string; error?: string; polls?: number; derive?: { from: number; op: string; engine?: string | null; voice?: string | null } } | null>(null); + // Derived takes still to make after a re-record ("re-run the chain"), from the new take. + const [chain, setChain] = useState<Array<{ from: number; step: Step }>>([]); + const [rerunChain, setRerunChain] = useState(true); + const [notInstalled, setNotInstalled] = useState<string | null>(null); + const derive = async (from: number, step: Step) => { + setNotInstalled(null); + const j = (await post({ op: "derive", from, op2: step.op, engine: step.engine || undefined, voice: step.voice || undefined })) as ({ jobId?: string; file?: string; installed?: boolean; error?: string } & Record<string, unknown>) | null; + if (j && j.installed === false) { + setNotInstalled(j.error ?? `the editor has no ${step.op} engine yet`); + setChain([]); + return; + } + if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: "", script, state: "running", derive: { from, op: step.op, engine: step.engine ?? null, voice: step.voice ?? null } }); + }; + const retake = async () => { + const j = await post({ op: "take", note: dir.note || undefined, voice: dir.voice || undefined, speed: dir.speed ? Number(dir.speed) : undefined, script }); + if (j?.jobId && j.file) setJob({ id: j.jobId, file: j.file, note: dir.note, script, state: "running" }); + }; + useEffect(() => { + if (!job || job.state !== "running") return; + const t = setTimeout(async () => { + const q = new URLSearchParams({ + project, id: entry.id, job: job.id, file: job.file, script: job.script, ...(job.note ? { note: job.note } : {}), + ...(job.derive ? { derive: String(job.derive.from), op: job.derive.op, ...(job.derive.engine ? { engine: job.derive.engine } : {}), ...(job.derive.voice ? { voice: job.derive.voice } : {}) } : {}), + }); + const r = await fetch(`/api/report/post-narration?${q}`, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as { state?: string; error?: string; entry?: Entry; token?: string }; + if (j.state === "done") { + setJob({ ...job, state: "done" }); + setStatus(`new take ${job.file} (picked)`); + if (j.entry) onEntry(j.entry, j.token ?? null); + else window.location.reload(); + } else if (j.state === "failed" || !r.ok) setJob({ ...job, state: "failed", error: j.error ?? `HTTP ${r.status}` }); + // Still queued or running on the editor: ask again. + else setJob({ ...job, polls: (job.polls ?? 0) + 1 }); + }, 1500); + return () => clearTimeout(t); + }, [job, project, entry.id]); + + useEffect(() => { + if (!chain.length || job?.state === "running") return; + const [first, ...rest] = chain; + setChain(rest); + void derive(first.from, first.step); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [chain, job?.state]); + + // The takes as a small tree: each source take (synthesized, recorded) with the takes derived from it under it. + const tree = useMemo(() => { + const byId = new Map(takes.map((t, i) => [takeIdOf(t), i])); + const kids = new Map<number, number[]>(); + const roots: number[] = []; + takes.forEach((t, i) => { + const src = takeSourceOf(t) as { kind: string; from?: string }; + const up = src.kind === "take" && src.from ? byId.get(src.from) : undefined; + if (up === undefined) roots.push(i); + else kids.set(up, [...(kids.get(up) ?? []), i]); + }); + const out: Array<{ i: number; depth: number }> = []; + const walk = (i: number, depth: number) => { + out.push({ i, depth }); + for (const k of kids.get(i) ?? []) walk(k, depth + 1); + }; + roots.forEach((i) => walk(i, 0)); + return { rows: out, kids }; + }, [takes]); + const [deriveDraft, setDeriveDraft] = useState<{ op: string; engine: string; voice: string }>({ op: "enhance", engine: "", voice: "" }); + + // ---- the lanes ------------------------------------------------------------------ + const vi = (entry.media ?? []).findIndex((m) => m.kind === "video"); + const video = vi >= 0 ? entry.media![vi] : null; + const vSecs = Number(video?.seconds ?? 0); + const step = vi >= 0 ? plan.steps.find((st) => st.items.some((m) => m.i === vi)) ?? null : null; + const win = step ? { from: step.srcFrom ?? 0, to: (step.srcFrom ?? 0) + step.seconds } : { from: 0, to: vSecs }; + const vMedia = useMemo(() => projectFileMedia({ project, path: video?.src ?? "", seconds: vSecs || 1 }), [project, video?.src, vSecs]); + const vPeaks = usePeaks(video ? vMedia : { ...vMedia, peaksUrl: null }); + const tMedia = useMemo(() => projectFileMedia({ project, path: picked?.file ?? "", seconds: picked?.seconds || 1 }), [project, picked?.file, picked?.seconds]); + const tPeaks = usePeaks(picked ? tMedia : { ...tMedia, peaksUrl: null }); + const [showWhole, setShowWhole] = useState(false); + const sch = plan.narration ?? null; + const total = plan.total; + const pct = (v: number) => `${(v / Math.max(0.1, total)) * 100}%`; + const drag = useRef<{ x: number; lead: number; w: number } | null>(null); + const [leadDraft, setLeadDraft] = useState<number | null>(null); + const lead = leadDraft ?? Number(k.lead); + + const mixKnob = (key: string, labelText: string, o: { step?: number; min?: number; max?: number; options?: string[] }) => ( + <label className="flex items-center gap-1.5" key={key}> + {labelText} + {o.options ? ( + <select value={String(k[key as keyof typeof k])} onChange={(e) => void set({ [key]: e.target.value === String(POST_NARRATION_DEFAULTS[key as keyof typeof POST_NARRATION_DEFAULTS]) ? null : e.target.value })} data-post-mix={key}> + {o.options.map((x) => ( + <option key={x} value={x}> + {x} + </option> + ))} + </select> + ) : ( + <input + type="number" + step={o.step ?? 0.1} + min={o.min} + max={o.max} + defaultValue={Number(k[key as keyof typeof k])} + key={`${entry.id}:${key}:${String(k[key as keyof typeof k])}`} + onBlur={(e) => { + const v = Number(e.target.value); + if (Number.isFinite(v) && v !== Number(k[key as keyof typeof k])) void set({ [key]: v }); + }} + className="w-16 rounded border border-seam bg-ground px-1 py-0.5" + data-post-mix={key} + /> + )} + </label> + ); + + return ( + <div className="space-y-3 text-[12.5px]" data-post-narration={entry.id} data-post-narration-plays={picked ? (picked.engine === "recorded" ? "recorded" : "synthesized") : "none"}> + {/* The cut's reading: how far along, and where next. */} + <section className="flex flex-wrap items-center gap-3 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" data-post-progress=""> + {progress ? ( + <span> + recorded <b data-post-progress-recorded="">{progress.counts.recorded}</b> of {progress.counts.posts} · placeholder (synthesized) {progress.counts.synthesized} · none {progress.counts.none} · approved {progress.counts.approved} + </span> + ) : ( + <span className="text-text-2">reading the cut…</span> + )} + {nextToRecord && ( + <Link href={postBenchHref(project, nextToRecord.id, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-next-unrecorded={nextToRecord.id}> + next to record: #{nextToRecord.n} › + </Link> + )} + {withNotes.length > 0 && ( + <span data-post-with-notes={withNotes.length}> + {withNotes.length} with notes{nextWithNote && nextWithNote.id !== entry.id && ( + <> + {" · "} + <Link href={postBenchHref(project, nextWithNote.id, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-next-with-note={nextWithNote.id}> + next with a note: #{nextWithNote.n} › + </Link> + </> + )} + </span> + )} + <span className="ml-auto text-text-2">N / P: next / previous post · R record · S stop · Space play</span> + {prev && <Link href={postBenchHref(project, prev, fromPlay ? { play: { at: 0 } } : {})} className="hidden" data-post-walk="prev" />} + {next && <Link href={postBenchHref(project, next, fromPlay ? { play: { at: 0 } } : {})} className="hidden" data-post-walk="next" />} + </section> + + {/* The operator's notes on this post (the notes system), and one more. */} + <section className="space-y-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" data-post-notes={mine.length}> + {mine.map((x) => ( + <p key={x.id} className="m-0" data-post-note={x.id}> + <span className="micro mr-1">note</span> + {x.text} + {x.replies.length ? <span className="ml-2 text-text-2">({x.replies.length} repl{x.replies.length === 1 ? "y" : "ies"})</span> : null} + </p> + ))} + <div className="flex items-center gap-1.5"> + <input value={noteText} onChange={(e) => setNoteText(e.target.value)} placeholder="a note on this post (direction for a re-take, a fix)" className="min-w-0 flex-1 rounded border border-seam bg-ground px-1.5 py-0.5" data-post-note-text="" /> + <button + type="button" + className={btn} + disabled={!noteText.trim() || notesApi.busy} + onClick={() => void notesApi.write({ op: "add", text: noteText.trim(), anchor: { kind: "entry", entry: entry.id } }).then((x) => x && setNoteText(""))} + data-post-note-add="" + > + Add note + </button> + </div> + </section> + + {/* THE LANES: the attachment's window, the read on the item's clock. */} + <section className="space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-lanes=""> + {video && ( + <div data-post-lane="attachment"> + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="micro">attachment · {vSecs.toFixed(1)} s · plays {win.from.toFixed(1)}–{win.to.toFixed(1)} s</span> + <button type="button" className={btn} onClick={() => void post({ op: "fit" }).then((j) => j && setStatus(j.untouched ? `nothing to fit: ${j.why}` : `best part: ${j.window?.start}–${j.window?.end} s`))} data-post-repick=""> + Re-pick best + </button> + <button type="button" className={btn} onClick={() => setShowWhole((x) => !x)} data-post-play-whole=""> + {showWhole ? "Hide whole attachment" : "Play whole attachment"} + </button> + </div> + <Waveform + view={{ from: 0, to: vSecs || 1 }} + sel={win} + cand={n.window ? { from: n.window.start, to: n.window.end } : win} + words={[]} + peaks={vPeaks} + playhead={step && s >= step.at ? (step.srcFrom ?? 0) + Math.min(step.seconds, s - step.at) : null} + onSel={(next2, dragging) => { + if (dragging) return; + const media = { [vi]: { start: next2.from > 0.02 ? Math.round(next2.from * 100) / 100 : null, end: next2.to < vSecs - 0.02 ? Math.round(next2.to * 100) / 100 : null } }; + void fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "set", id: entry.id, patch: { media }, token }) }) + .then((r) => r.json()) + .then((j: { entry?: Entry; token?: string; error?: string }) => (j.entry ? onEntry(j.entry, j.token ?? null) : setError(j.error ?? "not saved"))); + }} + onReachEdge={() => {}} + height={72} + /> + {n.window?.reason && ( + <p className="m-0 mt-1 text-text-2" data-post-window-reason=""> + chosen: {n.window.reason} + </p> + )} + {showWhole && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <video src={fileUrl(project, video.src)} controls className="mt-1 max-h-48" data-post-whole-video="" /> + )} + </div> + )} + {sch && picked && ( + <div data-post-lane="read"> + <div className="micro mb-1"> + the read · {picked.file.split("/").pop()} · {picked.seconds.toFixed(1)} s from {lead.toFixed(2)} s · muffled to {sch.voiceEnd.toFixed(1)} s, clean from {sch.rampEnd.toFixed(1)} s · {mixPhaseAt(sch, s)} + </div> + <div + className="relative h-16 w-full overflow-hidden rounded bg-black/30" + onPointerMove={(e) => { + if (!drag.current) return; + const dt = ((e.clientX - drag.current.x) / drag.current.w) * total; + setLeadDraft(Math.max(0, Math.min(5, Math.round((drag.current.lead + dt) * 20) / 20))); + }} + onPointerUp={() => { + if (!drag.current) return; + drag.current = null; + if (leadDraft !== null && leadDraft !== Number(k.lead)) void set({ lead: leadDraft }).then(() => setLeadDraft(null)); + else setLeadDraft(null); + }} + onClick={(e) => { + const r = e.currentTarget.getBoundingClientRect(); + setS(((e.clientX - r.left) / r.width) * total); + }} + > + {/* The muffle under the read, the ramp back to clean. */} + {sch.duck && <div className="absolute inset-y-0 left-0 bg-sky-500/15" style={{ width: pct(sch.voiceEnd) }} data-post-lane-muffle="" />} + {sch.duck && <div className="absolute inset-y-0 bg-gradient-to-r from-sky-500/15 to-transparent" style={{ left: pct(sch.voiceEnd), width: pct(sch.rampEnd - sch.voiceEnd) }} data-post-lane-ramp="" />} + {plan.steps.map((st, j) => ( + <div key={j} className="absolute bottom-0 h-2 border-l border-black/50 bg-[var(--color-sel)]/40" style={{ left: pct(st.at), width: pct(st.seconds) }} title={`${st.kind} ${st.seconds.toFixed(1)} s`} /> + ))} + <div + className="absolute inset-y-1 cursor-grab rounded bg-amber-400/20 ring-1 ring-amber-400/60" + style={{ left: pct(lead), width: pct(picked.seconds) }} + onPointerDown={(e) => { + e.stopPropagation(); + (e.currentTarget.parentElement as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { x: e.clientX, lead, w: (e.currentTarget.parentElement as HTMLElement).getBoundingClientRect().width }; + }} + data-post-lane-voice="" + > + {tPeaks && ( + <Waveform view={{ from: 0, to: picked.seconds }} sel={{ from: 0, to: 0 }} cand={{ from: 0, to: 0 }} words={[]} peaks={tPeaks} playhead={null} onSel={() => {}} onReachEdge={() => {}} height={52} /> + )} + {(picked.parts ?? []).map((p) => ( + <span key={p.n} className="absolute inset-y-0 w-px bg-amber-200/70" style={{ left: `${(p.start / picked.seconds) * 100}%` }} title={`part ${p.n}`} /> + ))} + </div> + <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: pct(s) }} /> + </div> + </div> + )} + </section> + + {/* THE RECORDING SESSION. */} + <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-record="" data-post-record-phase={phase}> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">record your read</h2> + <select + value={mic.device} + onChange={(e) => void mic.open(e.target.value)} + onFocus={() => !mic.devices.length && void mic.open(ls.get(MIC_KEY) ?? undefined)} + data-post-record-mic="" + aria-label="microphone" + > + {!mic.devices.length && <option value="">microphone…</option>} + {mic.devices.map((d) => ( + <option key={d.deviceId} value={d.deviceId}> + {d.label || d.deviceId.slice(0, 8)} + </option> + ))} + </select> + <div className="h-2 w-28 overflow-hidden rounded bg-black/40" aria-label="level" data-post-record-level={Math.round(mic.level * 100)}> + <div className={cn("h-full", mic.level > 0.85 ? "bg-red-500" : "bg-emerald-500")} style={{ width: `${mic.level * 100}%` }} /> + </div> + <label className="flex items-center gap-1"> + voice + <input + value={label} + onChange={(e) => { + setLabel(e.target.value.toLowerCase()); + ls.set(LABEL_KEY, e.target.value.toLowerCase()); + }} + className="w-24 rounded border border-seam bg-ground px-1 py-0.5" + data-post-record-label="" + /> + </label> + {mic.error && <span className="text-[var(--color-blocking,#c33)]">{mic.error}</span>} + </div> + {/* The teleprompter: every part, the one being read large. */} + <ol className="m-0 max-h-64 list-none space-y-1 overflow-auto p-0" data-post-teleprompter=""> + {parts.map((p, i) => ( + <li + key={p.n} + className={cn("cursor-pointer rounded px-2 py-1", i === part ? "bg-amber-400/15 text-[15px] leading-snug text-text" : "text-text-2", blobs[i] && "border-l-2 border-emerald-500")} + onClick={() => phase === "idle" && setPart(i)} + data-post-part={p.n} + data-post-part-current={i === part ? "1" : undefined} + data-post-part-recorded={blobs[i] ? "1" : undefined} + > + {parts.length > 1 && <span className="micro mr-1">{p.n}.</span>} + {p.text} + </li> + ))} + {!parts.length && <li className="text-text-2">no script yet — write it under “script” below</li>} + </ol> + <div className="flex flex-wrap items-center gap-1.5"> + {phase === "count" && ( + <span className="text-[18px] font-bold tabular-nums" data-post-record-count={count}> + {count} + </span> + )} + <button type="button" className={cn(buttonVariants({ variant: "go", size: "sm" }))} disabled={phase !== "idle" || !parts.length} onClick={() => void record()} data-post-record-start=""> + {blobs[part] ? "Redo part" : parts.length > 1 ? `Record part ${part + 1}` : "Record"} + </button> + <button type="button" className={btn} disabled={phase !== "recording"} onClick={() => void stop()} data-post-record-stop=""> + Stop + </button> + {parts.length > 1 && ( + <button type="button" className={btn} disabled={phase !== "idle" || part >= parts.length - 1} onClick={() => setPart((p) => p + 1)} data-post-record-next-part=""> + Next part + </button> + )} + {blobs[part] && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <audio src={blobs[part]!.url} controls className="h-7" data-post-record-playback={part + 1} /> + )} + <button type="button" className={cn(buttonVariants({ variant: "go", size: "sm" }))} disabled={!allIn || phase !== "idle"} onClick={() => void keep()} data-post-record-keep=""> + {phase === "saving" ? "Saving…" : "Keep"} + </button> + <button + type="button" + className={btn} + disabled={!blobs.some(Boolean) || phase !== "idle"} + onClick={() => { + blobs.forEach((b) => b && URL.revokeObjectURL(b.url)); + setBlobs([]); + setPart(0); + }} + data-post-record-discard="" + > + Discard + </button> + {phase === "recording" && <span className="text-red-400" data-post-recording="">● recording part {part + 1}</span>} + <label className="ml-auto flex items-center gap-1 text-text-2" title="after Keep, the steps the last recording's derived takes applied (enhance, convert) run again on the new one"> + <input type="checkbox" checked={rerunChain} onChange={(e) => setRerunChain(e.target.checked)} data-post-record-rerun-chain="" /> + then re-run the chain + </label> + </div> + </section> + + {/* TAKES, THE SCRIPT, A RE-TAKE WITH DIRECTION. */} + <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-takes=""> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">takes</h2> + <label className="flex items-center gap-1"> + <input type="checkbox" checked={n.approved === true} disabled={!picked} onChange={(e) => void set({ approved: e.target.checked ? true : null })} data-post-approve="" /> + approved + </label> + <label className="flex items-center gap-1"> + <input type="checkbox" checked={n.off !== true} disabled={!takes.length} onChange={(e) => void set({ off: e.target.checked ? null : true })} data-post-narrated="" /> + narrated + </label> + <button type="button" className={btn} onClick={() => void post({ op: "undo" }).then((j) => j && window.location.reload())} data-post-undo=""> + Undo last change + </button> + </div> + <ul className="m-0 list-none space-y-1 p-0" data-post-take-tree=""> + {tree.rows.map(({ i, depth }) => { + const t = takes[i]; + const src = takeSourceOf(t) as { kind: string; voice?: string; engine?: string }; + const step = (t.steps ?? [])[0]; + return ( + <li key={t.file} className={cn("rounded px-2 py-1", picked?.index === i && "bg-[var(--color-sel)]/15")} style={{ marginLeft: depth * 20 }} data-post-take={i + 1} data-post-take-picked={picked?.index === i ? "1" : undefined} data-post-take-engine={t.engine} data-post-take-source={src.kind} data-post-take-depth={depth}> + <div className="flex flex-wrap items-center gap-2"> + <span className="font-mono">{depth ? "└ " : ""}#{i + 1}</span> + <span> + {src.kind === "recorded" ? `recorded · ${src.voice ?? t.voice ?? "?"}` : src.kind === "take" ? `${step?.op ?? "derived"}${step?.engine ? ` · ${step.engine}` : ""}${step?.voice ? ` → ${step.voice}` : ""}` : `${t.engine ?? "?"} · ${t.voice ?? "?"}`} + </span> + <span className="tabular-nums">{Number(t.seconds).toFixed(1)} s</span> + {/* eslint-disable-next-line jsx-a11y/media-has-caption */} + <audio src={fileUrl(project, t.file)} controls preload="none" className="h-7" data-post-take-audio={i + 1} /> + <button type="button" className={btn} disabled={picked?.index === i} onClick={() => void set({ pick: i })} data-post-take-pick={i + 1}> + Pick + </button> + {src.kind === "take" && step && ( + <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(takes.findIndex((x) => takeIdOf(x) === (t.source as { from?: string }).from), step)} data-post-take-rerun={i + 1}> + Re-run + </button> + )} + {src.kind === "recorded" && ( + <button type="button" className={btn} onClick={() => document.querySelector("[data-post-record]")?.scrollIntoView({ behavior: "smooth" })} data-post-take-rerecord={i + 1}> + Re-record + </button> + )} + <button + type="button" + className={btn} + onClick={() => { + if (window.confirm(`Delete take #${i + 1}? Its file goes to the post's .trash/ folder.`)) void post({ op: "delete", take: i }); + }} + data-post-take-delete={i + 1} + > + Delete + </button> + {t.note && <span className="text-text-2">“{t.note}”</span>} + </div> + {(t.parts?.length ?? 0) > 1 && ( + <ol className="m-0 mt-1 list-none space-y-0.5 pl-6 text-text-2" data-post-take-parts={i + 1}> + {t.parts!.map((p) => ( + <li key={p.n} className="flex items-center gap-2"> + <span className="font-mono">{p.n}.</span> + <span className="truncate">{p.text ?? ""}</span> + <span className="tabular-nums">{p.start.toFixed(1)}+{p.seconds.toFixed(1)} s</span> + {p.file && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <audio src={fileUrl(project, p.file)} controls preload="none" className="h-6" /> + )} + </li> + ))} + </ol> + )} + </li> + ); + })} + {!takes.length && <li className="text-text-2">no take yet: record one above, or ask the editor for a placeholder below</li>} + </ul> + {picked && ( + <div className="flex flex-wrap items-center gap-1.5" data-post-derive=""> + <span className="micro">run AI on take #{picked.index + 1}</span> + <select value={deriveDraft.op} onChange={(e) => setDeriveDraft({ ...deriveDraft, op: e.target.value })} data-post-derive-op=""> + {POST_DERIVE_OPS.map((o) => ( + <option key={o} value={o}> + {o === "enhance" ? "enhance (denoise, level)" : "convert (to a stock synthetic voice)"} + </option> + ))} + </select> + <input value={deriveDraft.engine} onChange={(e) => setDeriveDraft({ ...deriveDraft, engine: e.target.value })} placeholder="engine" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-engine="" /> + {deriveDraft.op === "convert" && ( + <input value={deriveDraft.voice} onChange={(e) => setDeriveDraft({ ...deriveDraft, voice: e.target.value })} placeholder="stock voice" className="w-24 rounded border border-seam bg-ground px-1 py-0.5" data-post-derive-voice="" /> + )} + <button type="button" className={btn} disabled={job?.state === "running"} onClick={() => void derive(picked.index, { op: deriveDraft.op, ...(deriveDraft.engine ? { engine: deriveDraft.engine } : {}), ...(deriveDraft.voice ? { voice: deriveDraft.voice } : {}) })} data-post-derive-run=""> + Run → a new take + </button> + {notInstalled && ( + <span className="text-[var(--color-warn,#c80)]" data-post-derive-not-installed=""> + {notInstalled} + </span> + )} + </div> + )} + <label className="block"> + <span className="micro">script — the post, verbatim; add emotion with &lt;sigh&gt; &lt;laugh&gt; &lt;chuckle&gt; &lt;groan&gt; &lt;gasp&gt;</span> + <textarea value={script} onChange={(e) => setScript(e.target.value)} rows={4} className="mt-1 w-full rounded border border-seam bg-ground px-2 py-1" data-post-script="" /> + </label> + <div className="flex flex-wrap items-center gap-1.5"> + <button type="button" className={btn} disabled={script === (n.script ?? "")} onClick={() => void set({ script })} data-post-script-save=""> + Save script + </button> + <input value={dir.note} onChange={(e) => setDir({ ...dir, note: e.target.value })} placeholder="direction (kept with the take)" className="min-w-0 flex-1 rounded border border-seam bg-ground px-1.5 py-0.5" data-post-retake-note="" /> + <input value={dir.voice} onChange={(e) => setDir({ ...dir, voice: e.target.value })} placeholder={String(k.voice)} className="w-16 rounded border border-seam bg-ground px-1 py-0.5" aria-label="voice" data-post-retake-voice="" /> + <button type="button" className={btn} disabled={!script.trim() || job?.state === "running"} onClick={() => void retake()} data-post-retake=""> + {job?.state === "running" ? "Synthesizing on the editor…" : "Re-take with direction"} + </button> + {job?.state === "failed" && <span className="text-[var(--color-blocking,#c33)]">{job.error}</span>} + </div> + </section> + + {/* THE MIX, this post's. */} + <section className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-mix-knobs=""> + <h2 className="micro m-0 w-full">the mix (this post; absent: the cut's)</h2> + {mixKnob("wet", "wet", { step: 0.05, min: 0, max: 1 })} + {mixKnob("lead", "lead", { step: 0.05, min: 0, max: 5 })} + {mixKnob("tail", "tail", { step: 0.05, min: 0, max: 5 })} + {mixKnob("ramp", "ramp", { step: 0.1, min: 0, max: 5 })} + {mixKnob("linger", "linger", { step: 0.1, min: 0, max: 30 })} + {mixKnob("short", "short clip", { options: ["hold", "loop"] })} + {mixKnob("attach", "attachment", { options: ["under", "after"] })} + {mixKnob("clip", "clip", { options: ["read", "full"] })} + </section> + {status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>} + {error && ( + <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-narration-error=""> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -10,6 +10,7 @@ import SweepProject from "./SweepProject"; import TakesPage from "./TakesPage"; import TakesComparePage from "./TakesComparePage"; import NarrationPage from "./NarrationPage"; +import RecordPage from "./RecordPage"; import ReviewPage from "./ReviewPage"; import ClipDeckPage from "./ClipDeckPage"; import PlayCutPage from "./PlayCutPage"; @@ -81,6 +82,8 @@ export default async function ProjectView({ // `/browse/<project>/narration` -- the narration script, card by card, // approved / edited / rejected before synthesis. if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />; + // `/projects/<project>/narration/record` -- the recording session: the cut's posts read aloud, part by part. + if (rest.length === 2 && rest[0] === "narration" && rest[1] === "record") return <RecordPage project={project} search={search} />; // `/browse/<project>/review` -- every drafted field, approved / rejected // before a final build, and the alternatives a draft task kept. if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />; diff --git a/umtool/components/projects/RecordPage.tsx b/umtool/components/projects/RecordPage.tsx @@ -0,0 +1,69 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { notFound } from "next/navigation"; +import AppShell from "@/components/shell/AppShell"; +import RecordSession, { type RecordItem } from "./RecordSession"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { projectHref } from "@/lib/hrefs"; +import { deckGeometry, deckOn } from "umtool-report-to-video/deck"; +import { draftScript, pickedTake, takeSourceOf } from "umtool-report-to-video/post-narration"; +import { normalizeParts, partsFileOf } from "@/lib/report/postNarrationCli.mjs"; +import { avatarEntryOf } from "umtool-report-to-video/post-avatars"; +import type { ProjectRef } from "@/lib/project-types"; + +// THE RECORDING SESSION (operator, 3 Nov: "I need to do a dramatic reading of +// this starting tomorrow"): /projects/<p>/narration/record walks the cut's +// post items in order -- each post's card and attachment, its SCRIPT as a +// teleprompter in its PARTS (the placeholder take's parts.json when there is +// one, else the script split the same way), recorded part by part, every part +// on disk as soon as it is kept (lib/report/recordSession.mjs), the post's +// recorded take made and picked when the last part is in. + +type Take = { file: string; engine?: string; voice?: string; seconds: number; parts?: unknown; source?: { kind?: string } }; +type Entry = Record<string, unknown> & { id: string; type?: string; text?: string; author?: string; handle?: string; date?: string; media?: Array<{ src: string; kind: string }>; narration?: { script?: string; takes?: Take[] } }; + +export default async function RecordPage({ project, search = {} }: { project: ProjectRef; search?: Record<string, string | undefined> }) { + const m = (await readManifest(project.dir)) as Record<string, unknown> | null; + if (!m) notFound(); + const render = (m.render ?? {}) as Record<string, unknown>; + const posts = ((Array.isArray(m.timeline) ? m.timeline : []) as Entry[]).filter((e) => e?.type === "post"); + if (!posts.length) notFound(); + const items: RecordItem[] = []; + for (const [i, e] of posts.entries()) { + const takes = e.narration?.takes ?? []; + const picked = pickedTake(e) as (Take & { index: number }) | null; + // The placeholder: the newest synthesized take (its parts the teleprompter's). + const placeholder = [...takes].reverse().find((t) => (takeSourceOf(t) as { kind: string }).kind === "tts") ?? null; + let parts = placeholder ? normalizeParts(placeholder.parts) : null; + if (placeholder && !parts) { + parts = normalizeParts(await readFile(path.join(project.dir, ...partsFileOf(placeholder.file).split("/")), "utf8").then((t) => JSON.parse(t), () => null)); + } + const recorded = takes.some((t) => (takeSourceOf(t) as { kind: string }).kind === "recorded"); + const av = e.handle ? avatarEntryOf(m, e.handle) : null; + items.push({ + id: e.id, n: i + 1, author: String(e.author ?? ""), handle: String(e.handle ?? ""), date: String(e.date ?? ""), + text: String(e.text ?? ""), + script: String(e.narration?.script ?? draftScript(e.text ?? "").script), + plays: !picked ? "none" : (takeSourceOf(picked) as { kind: string }).kind === "recorded" ? "recorded" : "placeholder", + recorded, + placeholder: placeholder ? { file: placeholder.file, seconds: placeholder.seconds, parts: (parts ?? []).map((p) => ({ n: p.n, para: p.para ?? 0, text: p.text ?? "", start: p.start, seconds: p.seconds, ...(p.file ? { file: p.file } : {}) })) } : null, + media: (e.media ?? []).slice(0, 1).map((x) => ({ src: x.src, kind: x.kind }))[0] ?? null, + avatar: av ? String((av[1] as { src?: string }).src ?? "") || null : null, + }); + } + const box = deckOn(render) ? deckGeometry(render).footage : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) }; + const want = search.post ? items.findIndex((x) => x.id === search.post) : -1; + const start = want >= 0 ? want : Math.max(0, items.findIndex((x) => !x.recorded)); + return ( + <div className="flex h-full flex-col"> + <AppShell + active="projects" + crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id), label: project.name }, { label: "record the narration" }]} + note={`${items.filter((x) => x.recorded).length} of ${items.length} posts recorded`} + /> + <main className="deck-main flex-1 overflow-auto p-4"> + <RecordSession project={project.id} items={items} start={start} box={{ width: box.width, height: box.height }} /> + </main> + </div> + ); +} diff --git a/umtool/components/projects/RecordSession.tsx b/umtool/components/projects/RecordSession.tsx @@ -0,0 +1,401 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { postBenchHref } from "@/lib/hrefs"; +import { scriptParts } from "umtool-report-to-video/post-narration"; +import { MIC_KEY, ls, useMic } from "./useMic"; + +// --------------------------------------------------------------------------- +// THE RECORDING SESSION, the client half (RecordPage.tsx): one post at a time, +// in the cut's order -- its card and attachment, the script as a teleprompter +// in its parts, the current part large -- recorded PART BY PART: +// +// Space Record / Stop (a count-in first, when it is on) +// r Redo the current part +// Enter the next part (or, the post done, the next post) +// n / p the next / previous post +// +// Each part is uploaded the moment it is stopped (POST /api/report/post- +// narration/record) -- on disk, so a crash loses at most the part being read +// and a reload resumes; when the last part is in, the post's recorded take is +// made (trimmed, joined with the parts' pauses, levelled to the placeholder's) +// and PICKED. +// --------------------------------------------------------------------------- + +type Part = { n: number; para: number; text: string; start?: number; seconds?: number; file?: string }; +export type RecordItem = { + id: string; + n: number; + author: string; + handle: string; + date: string; + text: string; + script: string; + plays: "recorded" | "placeholder" | "none"; + recorded: boolean; + placeholder: { file: string; seconds: number; parts: Part[] } | null; + media: { src: string; kind: string } | null; + avatar: string | null; +}; +type Session = { count: number | null; parts: Record<string, { file: string; text: string; at: string }> }; + +const COUNT_KEY = "umtool.record.count-in"; +const enc = encodeURIComponent; +const fileUrl = (project: string, rel: string) => `/api/report/file?project=${enc(project)}&path=${enc(rel)}`; +const postFileUrl = (project: string, rel: string) => `/api/report/post-item?project=${enc(project)}&file=${enc(rel)}`; + +export default function RecordSession({ project, items: initial, start, box }: { project: string; items: RecordItem[]; start: number; box: { width: number; height: number } }) { + const [items, setItems] = useState(initial); + const [at, setAt] = useState(start); + const item = items[at]; + const parts: Part[] = useMemo(() => { + const ph = item.placeholder?.parts ?? []; + return ph.length ? ph : scriptParts(item.script).map((p) => ({ n: p.n, para: p.para, text: p.text })); + // The post's script and placeholder, not its recorded state: a take made does not re-split it (nor clear the status). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [item.id, item.placeholder, item.script]); + const [session, setSession] = useState<Session>({ count: null, parts: {} }); + const [cur, setCur] = useState(0); + const [phase, setPhase] = useState<"idle" | "count" | "recording" | "saving" | "finishing">("idle"); + const [count, setCount] = useState(0); + const [countIn, setCountIn] = useState(true); + const [status, setStatus] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const mic = useMic(); + const kept = (n: number) => !!session.parts[String(n)] && session.count === parts.length; + + useEffect(() => setCountIn(ls.get(COUNT_KEY) !== "0"), []); + // The post's session: what was kept before (a reload resumes at the first part not kept). + const loadSession = useCallback(async () => { + const r = await fetch(`/api/report/post-narration/record?project=${enc(project)}&id=${enc(item.id)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as { session?: Session }; + const s = j.session ?? { count: null, parts: {} }; + setSession(s); + const firstOpen = parts.findIndex((p) => !(s.parts[String(p.n)] && s.count === parts.length)); + setCur(firstOpen < 0 ? Math.max(0, parts.length - 1) : firstOpen); + }, [project, item.id, parts]); + useEffect(() => { + setStatus(null); + setError(null); + void loadSession(); + try { + window.history.replaceState(null, "", `?post=${enc(item.id)}`); + } catch { + // not in a browser history + } + }, [loadSession, item.id]); + + const done = parts.length > 0 && parts.every((p) => kept(p.n)); + + const finish = useCallback(async () => { + setPhase("finishing"); + const r = await fetch("/api/report/post-narration/record", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "finish", id: item.id, script: item.script }) }); + const j = (await r.json().catch(() => ({}))) as { take?: { file: string; seconds: number }; error?: string }; + setPhase("idle"); + if (!r.ok || !j.take) { + setError(j.error ?? `HTTP ${r.status}`); + return; + } + setItems((xs) => xs.map((x) => (x.id === item.id ? { ...x, recorded: true, plays: "recorded" } : x))); + setSession({ count: null, parts: {} }); + setStatus(`kept: ${j.take.file.split("/").pop()} (${j.take.seconds.toFixed(1)} s), picked — Enter for the next post`); + }, [project, item.id, item.script]); + + const record = useCallback(async () => { + if (phase !== "idle" || !parts.length) return; + setError(null); + if (countIn) { + setPhase("count"); + for (const c of [3, 2, 1]) { + setCount(c); + await new Promise((res) => setTimeout(res, 650)); + } + setCount(0); + } + if (!(await mic.start())) { + setPhase("idle"); + setError(mic.error ?? "the microphone did not open"); + return; + } + setPhase("recording"); + }, [phase, parts.length, countIn, mic]); + + const stop = useCallback(async () => { + if (phase !== "recording") return; + const blob = await mic.stop(); + if (!blob || !blob.size) { + setPhase("idle"); + return; + } + setPhase("saving"); + const p = parts[cur]; + const fd = new FormData(); + fd.set("project", project); + fd.set("id", item.id); + fd.set("n", String(p.n)); + fd.set("count", String(parts.length)); + fd.set("text", p.text); + fd.set("para", String(p.para)); + fd.set("part", blob, `p${p.n}.${/ogg/.test(blob.type) ? "ogg" : "webm"}`); + const r = await fetch("/api/report/post-narration/record", { method: "POST", body: fd }); + const j = (await r.json().catch(() => ({}))) as { session?: Session; error?: string }; + setPhase("idle"); + if (!r.ok || !j.session) { + setError(`part ${p.n} was NOT saved: ${j.error ?? `HTTP ${r.status}`} — record it again`); + return; + } + setSession(j.session); + const s = j.session; + const next = parts.findIndex((q) => !(s.parts[String(q.n)] && s.count === parts.length)); + if (next < 0) await finish(); + else setCur(next); + }, [phase, mic, parts, cur, project, item.id, finish]); + + const redo = useCallback(async () => { + if (phase !== "idle") return; + const p = parts[cur]; + if (p && kept(p.n)) { + const r = await fetch("/api/report/post-narration/record", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "discard", id: item.id, n: p.n }) }); + const j = (await r.json().catch(() => ({}))) as { session?: Session }; + if (j.session) setSession(j.session); + } + await record(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [phase, parts, cur, project, item.id, record, session]); + + const go = useCallback((k: number) => { + if (phase !== "idle") return; + setAt((x) => Math.max(0, Math.min(items.length - 1, x + k))); + }, [phase, items.length]); + + // The keys of a reading session. + useEffect(() => { + const onKey = (ev: KeyboardEvent) => { + const tgt = ev.target as HTMLElement | null; + // A text box or a select keeps its keys; a checkbox (the count-in) does not -- Space still records. + if (tgt?.closest("textarea, select, input:not([type=checkbox])")) return; + if (ev.metaKey || ev.ctrlKey || ev.altKey) return; + if (ev.key === " ") { + ev.preventDefault(); + if (phase === "recording") void stop(); + else void record(); + } else if (ev.key === "r") { + ev.preventDefault(); + void redo(); + } else if (ev.key === "Enter") { + ev.preventDefault(); + if (done || item.recorded && !Object.keys(session.parts).length) go(1); + else if (phase === "idle") setCur((c) => Math.min(parts.length - 1, c + 1)); + } else if (ev.key === "n") go(1); + else if (ev.key === "p") go(-1); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [phase, stop, record, redo, done, item.recorded, session.parts, go, parts.length]); + + // Play a kept part back, or the placeholder's part for reference. + const player = useRef<HTMLAudioElement | null>(null); + const stopAt = useRef<number | null>(null); + const play = (src: string, from = 0, seconds: number | null = null) => { + const a = player.current; + if (!a) return; + a.src = src; + a.currentTime = 0; + const go2 = () => { + try { + a.currentTime = from; + } catch { + // seeks once it can + } + stopAt.current = seconds ? from + seconds : null; + void a.play().catch(() => {}); + }; + if (a.readyState >= 1) go2(); + else a.addEventListener("loadedmetadata", go2, { once: true }); + }; + const playPlaceholderPart = (p: Part) => { + const ph = item.placeholder; + if (!ph) return; + if (p.file) play(fileUrl(project, p.file)); + else if (typeof p.start === "number") play(fileUrl(project, ph.file), p.start, p.seconds ?? null); + else play(fileUrl(project, ph.file)); + }; + + const recordedCount = items.filter((x) => x.recorded).length; + const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); + const scale = 0.42; + + return ( + <div className="mx-auto grid max-w-[1500px] grid-cols-1 gap-4 min-[1100px]:grid-cols-[260px_minmax(0,1fr)]" data-record-session={item.id} data-record-phase={phase} data-record-part={parts[cur]?.n ?? 0}> + {/* The jump list: every post, recorded or on its placeholder. */} + <nav className="max-h-[80vh] overflow-auto rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12px]" data-record-list=""> + <div className="micro mb-1" data-record-progress={recordedCount}> + recorded {recordedCount} of {items.length} + </div> + <ol className="m-0 list-none space-y-0.5 p-0"> + {items.map((x, i) => ( + <li key={x.id}> + <button + type="button" + onClick={() => phase === "idle" && setAt(i)} + className={cn("flex w-full items-center gap-1.5 rounded px-1.5 py-0.5 text-left", i === at ? "bg-[var(--color-sel)]/20" : "hover:bg-white/5")} + data-record-jump={x.id} + data-record-state={x.recorded ? "recorded" : x.placeholder ? "placeholder" : "none"} + > + <span className={cn("inline-block h-2 w-2 shrink-0 rounded-full", x.recorded ? "bg-emerald-500" : x.placeholder ? "bg-amber-400" : "bg-white/20")} /> + <span className="font-mono tabular-nums">{x.n}</span> + <span className="truncate text-text-2">{x.date.slice(5, 10)} {x.text.replace(/\s+/g, " ").slice(0, 40)}</span> + </button> + </li> + ))} + </ol> + </nav> + + <section className="min-w-0 space-y-3"> + <div className="flex flex-wrap items-center gap-2 text-[12.5px]"> + <button type="button" className={btn} disabled={at === 0 || phase !== "idle"} onClick={() => go(-1)} data-record-prev=""> + ‹ P + </button> + <span className="font-mono"> + post {item.n} of {items.length} + </span> + <button type="button" className={btn} disabled={at === items.length - 1 || phase !== "idle"} onClick={() => go(1)} data-record-next=""> + N › + </button> + <span className={cn("rounded px-1.5", item.recorded ? "bg-emerald-500/20" : "bg-amber-400/20")} data-record-item-state={item.recorded ? "recorded" : "placeholder"}> + {item.recorded ? "recorded" : item.placeholder ? "on its placeholder" : "no take yet"} + </span> + <a href={postBenchHref(project, item.id)} className="ink-link ml-auto"> + its bench › + </a> + </div> + + {/* The post: its card (the render's own page) and its attachment. */} + <div className="flex flex-wrap items-start gap-3"> + <div className="relative overflow-hidden rounded border border-seam bg-black" style={{ width: box.width * scale, height: box.height * scale }}> + <iframe + title={`post ${item.id}`} + src={`/api/report/post-item?project=${enc(project)}&id=${enc(item.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}`} + className="absolute left-0 top-0 border-0" + style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }} + data-record-card="" + /> + </div> + {item.media && ( + <div className="w-56" data-record-media={item.media.kind}> + {item.media.kind === "image" ? ( + // eslint-disable-next-line @next/next/no-img-element + <img src={postFileUrl(project, item.media.src)} alt="" className="w-full rounded" /> + ) : ( + <video src={postFileUrl(project, item.media.src)} muted controls preload="metadata" className="w-full rounded" /> + )} + </div> + )} + </div> + + {/* The mic. */} + <div className="flex flex-wrap items-center gap-2 text-[12.5px]"> + <select value={mic.device} onChange={(e) => void mic.open(e.target.value)} onFocus={() => !mic.devices.length && void mic.open(ls.get(MIC_KEY) ?? undefined)} aria-label="microphone" data-record-mic=""> + {!mic.devices.length && <option value="">microphone…</option>} + {mic.devices.map((d) => ( + <option key={d.deviceId} value={d.deviceId}> + {d.label || d.deviceId.slice(0, 8)} + </option> + ))} + </select> + <div className="h-2.5 w-40 overflow-hidden rounded bg-black/40" aria-label="level" data-record-level={Math.round(mic.level * 100)}> + <div className={cn("h-full", mic.level > 0.85 ? "bg-red-500" : "bg-emerald-500")} style={{ width: `${mic.level * 100}%` }} /> + </div> + <label className="flex items-center gap-1"> + <input + type="checkbox" + checked={countIn} + onChange={(e) => { + setCountIn(e.target.checked); + ls.set(COUNT_KEY, e.target.checked ? "1" : "0"); + }} + data-record-count-in="" + /> + count-in + </label> + <span className="text-text-2">Space record / stop · r redo the part · Enter next part · n / p next / previous post</span> + </div> + + {/* The teleprompter: every part, the current one large. */} + <ol className="m-0 list-none space-y-2 p-0" data-record-teleprompter=""> + {parts.map((p, i) => ( + <li + key={p.n} + className={cn( + "rounded border-l-4 px-3 py-2 leading-snug", + i === cur ? "border-amber-400 bg-amber-400/10 text-[26px] text-text" : "border-transparent text-[15px] text-text-2", + kept(p.n) && i !== cur && "border-emerald-500/70", + )} + onClick={() => phase === "idle" && setCur(i)} + data-record-prompt={p.n} + data-record-prompt-current={i === cur ? "1" : undefined} + data-record-prompt-kept={kept(p.n) ? "1" : undefined} + > + {parts.length > 1 && <span className="micro mr-2 align-middle">{p.n}/{parts.length}</span>} + {p.text} + {i === cur && ( + <span className="mt-1 flex flex-wrap gap-1.5 text-[12px]"> + {kept(p.n) && ( + <button type="button" className={btn} onClick={() => play(`/api/report/post-narration/record?project=${enc(project)}&id=${enc(item.id)}&n=${p.n}&v=${enc(session.parts[String(p.n)]?.at ?? "")}`)} data-record-play-part={p.n}> + Play it back + </button> + )} + {item.placeholder && ( + <button type="button" className={btn} onClick={() => playPlaceholderPart(p)} data-record-play-placeholder={p.n}> + Play the placeholder + </button> + )} + </span> + )} + </li> + ))} + {!parts.length && <li className="text-text-2">no script yet — write one on its bench</li>} + </ol> + + <div className="flex flex-wrap items-center gap-2"> + {phase === "count" && ( + <span className="text-[28px] font-bold tabular-nums" data-record-count={count}> + {count} + </span> + )} + <button + type="button" + className={cn(buttonVariants({ variant: phase === "recording" ? "outline" : "go", size: "sm" }))} + disabled={(phase !== "idle" && phase !== "recording") || !parts.length} + onClick={() => void (phase === "recording" ? stop() : record())} + data-record-toggle="" + > + {phase === "recording" ? "Stop (Space)" : `Record part ${parts[cur]?.n ?? 1} (Space)`} + </button> + <button type="button" className={btn} disabled={phase !== "idle" || !parts.length} onClick={() => void redo()} data-record-redo=""> + Redo part (r) + </button> + <button type="button" className={btn} disabled={phase !== "idle" || cur >= parts.length - 1} onClick={() => setCur((c) => c + 1)} data-record-next-part=""> + Next part (Enter) + </button> + {phase === "recording" && <span className="text-red-400" data-record-recording="">● recording part {parts[cur]?.n}</span>} + {phase === "saving" && <span className="text-text-2">saving the part…</span>} + {phase === "finishing" && <span className="text-text-2">joining the parts into the take…</span>} + {status && <span className="text-emerald-500" data-record-status="">{status}</span>} + {error && <span className="text-[var(--color-blocking,#c33)]" data-record-error="">{error}</span>} + </div> + {/* eslint-disable-next-line jsx-a11y/media-has-caption */} + <audio + ref={player} + className="hidden" + onTimeUpdate={(e) => { + if (stopAt.current !== null && e.currentTarget.currentTime >= stopAt.current) e.currentTarget.pause(); + }} + data-record-player="" + /> + </section> + </div> + ); +} diff --git a/umtool/components/projects/bench/benchMedia.ts b/umtool/components/projects/bench/benchMedia.ts @@ -123,3 +123,29 @@ export function renderedFileMedia({ peaksOnSource: (p) => peaksOnSource(p, span, map), }; } + +/** + * A FILE OF THE PROJECT on its own clock (the post bench, lane/post-narration): + * a post item's attachment or a narration take -- its seconds are its own, so + * every mapping is the identity. `seconds` its length. + */ +export function projectFileMedia({ project, path, seconds, v = null }: { project: string; path: string; seconds: number; v?: string | number | null }): BenchMedia { + const q = `project=${enc(project)}&path=${enc(path)}${v ? `&v=${enc(String(v))}` : ""}`; + const id = (t: number) => t; + const span = { from: 0, to: seconds }; + return { + kind: "file", + key: `${path}|${v ?? ""}`, + src: `/api/report/file?${q}`, + span, + clock: span, + clockOf: id, + sourceOfClock: id, + elOf: id, + clockOfEl: id, + clockGaps: (gaps) => gaps, + audioUrl: (s) => `/api/report/audio?${q}&from=${s.from}&to=${s.to}`, + peaksUrl: `/api/report/peaks?${q}&from=0&to=${seconds}`, + peaksOnSource: (p) => p, + }; +} diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -8,7 +8,7 @@ import { } from "@/lib/projects/report.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { buttonVariants } from "@/components/ui/button"; -import { postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs"; +import { narrationRecordHref, postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs"; import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs"; import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import FetchUnfetchedButton from "../FetchUnfetchedButton"; @@ -363,6 +363,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor return ( <> <div className="flex flex-wrap items-start gap-3"> + {/* A cut of posts is read aloud: its recording session (lane/post-narration). */} + {entries.some((x) => x.kind === "post") && ( + <Link href={narrationRecordHref(project.id)} className={buttonVariants({ variant: "go", size: "sm" })} data-record-narration-link=""> + Record the narration › + </Link> + )} {/* ---- the way in ---- Every clip row carries a bench link, which is the right control for "go to that one" and the wrong one for "start". Reviewing a cut is 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/components/projects/useMic.ts b/umtool/components/projects/useMic.ts @@ -0,0 +1,98 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; + +// THE MICROPHONE for a recording (the post bench, the recording session): +// its devices, the one chosen (remembered per browser), a live level, and a +// MediaRecorder -- opus in webm (Chromium) or ogg (Firefox). Localhost is a +// secure context, so getUserMedia works with no network beyond it. + +export const MIC_KEY = "umtool.post-narration.mic"; + +export const ls = { + get: (k: string) => { + try { + return window.localStorage.getItem(k); + } catch { + return null; + } + }, + set: (k: string, v: string) => { + try { + window.localStorage.setItem(k, v); + } catch { + // private mode: not remembered + } + }, +}; + +/** The microphone: its devices, the one chosen (remembered), a level, a recorder. */ +export function useMic() { + const [devices, setDevices] = useState<MediaDeviceInfo[]>([]); + const [device, setDevice] = useState<string>(""); + const [level, setLevel] = useState(0); + const [error, setError] = useState<string | null>(null); + const stream = useRef<MediaStream | null>(null); + const rec = useRef<MediaRecorder | null>(null); + const chunks = useRef<Blob[]>([]); + const raf = useRef(0); + const ctx = useRef<AudioContext | null>(null); + const open = useCallback(async (id?: string) => { + setError(null); + try { + stream.current?.getTracks().forEach((t) => t.stop()); + const s = await navigator.mediaDevices.getUserMedia({ audio: id ? { deviceId: { exact: id }, echoCancellation: false, noiseSuppression: false, autoGainControl: false } : { echoCancellation: false, noiseSuppression: false, autoGainControl: false } }); + stream.current = s; + const list = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput"); + setDevices(list); + const now = s.getAudioTracks()[0]?.getSettings().deviceId ?? id ?? ""; + setDevice(now); + if (now) ls.set(MIC_KEY, now); + ctx.current ??= new AudioContext(); + const an = ctx.current.createAnalyser(); + an.fftSize = 1024; + ctx.current.createMediaStreamSource(s).connect(an); + const buf = new Float32Array(an.fftSize); + cancelAnimationFrame(raf.current); + const tick = () => { + an.getFloatTimeDomainData(buf); + let acc = 0; + for (const v of buf) acc += v * v; + setLevel(Math.min(1, Math.sqrt(acc / buf.length) * 4)); + raf.current = requestAnimationFrame(tick); + }; + tick(); + return s; + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + return null; + } + }, []); + useEffect(() => () => { + cancelAnimationFrame(raf.current); + stream.current?.getTracks().forEach((t) => t.stop()); + }, []); + const start = useCallback(async () => { + const s = stream.current ?? (await open(ls.get(MIC_KEY) ?? undefined)); + if (!s) return false; + chunks.current = []; + const type = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/webm"].find((t) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(t)); + const r = new MediaRecorder(s, type ? { mimeType: type } : undefined); + r.ondataavailable = (ev) => ev.data.size && chunks.current.push(ev.data); + r.start(250); + rec.current = r; + return true; + }, [open]); + const stop = useCallback( + () => + new Promise<Blob | null>((resolve) => { + const r = rec.current; + if (!r || r.state === "inactive") return resolve(null); + r.onstop = () => resolve(new Blob(chunks.current, { type: r.mimeType || "audio/webm" })); + r.stop(); + }), + [], + ); + return { devices, device, level, error, open, start, stop }; +} + diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -82,7 +82,10 @@ Inbox cannot disagree about what is wrong with one. | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) | | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | -| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words | +| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words | +| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) | +| `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is | +| `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | | `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -644,8 +644,8 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused | Knob | In umtool | From a terminal | Route | |---|---|---|---| -| `hold` — the item's whole length in seconds (1–120; absent: the duration rule) | post bench, **hold** | `umtool posts set-item <p> <item> hold=12` (`hold=off`) | `POST /api/report/post-item {project, op: "set", id, patch: {hold}, token}` | -| `mediaLayout` — `grid`: its 2-4 images at once (3.5 s + 1 per extra); absent: one after another | post bench, **images** | `layout=grid` (`layout=sequence`) | same, `patch: {mediaLayout}` | +| `hold` — the item's whole length in seconds (1–120; absent: the pacing rule, the item is its read) | post bench, **hold** | `umtool posts set-item <p> <item> hold=12` (`hold=off`) | `POST /api/report/post-item {project, op: "set", id, patch: {hold}, token}` | +| `mediaLayout` — `grid`: its 2-4 images at once (one picture of the read); absent: one after another, cycling | post bench, **images** | `layout=grid` (`layout=sequence`) | same, `patch: {mediaLayout}` | | `redact` — other authors (the posts it answers, the one it quotes, a repost's original): absent, the privacy rule (blurred unless a subject or gold/grey verified); `false` shows them (judged public); `true` blurs even the verified | post bench, **other authors** | `redact=off` · `redact=on` · `redact=auto` | same, `patch: {redact}` | | `media[i].start`, `media[i].end` — a video's or a GIF's in and out, its own seconds (at least 0.5 s apart) | post bench, **in / out**, **In at playhead**, **Out at playhead**, **Whole** | `media.0.start=1.5 media.0.end=6` · `media.0.trim=off` | same, `patch: {media: {"0": {start, end}}}` | | `media[i].mute` — `true`: the video plays silent | post bench, **its sound** | `media.0.mute=on` (`=off`) | same | @@ -661,6 +661,36 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused | move, remove, a section, a group | the Cut tab's row (⠿, ⋯, the section bars), Play's reel strip | `umtool timeline <p> move\|remove\|section-move\|section-add …` | as a clip's | | the card's page, an attachment, the faces | Play the cut, the post bench | — | `GET /api/report/post-item?project&id&w&h[&phase][&take]` · `?project&file=posts-media/…` · `?project&font=regular\|bold` | +## A narrated post item + +A post item read aloud, its attachment muffled under the read ([report-video.md](report-video.md#narrated-post-items): +the shape, the mix, recordings, parts, the best part). One writer for a post's narration, `updatePostNarration` +(`lib/report/manifest.mjs`; several at once `updatePostNarrations`, the best part `fitPostItems`, the cut's mix +`updatePostNarrationRender`), refused in the build's words (`validatePostNarration`). Its bench is the post bench +(`/projects/<p>/post/<id>`), its route `POST /api/report/post-narration {project, op, id, …, token}`. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `narration.script` — what is read: the post, verbatim; Orpheus's tags for emotion | post bench, **script**, **Save script** | `umtool posts narrate <p> <item> --script "…"` · every post's drafted: `--all --draft-scripts [--force]` | `op: "set", patch: {script}` | +| **the recording session** — the cut's posts read aloud in order, part by part, each part on disk as soon as it is kept (a reload resumes), the post's recorded take made and picked when its last part is in | `/projects/<p>/narration/record` (the Cut tab's **Record the narration**): the jump list (recorded / placeholder, n of N), the post's card and attachment, the teleprompter in its parts (the placeholder's `parts.json`, else the script split), the mic, the level, count-in; **Space** record / stop, **r** redo the part, **Enter** the next part (the post done: the next post), **n** / **p** posts; **Play it back**, **Play the placeholder** | — | `GET /api/report/post-narration/record?project&id[&n]` · `POST` multipart `{project, id, n, count, text, para, part}` · `POST {op: "discard", id, n}` · `POST {op: "finish", id}` | +| a recorded take — your own read, part by part, kept as `take-<n>.recorded-<label>.wav`, picked | post bench, **record your read**: the mic, the level, **Record** (R) / **Stop** (S) / **Redo part** / **Next part**, **Keep** / **Discard**, **voice** (the label, default `operator`) | — | `POST` multipart `{project, id, label, script?, part[], text[], para[]}` | +| a synthesized take — the editor's tts op, with direction | post bench, **Re-take with direction** (a note, a voice) | `umtool posts narrate <p> <item> --take [--note "…"] [--voice v] [--engine e] [--speed s]` · every missing one: `--all --take` | `op: "take"` → `{jobId, file}` · `GET ?project&id&job&file` keeps it when done | +| a derived take — a take run through the editor's `enhance` or `convert` (a stock synthetic voice) into a NEW take, the original kept; "not installed" until the editor has the engine | post bench, **run AI on take #n** (the op, an engine, a stock voice) → **Run → a new take**; a derived take's **Re-run**; a recording's **Re-record** with **then re-run the chain** | `umtool posts narrate <p> <item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` | `op: "derive", from, op2, engine?, voice?` → `{jobId, file}` (or `{installed: false}`) · `GET ?project&id&job&file&derive=<from>&op=…` keeps it | +| delete a take (soft: its file to the post's `.trash/`) | post bench, the take's **Delete** | `--delete <n>` | `op: "delete", take` (an index) | +| `narration.pick` — the take that plays | post bench, the take's **Pick** | `--pick <n>` (1 = the first, as `--list` shows) | `patch: {pick}` (an index) | +| `narration.approved` — the picked take on this script, approved (a new script or pick takes it away) | post bench, **approved** | `--approve` · `--unapprove` | `patch: {approved: true \| null}` | +| `narration.off` — keep it all, play un-narrated | post bench, **narrated** | `--off` · `--on` | `patch: {off: true \| null}` | +| `lead`, `tail`, `ramp`, `linger`, `wet`, `lowpassHz`, `duck`, `short` (`hold`\|`loop`), `clip` (`read`\|`full`), `attach` (`under`\|`after`), `lufs` — this post's mix | post bench, **the mix**; the read lane's voice block dragged sets `lead` | `umtool posts narrate <p> <item> lead=0.6 wet=0.25 short=loop …` (`k=` back to the cut's) | `patch: {…}` | +| the attachment's window — its in and out for the read; why it was chosen (`narration.window`) | post bench, the attachment lane's handles; **Re-pick best**; **Play whole attachment** | `umtool posts fit <p> --all \| <item>… [--linger s]` · `posts set-item <p> <item> fit=read[:<linger>]` | `op: "fit", linger?` · the handles: `POST /api/report/post-item {op: "set", patch: {media}}` | +| `render.postNarration` — the cut's mix (every key above but `attach`, and `engine`, `voice`) | — | `umtool posts narrate <p> --cut wet=0.25 clip=full …` | — | +| undo the last write | post bench, **Undo last change** | `umtool timeline <p> undo` | `op: "undo"` | +| the hand-made batch | — | `umtool posts narrate <p> --import` (`narration/posts/index.json`, a take's `take-<n>.parts.json`) | — | +| the authors' pictures (`postAvatars`) | drawn on every card | `umtool posts avatar <p> <handle> <image>` (`off`) · `umtool posts avatars <p>` | — | + +**The walk**: the bench's header counts the cut's reading (recorded n of N, how many on a synthesized placeholder, +none, approved) and links the next post to record; **N** / **P** walk the cut's posts, **Space** plays the item as the +render will (the take over the muffled attachment). + ## The source backlog (Sources · Prioritize · Re-sweep when complete) The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -443,29 +443,31 @@ the generator. handle, the date, the words, the counts, "reposted by", the posts it answers above it (a thread line down to it), the post it quotes inside it — in the deck's palette and faces, by the browser the build already uses for the chrome (`postCardHtml`; never a -screenshot of the platform). Its attachments play inside it: the words are read -first, then each attachment in turn — a video with its sound, from its trim; a GIF -looped; an image held (pushed in on with `push`); 2-4 images at once with -`mediaLayout: "grid"`. The layout (`postLayout`) is decided from the words: no -attachment, the card alone; words that fit beside the attachments at a readable size, -the card on the left and the attachments in a slot on the right, the first one's -first frame up while the words are read; words that do not, the card alone while it -is read, then the attachments large under a strip naming the post. Under the deck it +screenshot of the platform). **One layout** (operator, 2 Nov: "the gallery cycle +needs to be shown like a video and text stays on the screen the whole time"): no +attachment, the card alone; with attachments, the card with its FULL text on the left +for the item's whole length (at the size that fits; the page shrinks the words +further if it must) and the attachments beside it in a slot, played as ONE sequence +like a video WHILE the words are read — a video from the item's first frame, with its +sound, from its trim; a GIF looped; the images cycling, each crossfading in (0.3 s) +over the last (pushed in on with `push`); 2-4 images at once with `mediaLayout: +"grid"`. Never the card first and a gallery after, never a strip. Under the deck it is framed into the footage box like a clip, so the rail's pip, the section bars and the date (its day; the subtitle "author @handle on X", "reposted on X", "replying on X") ride over it; its QR is the post (`deckQrUrl`: its own page, or its archive's under `qr.links: "archive"` with a `siteChannel`). -**The duration rule** (`post-item.mjs`, `POST_READ` and its neighbours): +**The pacing rule** (`post-item.mjs`, `postItemPlan`; operator, 2 Nov: "read out every +post, and not linger too long after finishing the read"): the item is its READ, and the +attachments play beside the words within it. | | seconds | |---|---| -| reading the post | `clamp(1 + words / 3, 3, 15)` — 3 words a second (about 180 a minute), a second to find the text first; the cap keeps a 500-word post from stalling the reel (it is shown at the size that fits, and `hold` gives it more) | -| + each post it answers, and the post it quotes | `clamp(words / 3, 1, 4)` — context, not the post | -| + a video | its trimmed span, `end − start` (at least 0.5) | -| + a GIF | looped to at least 3 s (one pass when longer, at most 10) | -| + an image | 3.5 | -| + a grid of 2-4 images | 3.5 + 1 per image after the first | +| the read, un-narrated | the reading time: `clamp(1 + words / 3, 3, 15)` — 3 words a second (about 180 a minute), a second to find the text first — + each post it answers, and the post it quotes, `clamp(words / 3, 1, 4)` (context, not the post) | +| the read, narrated | lead + the take + tail + linger (0.4 + take + 0.3 + 1.8: the item ends `linger` after the words; [Narrated post items](#narrated-post-items)) | +| 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. Shorter than the read: its last frame held (`short: "loop"` loops it) | +| pictures | the read's time left after the videos, shared out: each image (or a GIF, looped; or a grid, one picture) at least 1.5 s (`POST_PICTURE_MIN`) | +| the item | max(the read, the attachments) | | `hold` | replaces the whole: a longer hold holds the last thing up, a shorter one cuts the attachments short at it | Words are runs of non-space; a link is one word; a repost's `RT @x:` prefix is its @@ -513,6 +515,134 @@ on Play's clock); the Cut tab lists it with its own glyph; the post bench asks the editor to transcribe a video's words (`pnpm ops transcribe`'s op: a local file, a job; never ASR by hand), which then show under it in Play and the render. +### Narrated post items + +A post item may be READ ALOUD (`report-to-video/post-narration.mjs`): its `narration` +is a script and takes — a person's own recording (the primary path: operator, 2 Nov, +"I think I'll record my voice") or a stock synthetic voice the EDITOR synthesizes +(`pnpm ops tts`; Orpheus `zac` by default, a placeholder for timing) — and the item's +own attachment plays UNDER the read, its sound low-passed and quiet while the voice +speaks, then crossfaded back to its clean, full sound. The operator's hand-made demo +(narr-demo/mix.sh, 2 Nov) is the reference; its numbers are the defaults. + +```jsonc +"narration": { + "script": "the post, verbatim\n\nits paragraphs kept <sigh>", // what is read; Orpheus tags allowed + "takes": [ + { "file": "narration/posts/<postId>/take-1.orpheus-zac.wav", "engine": "orpheus", "voice": "zac", + "seconds": 13.71, "script": "…", "at": "…", "lufs": -21.3, "note": "direction, kept with it", + "parts": [{ "n": 1, "para": 0, "text": "…", "file": "…/take-1.parts/p01.wav", "start": 0, "seconds": 6.2, "gapBefore": 0 }] }, + { "file": "narration/posts/<postId>/take-2.recorded-operator.wav", "engine": "recorded", "voice": "operator", "seconds": 14.2 } + ], + "pick": 1, "approved": true, // the take that plays; approved on this script and pick + "off": true, // keep it all, play un-narrated + "lead": 0.4, "wet": 0.25, …, // this post's mix (absent: render.postNarration's, else the defaults) + "window": { "media": 0, "start": 12.5, "end": 28.7, "score": 1.2, "reason": "…" } // why posts fit chose the span +} +``` + +**The takes are files of the project**, `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav` +(`take-<n>.recorded-<label>.wav` for a recording), with `narration/posts/index.json` +the hand-made batch's list — `umtool posts narrate <p> --import` reads it into the +manifest in one undoable write. umtool never synthesizes: `posts narrate <p> <item> +--take [--note "…"]` and the bench's **Re-take with direction** ask the editor's tts op +(a job on its queue) to write the next take there, then measure it, append it and pick it. + +**The mix, inside the build's audio graph** (`postNarrationFilters`, frame-accurate, +the item's true length — so the deck's rail and date run on with it, never frozen): +the item's own sound split wet / dry; the wet low-passed at `lowpassHz` twice at `wet` +until `lead + take + tail`, then ramped to silence over `ramp` while the dry ramps up +from silence; the voice levelled to `lufs` (its measured loudness), the narrator's +compressor (threshold 0.1, ratio 3) and ×1.5 make-up, delayed by `lead`; all three +mixed without normalising under a 0.95 limiter. Measured against the demo: the same +segment lengths to the millisecond, its levels within 0.2 dB in the read and after it. +Play the cut plays the take and muffles the attachment live (WebAudio: two low-pass +BiquadFilters and two gains on the same schedule). + +| `render.postNarration` / a post's `narration` | default | what it does | +|---|---|---| +| `lead` | 0.4 | the voice 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 clean over this | +| `linger` | 1.8 | the item ends this long after the words (the ramp happens inside it) | +| `clip` | `read` | a video longer than the read is cut to it (`full`: played whole, the demo's way) | +| `wet` | 0.30 | the muffled sound's level under the voice | +| `lowpassHz` | 650 | the muffle's low-pass (applied twice) | +| `duck` | `true` | `false`: the attachment plays full under the voice | +| `short` | `hold` | a video shorter than the read: its last frame held, or `loop` | +| `attach` | `under` | one post's: `after` reads over the card first, then plays the attachments whole | +| `lufs` | −21 | the voice levelled to this before the compressor (where Orpheus `zac` reads) | +| `engine`, `voice` | `orpheus`, `zac` | what a new synthesized take asks for (the cut's, or one post's) | + +**Scripts are the post, VERBATIM** (operator: "stick to the script! Only adjust +emotion"): `posts narrate <p> --all --draft-scripts` cleans them only to be spoken +(@handles, links and emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; the +paragraphs kept). Emotion is Orpheus's tags. A shorter read is only ever the +operator's own edit. + +**A long read, part by part** (`scriptParts`: the paragraphs, a paragraph over 60 +words split at its sentence ends): a take may be COMPOSED OF PARTS, joined with 0.6 s +between paragraphs and 0.25 s inside one (`POST_PART_GAP`); `--import` reads a take's +`take-<n>.parts.json`, and a recording is recorded part by part. + +**The recording session** — `/projects/<p>/narration/record` (the Cut tab's **Record the +narration**), made for reading a whole cut (operator, 3 Nov: "I need to do a dramatic reading +of this starting tomorrow"): it walks the cut's posts in order — a jump list with each post +recorded or still on its placeholder, n of N — showing the post's card (the render's own +page: text, avatar, date) and its attachment, and the SCRIPT as a teleprompter in its PARTS +(the placeholder take's `parts.json`, else the script split by `scriptParts`), the part being +read large. **Space** records and stops (a 3-2-1 count-in first, a toggle), **r** redoes the +part, **Enter** goes on (the post done: to the next post), **n** / **p** walk the posts; +**Play it back** and **Play the placeholder** (the synthesized part, for reference). Each +part is written to `narration/posts/<postId>/.recording-<label>/` the moment it is stopped +(`lib/report/recordSession.mjs`: a crash loses at most the part being read, a reload +resumes at the first part not kept); when the last part is in, the parts become the post's +recorded take (below) and it is picked. Chromium and Firefox (webm or ogg opus), no network +beyond localhost. + +**Recorded takes** — the post bench's recording session: the mic (remembered per +browser), a level meter, a 3-2-1 count-in, the script as a teleprompter with the part +being read large, **Record / Stop / Redo part / Next part** (auto-advancing; R and S), +play back, **Keep** or **Discard**. Kept, `POST /api/report/post-narration` decodes +each part to 48 kHz mono, trims its silence at either end (detectSilence, leaving a +breath of room), joins the parts with the pauses and brings the whole to the level of +the project's synthesized takes by one gain under a −1 dBFS limiter — nothing else, no +cloning, no TTS — as `take-<n>.recorded-<label>.wav` (`label` default `operator`, a +guest's voice another), picked. It plays, mixes and renders exactly as a synthesized +take. A recorded take carries no synthetic-voice disclosure; a synthesized one's is +the cut's (`readCutDisclosure`). + +**What a take is** (operator: "pure AI voice, record voice, and run AI on recorded voice, +and re-run or re-record"): a `source` and the `steps` applied to it — `{kind: "tts", engine, +voice, script}` (the editor's tts), `{kind: "recorded", voice}` (the bench's recording) or +`{kind: "take", from: <take id>}` (DERIVED: a new take made from another, `steps: [{op, +engine?, voice?, params?, ranAt, job}]`). A derived take never overwrites the one it came +from; a parted take is processed part by part (its parts kept). The ops are the editor's, +each a job like tts: `enhance` (denoise, level, de-reverb; `POST /api/ops/voice-enhance`) +and `convert` (voice conversion: the performance kept, the timbre swapped for a STOCK +synthetic voice, never a real person's; `/api/ops/voice-convert`, disclosed as "voice +converted to a synthetic voice"). The engines are a follow-up lane's: until the editor has +one, the bench and `posts narrate --derive` say "not installed" and write nothing. The +bench lists the takes as a tree (each source take, its derived takes under it) with +**Pick**, **Re-run** (the same step from the same source, a new take), **Re-record** (a +recording's: record again; **then re-run the chain** re-applies the steps its derived +takes had) and **Delete** (soft: the file to `narration/posts/<postId>/.trash/`). + +**The best part of an attachment** (`umtool posts fit`, the bench's **Re-pick +best**; `lib/report/postFit.mjs`): a video longer than the read is cut to a window of +the read's length chosen by a scored scan — its sound's RMS (the window's mean and its +peak on the file's own range), the share of speech when it has a transcript, its scene +cuts (ffmpeg scdet) — the start snapped to a pause or a cut within 0.75 s, a slight +preference for the start on a tie; written as the attachment's in and out with +`narration.window` saying why. + +**The authors' pictures** (`post-avatars.mjs`): `postAvatars` maps a handle to a +picture in `posts-media/_avatars/` — copied from the archive's store (the editor's +capture-posts, a channel's `posts-media/_avatars/avatars.json`) by `posts reel`, a +post's insert and `umtool posts avatars <p>`, or set by hand with `umtool posts avatar +<p> <handle> <image>` (never replaced by the archive's). Every card that draws that +author unblurred shows it — the render, Play and the bench; a redacted author never. + ## The on-screen deck (`render.chrome`) Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -18,7 +18,7 @@ import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs"; import http from "node:http"; import { spawn, spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; import path from "node:path"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; @@ -1357,10 +1357,15 @@ const server = http.createServer((req, res) => { "-ac", "1", "-c:a", "pcm_s16le", wav, ], { stdio: "inherit" }); if (r.status !== 0) return json(res, 500, { ok: false, error: "ffmpeg failed writing the stub's voice" }); + // `out`: the editor copies its result there (a post item's take, lane/post-narration). + if (typeof body.out === "string" && path.isAbsolute(body.out)) { + mkdirSync(path.dirname(body.out), { recursive: true }); + copyFileSync(wav, body.out); + } ttsJobs.set(id, { polls: 0, result: { - wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0, + wav: typeof body.out === "string" && path.isAbsolute(body.out) ? body.out : wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0, sha: id, sampleRate: 48000, speed: body.speed ?? 1, // The editor's own line, which umtool uses verbatim. disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice ?? "af_heart"})`, @@ -1375,7 +1380,8 @@ const server = http.createServer((req, res) => { req.resume(); const j = ttsJobs.get(opsJob[1]); const tail = url.searchParams.get("tail"); - if (!tail) j.polls += 1; + // A poll that asks for the tail counts too (umtool's job follower always asks for it: case-editor.ts jobState). + j.polls += 1; // One poll of latency: the follow path, not only the finished one. const status = j.polls <= 1 ? "running" : "done"; return json(res, 200, { diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -54,6 +54,7 @@ import { makeCutEditingFixture } from "./cut-editing-fixture.mjs"; import { makeReelFixture } from "./reel-fixture.mjs"; import { makeIntakeFixture } from "./intake-fixture.mjs"; import { makePostItemsFixture } from "./post-items-fixture.mjs"; +import { makePostNarrationFixture } from "./post-narration-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1910,6 +1911,8 @@ makeReelFixture({ reports, deckManifest }); makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Post items (report-to-video/post-item.mjs): a cut mixing a clip and posts played as items, a synthesized posts archive (post-items.spec.ts). makePostItemsFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Narrated post items (report-to-video/post-narration.mjs): a take read over a video, four pictures cycling (post-narration.spec.ts). +makePostNarrationFixture({ reports, deckManifest }); // Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut, // undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1 // window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it). diff --git a/umtool/e2e/fixtures/post-narration-fixture.mjs b/umtool/e2e/fixtures/post-narration-fixture.mjs @@ -0,0 +1,66 @@ +// NARRATED POST ITEMS (report-to-video/post-narration.mjs): a posts cut whose +// first item reads a take over its video (post-narration.spec.ts). +// +// post-narration-fixture p-vid a 4 s video with a 440 Hz tone, narrated +// by a 2 s take (a 262 Hz tone): the muffle +// from 0 to lead + 2 + tail = 2.7 s, the ramp +// to 3.5 s, clean after; a long script of two +// paragraphs (two parts to record) +// p-pics four pictures, un-narrated: one card, the +// pictures cycling beside it +// p-txt words only, a script and no take +// the deck on. WRITES its manifest: the spec puts +// it back before each test. +// +// Synthetic, like every fixture. +import { mkdirSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +const ff = (args) => { + const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]); + if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`); +}; + +/** @param {{ reports: string, deckManifest: Function }} o */ +export function makePostNarrationFixture({ reports, deckManifest }) { + const name = "post-narration-fixture"; + const dir = path.join(reports, name); + const media = path.join(dir, "posts-media", "narrchan-x"); + for (const id of ["11", "12"]) mkdirSync(path.join(media, id), { recursive: true }); + ff([ + "-f", "lavfi", "-i", "testsrc=size=320x180:rate=30:duration=4", + "-f", "lavfi", "-i", "sine=frequency=440:duration=4", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", "-shortest", path.join(media, "11", "11_1.mp4"), + ]); + for (const [k, c] of ["red", "green", "blue", "yellow"].entries()) { + ff(["-f", "lavfi", "-i", `color=c=${c}:size=320x180`, "-frames:v", "1", path.join(media, "12", `12_${k + 1}.png`)]); + } + const takes = path.join(dir, "narration", "posts", "11"); + mkdirSync(takes, { recursive: true }); + ff(["-f", "lavfi", "-i", "sine=frequency=262:sample_rate=48000:duration=2", "-ac", "1", "-c:a", "pcm_s16le", path.join(takes, "take-1.orpheus-zac.wav")]); + const base = (id, text, o = {}) => ({ + type: "post", id, post: `narrchan-x/${id.slice(2)}`, platform: "x", author: "Narr Subject", handle: "narrsubject", + date: "2026-10-30T10:00:00.000Z", text, url: `https://x.com/narrsubject/status/${id}`, engagement: { likes: 4 }, subjects: ["narrsubject"], ...o, + }); + const timeline = [ + base("p-11", "The video speaks for itself.", { + post: "narrchan-x/11", + media: [{ src: "posts-media/narrchan-x/11/11_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true }], + narration: { + script: "The video speaks for itself.\n\nAnd a second paragraph, read as its own part.", + takes: [{ file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 2, script: "The video speaks for itself.", at: "2026-11-02T00:00:00.000Z" }], + pick: 0, + }, + }), + base("p-12", "Four pictures of the thing, one after another, while this is read.", { + post: "narrchan-x/12", + media: [1, 2, 3, 4].map((k) => ({ src: `posts-media/narrchan-x/12/12_${k}.png`, kind: "image", width: 320, height: 180 })), + }), + base("p-13", "Words only, waiting for a voice.", { post: "narrchan-x/13", narration: { script: "Words only, waiting for a voice." } }), + ]; + const m = deckManifest(name, "The Post Narration Fixture", timeline); + m.provenance = { ...m.provenance, channelSlug: "narrchan-x" }; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { dir }; +} diff --git a/umtool/e2e/post-items.spec.ts b/umtool/e2e/post-items.spec.ts @@ -12,10 +12,12 @@ import * as urls from "./urls"; // self-reply under its parent), p-img (a picture), p-vid (a 4 s video with a // tone, a reply to a private account) from the synthesized archive postchan-x. // -// The rule's seconds (reading 1 s + words / 3, at least 3; a parent 1-4 s; -// then the attachments): p-txt 12 words + a 7-word parent = 5 + 2.33 = 7.33; -// p-img 5 words = 3 + a picture 3.5 = 6.5; p-vid 7 words + a 4-word parent = -// 3.33 + 1.33 = 4.67 to read, then the video's 4 s = 8.67. +// The rule's seconds (the pacing rule, 2 Nov: the item is its reading time -- +// 1 s + words / 3, at least 3; a parent 1-4 s -- the attachments playing +// beside the words, not after them): p-txt 12 words + a 7-word parent = 5 + +// 2.33 = 7.33; p-img 5 words = 3 (its picture up the whole time); p-vid 7 +// words + a 4-word parent = 3.33 + 1.33 = 4.67, its 4 s video from the first +// frame, the last frame held. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -59,8 +61,8 @@ test("the Cut tab lists the mixed cut: the clip, then post rows with their glyph await expect(page.locator('[data-entry="p-img"] [data-post-carries]')).toHaveText("image"); await expect(page.locator('[data-entry="p-vid"] [data-post-carries]')).toHaveText("video"); await expect(page.locator('[data-entry="p-txt"] [data-post-seconds]')).toHaveText("7.3s"); - await expect(page.locator('[data-entry="p-img"] [data-post-seconds]')).toHaveText("6.5s"); - await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("8.7s"); + await expect(page.locator('[data-entry="p-img"] [data-post-seconds]')).toHaveText("3.0s"); + await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("4.7s"); await expect(page.locator('[data-entry="p-vid"]')).toContainText("Yes, and here is the video."); // A post item takes a section's place like a clip: the bar after c01 opens on p-txt. await expect(page.locator('[data-entry="p-vid"] [data-post-bench-link]')).toHaveAttribute("href", urls.postBenchHref(PROJECT, "p-vid")); @@ -75,7 +77,8 @@ test("Play plays a post item: its card, the private parent blurred, its video pl const player = page.locator('[data-post-play="p-vid"]'); await expect(player).toBeVisible(); await expect(player).toHaveAttribute("data-post-layout", "side"); - await expect(player).toHaveAttribute("data-post-step", "read"); + // One layout: the video beside the card from the item's first frame (not after a reading beat). + await expect(player).toHaveAttribute("data-post-step", "video"); // The card is the build's page: the post's words, its counts, the parent above it blurred. const card = page.frameLocator('[data-post-card-frame="read"]'); await expect(card.locator('[data-post-card="p-vid"]')).toBeVisible(); @@ -83,16 +86,15 @@ test("Play plays a post item: its card, the private parent blurred, its video pl await expect(card.locator('[data-post-parent="0"][data-redacted]')).toHaveCount(1); await expect(card.locator("body")).not.toContainText("someone_private"); await expect(card.locator("body")).not.toContainText("Private Person"); - // Its first frame is up beside the card while the words are read. + // Paused: its first frame is up beside the card. await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "0"); const t0 = Number(await root(page).getAttribute("data-play-t")); await page.locator("[data-play-toggle]").click(); - await expect(player).toHaveAttribute("data-post-step", "video", { timeout: 15_000 }); - await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "1"); + await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "1", { timeout: 15_000 }); await expect.poll(async () => page.locator('[data-post-video="0"]').evaluate((v: HTMLVideoElement) => v.currentTime), { timeout: 10_000 }).toBeGreaterThan(0.5); expect(await page.locator('[data-post-video="0"]').evaluate((v: HTMLVideoElement) => v.muted)).toBe(false); const t1 = Number(await root(page).getAttribute("data-play-t")); - expect(t1).toBeGreaterThan(t0 + 4); + expect(t1).toBeGreaterThan(t0); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-play.png") }); await page.locator("[data-play-toggle]").click(); // Edit this post opens its bench, and Back to the cut returns to it. @@ -106,10 +108,11 @@ test("the post bench trims the video attachment and saves it; the cut's seconds await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.postBenchHref(PROJECT, "p-vid")); await expect(page.locator('[data-post-bench="p-vid"]')).toBeVisible(); - await expect(page.locator("[data-post-bench-rule]")).toHaveText("8.7 s"); + await expect(page.locator("[data-post-bench-rule]")).toHaveText("4.7 s"); await page.locator('[data-post-bench-start="0"]').fill("1"); await page.locator('[data-post-bench-end="0"]').fill("3"); - await expect(page.locator("[data-post-bench-rule]")).toHaveText("6.7 s"); + // The item is its read: a shorter clip holds its last frame, the length stays. + await expect(page.locator("[data-post-bench-rule]")).toHaveText("4.7 s"); await expect(page.locator('[data-post-bench-step="video"]')).toContainText("video 2.0 s"); await page.locator('[data-post-bench-sound="0"]').uncheck(); await page.locator("[data-post-bench-save]").click(); @@ -123,7 +126,7 @@ test("the post bench trims the video attachment and saves it; the cut's seconds expect(timeline().find((e) => e.id === "p-vid")!.media?.[0]?.end).toBe(3); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-bench.png") }); await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); - await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("6.7s"); + await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("4.7s"); }); test("umtool posts reel adds only what the cut does not play yet, in one write", async () => { diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -0,0 +1,247 @@ +import { test, expect, type Page } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// NARRATED POST ITEMS (report-to-video/post-narration.mjs; knobs.md, "A narrated +// post item"). Fixture: e2e/fixtures/post-narration-fixture.mjs -- p-11 a 4 s +// video narrated by a 2 s take (muffled 0-2.7 s, the ramp to 3.5 s, clean after; +// the item 0.4 + 2 + 0.3 + 1.8 = 4.5 s), p-12 four pictures un-narrated, p-13 +// words and a script, no take. The editor is the suite's stub (its tts op +// writes a tone where `out` says). +// +// POST_NARRATION_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const DIR = path.join(FIXTURE, "reports", "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.POST_NARRATION_SHOTS ?? null; +/** A voice for the fake microphone: a 1 kHz tone, two seconds. */ +const MIC_WAV = path.join(FIXTURE, "post-narration-mic.wav"); + +type Take = { file: string; engine?: string; voice?: string; note?: string; seconds: number }; +type Entry = { id: string; narration?: { script?: string; takes?: Take[]; pick?: number; approved?: boolean } }; +const timeline = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline; +const narr = (id: string) => timeline().find((e) => e.id === id)!.narration!; + +if (!existsSync(MIC_WAV)) { + mkdirSync(FIXTURE, { recursive: true }); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]); +} + +// A fake microphone (the recording session) and audio that may start without a gesture, for the whole file. +test.use({ launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${MIC_WAV}`, "--autoplay-policy=no-user-gesture-required"] } }); + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); + for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true }); + rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true }); + rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true }); + rmSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"), { recursive: true, force: true }); +}); + +const root = (page: Page) => page.locator("[data-play-cut]"); + +test("Play plays the take over the attachment, muffled under the read, then opens up clean", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); + await expect(root(page)).toHaveAttribute("data-play-item", "p-11"); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-narrated", "1"); + // The video beside the card from the item's first frame; the muffle on. + await expect(player).toHaveAttribute("data-post-step", "video"); + await expect(player).toHaveAttribute("data-post-mix-phase", "muffled"); + await expect(player).toHaveAttribute("data-post-wet", "0.3"); + await expect(player).toHaveAttribute("data-post-dry", "0"); + await expect(page.locator("[data-post-narration-audio]")).toHaveAttribute("data-post-narration-audio", "narration/posts/11/take-1.orpheus-zac.wav"); + await page.locator("[data-play-toggle]").click(); + await expect(player).toHaveAttribute("data-post-narration-playing", "1", { timeout: 15_000 }); + await expect.poll(async () => page.locator("[data-post-narration-audio]").evaluate((a: HTMLAudioElement) => a.currentTime), { timeout: 10_000 }).toBeGreaterThan(0.3); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-play-muffled.png") }); + // Past the words and the tail: the ramp, then clean. + await expect(player).toHaveAttribute("data-post-mix-phase", /ramp|clean/, { timeout: 15_000 }); + await expect(player).toHaveAttribute("data-post-narration-playing", "0"); + await page.locator("[data-play-toggle]").click(); +}); + +test("four pictures cycle beside the card while it is read; the words stay up the whole item", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.postBenchHref(PROJECT, "p-12")); + await expect(page.locator('[data-post-bench="p-12"]')).toBeVisible(); + const player = page.locator('[data-post-play="p-12"]'); + await expect(player).toHaveAttribute("data-post-layout", "side"); + const scrub = page.locator("[data-post-bench-scrub]"); + const seen: string[] = []; + for (const [k, at] of [0.2, 2, 4.5].entries()) { + await scrub.fill(String(at)); + await expect(player).toHaveAttribute("data-post-step", "image"); + await expect(page.frameLocator('[data-post-card-frame="read"]').locator("[data-post-words]")).toContainText("Four pictures of the thing"); + seen.push(String(await page.locator("[data-post-image]").first().getAttribute("src"))); + await expect.poll(() => page.locator("[data-post-image]").first().evaluate((i: HTMLImageElement) => i.complete && i.naturalWidth > 0)).toBe(true); + if (SHOTS) await page.waitForTimeout(400); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `post-narration-pictures-${k + 1}.png`) }); + } + expect(new Set(seen).size).toBe(3); +}); + +test("the post bench: the lanes, a re-take with direction (the editor's tts job), Pick and Approve", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1400 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const panel = page.locator('[data-post-narration="p-11"]'); + await expect(panel).toBeVisible(); + await expect(panel.locator('[data-post-lane="attachment"]')).toBeVisible(); + await expect(panel.locator('[data-post-lane="read"]')).toBeVisible(); + await expect(panel.locator("[data-post-lane-muffle]")).toBeVisible(); + await expect(panel.locator("[data-post-take]")).toHaveCount(1); + await expect(panel.locator('[data-post-take="1"]')).toHaveAttribute("data-post-take-picked", "1"); + // A take plays: its file is served as audio. + const res = await page.request.get(`/api/report/file?project=${encodeURIComponent(PROJECT)}&path=${encodeURIComponent("narration/posts/11/take-1.orpheus-zac.wav")}`); + expect(res.status()).toBe(200); + expect(res.headers()["content-type"]).toBe("audio/wav"); + await expect(panel.locator("[data-post-progress-recorded]")).toHaveText("0"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench.png"), fullPage: true }); + // Re-take with direction: queued on the editor, kept when done, picked, its note with it. + await panel.locator("[data-post-retake-note]").fill("slower, a sigh first"); + await panel.locator("[data-post-script]").fill("<sigh> The video speaks for itself."); + await panel.locator("[data-post-retake]").click(); + await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 20_000 }); + const n = narr("p-11"); + expect(n.takes![1]).toMatchObject({ file: "narration/posts/11/take-2.orpheus-zac.wav", engine: "orpheus", voice: "zac", note: "slower, a sigh first" }); + expect(n.pick).toBe(1); + expect(n.script).toBe("<sigh> The video speaks for itself."); + await expect(page.locator('[data-post-narration="p-11"] [data-post-take="2"]')).toHaveAttribute("data-post-take-picked", "1"); + // Pick the first back; approve it. + await page.locator('[data-post-take-pick="1"]').click(); + await expect(page.locator('[data-post-take="1"]')).toHaveAttribute("data-post-take-picked", "1"); + expect(narr("p-11").pick).toBe(0); + await page.locator("[data-post-approve]").click(); + await expect(page.locator("[data-post-approve]")).toBeChecked(); + await expect.poll(() => narr("p-11").approved).toBe(true); + // An operator's note on the post: shown on its bench, counted in the walk. + await page.locator("[data-post-note-text]").fill("read it angrier"); + await page.locator("[data-post-note-add]").click(); + await expect(page.locator("[data-post-note]")).toContainText("read it angrier"); + await page.goto(urls.postBenchHref(PROJECT, "p-12")); + await expect(page.locator("[data-post-with-notes]")).toHaveAttribute("data-post-with-notes", "1"); + await expect(page.locator("[data-post-next-with-note]")).toHaveAttribute("data-post-next-with-note", "p-11"); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + // The mix: a knob is one write. + await page.locator('[data-post-mix="wet"]').fill("0.2"); + await page.locator('[data-post-mix="wet"]').blur(); + await expect.poll(() => (timeline().find((e) => e.id === "p-11")!.narration as Record<string, unknown>).wet).toBe(0.2); + // Run AI on a take: the stub editor has no voice ops -- "not installed", said plainly, nothing written. + await page.locator("[data-post-derive-op]").selectOption("enhance"); + await page.locator("[data-post-derive-run]").click(); + await expect(page.locator("[data-post-derive-not-installed]")).toContainText("not installed"); + expect(narr("p-11").takes).toHaveLength(2); + // Delete, softly: the take out of the list, its file in .trash/. + page.once("dialog", (d) => void d.accept()); + await page.locator('[data-post-take-delete="2"]').click(); + await expect(page.locator("[data-post-take]")).toHaveCount(1); + expect(existsSync(path.join(DIR, "narration", "posts", "11", "take-2.orpheus-zac.wav"))).toBe(false); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-bench-takes.png"), fullPage: true }); +}); + +test.describe("the recording session", () => { + test("record a long script part by part, play it back, Keep: a recorded take, picked, and it plays", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1400 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const rec = page.locator("[data-post-record]"); + await expect(rec.locator("[data-post-part]")).toHaveCount(2); + await expect(rec.locator('[data-post-part="1"]')).toHaveAttribute("data-post-part-current", "1"); + await rec.locator("[data-post-record-start]").click(); + await expect(rec).toHaveAttribute("data-post-record-phase", "recording", { timeout: 10_000 }); + await expect(rec.locator("[data-post-recording]")).toBeVisible(); + await page.waitForTimeout(1200); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-narration-recording.png"), fullPage: true }); + await rec.locator("[data-post-record-stop]").click(); + // Auto-advanced to the second part; the first is recorded and plays back. + await expect(rec.locator('[data-post-part="2"]')).toHaveAttribute("data-post-part-current", "1"); + await expect(rec.locator('[data-post-part="1"]')).toHaveAttribute("data-post-part-recorded", "1"); + await rec.locator("[data-post-record-start]").click(); + await expect(rec).toHaveAttribute("data-post-record-phase", "recording", { timeout: 10_000 }); + await page.waitForTimeout(1000); + await rec.locator("[data-post-record-stop]").click(); + await expect(rec.locator('[data-post-part="2"]')).toHaveAttribute("data-post-part-recorded", "1"); + await rec.locator("[data-post-record-keep]").click(); + const panel = page.locator('[data-post-narration="p-11"]'); + await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 }); + await expect(panel.locator('[data-post-take="2"]')).toHaveAttribute("data-post-take-engine", "recorded"); + await expect(panel.locator('[data-post-take="2"]')).toHaveAttribute("data-post-take-picked", "1"); + await expect(panel).toHaveAttribute("data-post-narration-plays", "recorded"); + const n = narr("p-11"); + expect(n.takes![1]).toMatchObject({ file: "narration/posts/11/take-2.recorded-operator.wav", engine: "recorded", voice: "operator" }); + expect((n.takes![1] as unknown as { parts: unknown[] }).parts).toHaveLength(2); + // The bench's player plays it, as the render will. + await expect(page.locator("[data-post-narration-audio]")).toHaveAttribute("data-post-narration-audio", "narration/posts/11/take-2.recorded-operator.wav"); + await expect(panel.locator("[data-post-progress-recorded]")).toHaveText("1"); + }); +}); + +test("THE RECORDING SESSION: part by part, a reload resumes, redo one, the last part makes the recorded take and picks it", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1200 }); + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await expect(page.locator("[data-record-narration-link]")).toHaveAttribute("href", urls.narrationRecordHref(PROJECT)); + await page.goto(urls.narrationRecordHref(PROJECT, { post: "p-11" })); + const s = page.locator("[data-record-session]"); + await expect(s).toHaveAttribute("data-record-session", "p-11"); + await expect(page.locator("[data-record-jump]")).toHaveCount(3); + await expect(page.locator('[data-record-jump="p-11"]')).toHaveAttribute("data-record-state", "placeholder"); + await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "0"); + // Two paragraphs: two parts, the first current. + await expect(page.locator("[data-record-prompt]")).toHaveCount(2); + await expect(page.locator('[data-record-prompt="1"]')).toHaveAttribute("data-record-prompt-current", "1"); + await page.locator("[data-record-count-in]").uncheck(); + // Space records, Space stops: part 1 is on disk, part 2 is next. + await page.keyboard.press("Space"); + await expect(s).toHaveAttribute("data-record-phase", "recording", { timeout: 10_000 }); + await page.waitForTimeout(900); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "record-session-recording.png"), fullPage: true }); + await page.keyboard.press("Space"); + await expect(page.locator('[data-record-prompt="1"]')).toHaveAttribute("data-record-prompt-kept", "1"); + await expect(page.locator('[data-record-prompt="2"]')).toHaveAttribute("data-record-prompt-current", "1"); + expect(existsSync(path.join(DIR, "narration", "posts", "11", ".recording-operator", "session.json"))).toBe(true); + // A reload resumes: part 1 kept, part 2 current. + await page.reload(); + await expect(page.locator('[data-record-prompt="1"]')).toHaveAttribute("data-record-prompt-kept", "1"); + await expect(page.locator('[data-record-prompt="2"]')).toHaveAttribute("data-record-prompt-current", "1"); + await expect(page.locator('[data-record-play-placeholder="2"]')).toBeVisible(); + // Redo part 1 (r): recorded again, still kept; the next unkept part is current. + await page.locator('[data-record-prompt="1"]').click(); + await page.locator("[data-record-count-in]").uncheck(); + await page.keyboard.press("r"); + await expect(s).toHaveAttribute("data-record-phase", "recording", { timeout: 10_000 }); + await page.waitForTimeout(700); + await page.keyboard.press("Space"); + await expect(page.locator('[data-record-prompt="2"]')).toHaveAttribute("data-record-prompt-current", "1"); + await expect(page.locator('[data-record-play-part="1"]')).toHaveCount(0); + // The last part: the take is made, picked, and the post is recorded. + await page.keyboard.press("Space"); + await expect(s).toHaveAttribute("data-record-phase", "recording", { timeout: 10_000 }); + await page.waitForTimeout(700); + await page.keyboard.press("Space"); + await expect(page.locator("[data-record-status]")).toContainText("take-2.recorded-operator.wav", { timeout: 30_000 }); + await expect(page.locator('[data-record-jump="p-11"]')).toHaveAttribute("data-record-state", "recorded"); + await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "1"); + const n = narr("p-11"); + expect(n.pick).toBe(1); + expect(n.takes![1]).toMatchObject({ file: "narration/posts/11/take-2.recorded-operator.wav", engine: "recorded", voice: "operator" }); + expect((n.takes![1] as unknown as { parts: unknown[] }).parts).toHaveLength(2); + expect(existsSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"))).toBe(false); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "record-session-done.png"), fullPage: true }); + // Enter: on to the next post. + await page.keyboard.press("Enter"); + await expect(s).toHaveAttribute("data-record-session", "p-12"); +}); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -407,6 +407,11 @@ export function narrationHref(project: string, q: NoteOpt = {}): string { return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note); } +/** The recording session: a person reads the cut's post items aloud, part by part (lane/post-narration). */ +export function narrationRecordHref(project: string, q: { post?: string | null } = {}): string { + return withQuery(`/projects/${encodePath(project)}/narration/record`, q.post ? { post: q.post } : {}); +} + /** The drafts review (release 28). */ export function reviewHref(project: string, q: NoteOpt & { view?: "list" } = {}): string { return withQuery(`/projects/${encodePath(project)}/review`, q.view ? { view: q.view } : {}, q.note); 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,193 @@ 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 }; + }); +} + /** What a context write may set on a post item (postContext.mjs). */ export const POST_ITEM_CONTEXT_KEYS = Object.freeze(["quoted", "parents"]); @@ -2437,6 +2629,36 @@ export async function setPostItemsContext(dir, patches, { token = null } = {}) { }); } +/** 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,320 @@ +// 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); +}); + +test("a RECORDING kept part by part: each trimmed of its silence, joined with the pauses, levelled, picked", async () => { + const { keepRecording, trimSpan } = await import("./postRecord.mjs"); + assert.deepEqual(trimSpan([{ s: 0, e: 0.5 }, { s: 1.5, e: 2 }], 2), { from: 0.42, to: 1.65 }); + assert.deepEqual(trimSpan([], 2), { from: 0, to: 2 }); + const p = await project("rec", [item("1", { narration: { script: "one.\n\ntwo.", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 2, lufs: -21.3 }] } })]); + const parts = []; + for (const k of [1, 2]) { + const f = path.join(ROOT, `rec-${k}.wav`); + ff(["-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono:d=0.6", "-f", "lavfi", "-i", "sine=f=300:d=1:r=44100", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono:d=0.6", "-filter_complex", "[1:a]volume=0.1[s];[0:a][s][2:a]concat=n=3:v=0:a=1", f]); + parts.push({ file: f, text: k === 1 ? "one." : "two.", para: k - 1 }); + } + const r = await keepRecording(p, (await manifest(p)).timeline[0], parts, { manifest: await manifest(p) }); + assert.equal(r.take.file, "narration/posts/1/take-2.recorded-operator.wav"); + assert.equal(r.take.engine, "recorded"); + assert.equal(r.target, -21.3); + assert.equal(r.take.parts.length, 2); + assert.equal(r.take.parts[1].gapBefore, 0.6); + // Two 1 s words with a breath of room each, and the paragraph's pause. + assert.ok(r.take.seconds > 2.6 && r.take.seconds < 3.1, String(r.take.seconds)); + assert.ok(Math.abs(r.take.lufs - -21.3) < 1.5, String(r.take.lufs)); + const n = (await manifest(p)).timeline[0].narration; + assert.equal(n.pick, 1); + assert.equal(n.takes[1].voice, "operator"); + assert.equal(postItemPlan((await manifest(p)).timeline[0]).narration.seconds, r.take.seconds); +}); + +test("a DERIVED take: run through the editor's op into a new take, the original kept; not installed says so; delete is soft", async () => { + const { deriveTake, deleteTake } = await import("./postNarrationCli.mjs"); + const p = await project("der", [item("1")]); + await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); + wav(path.join(p.dir, "narration", "posts", "1", "take-1.recorded-operator.wav"), 1.5); + await updatePostNarration(p.dir, "p-1", { script: "x", addTake: { file: "narration/posts/1/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", seconds: 1.5, source: { kind: "recorded", voice: "operator" } } }); + const asked = []; + const ask = async (route, body) => { + asked.push({ route, body }); + wav(body.out, 1.4); + return { jobId: "job-d", result: null }; + }; + const r = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "convert", engine: "rvc", voice: "stock-a", ask }); + assert.equal(asked[0].route, "/api/ops/voice-convert"); + assert.ok(asked[0].body.file.endsWith("take-1.recorded-operator.wav")); + assert.equal(r.take.file, "narration/posts/1/take-2.convert-rvc.wav"); + assert.deepEqual(r.take.source, { kind: "take", from: "take-1.recorded-operator" }); + assert.equal(r.take.steps[0].op, "convert"); + const n = (await manifest(p)).timeline[0].narration; + assert.equal(n.takes.length, 2); + assert.equal(n.pick, 1); + const { postNarrationDisclosure, rootTakeOf } = await import("umtool-report-to-video/post-narration"); + assert.equal(rootTakeOf(n.takes, n.takes[1]), n.takes[0]); + assert.equal(postNarrationDisclosure((await manifest(p)).timeline[0]), "Narration: voice converted to a synthetic voice (rvc · stock-a)"); + // An op the editor has no engine for. + const { OpNotInstalled } = await import("umtool-report-to-video/narrate-via-editor"); + await assert.rejects( + deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "enhance", ask: async (route) => { throw new OpNotInstalled(route, "no such op"); } }), + /no engine for \/api\/ops\/voice-enhance yet \(not installed/, + ); + // Delete, softly: moved to .trash, out of the list, the pick following. + await deleteTake(p, (await manifest(p)).timeline[0], 1); + const after = (await manifest(p)).timeline[0].narration; + assert.equal(after.takes.length, 1); + assert.equal(after.pick, 0); + const trash = await readdir(path.join(p.dir, "narration", "posts", "1", ".trash")); + assert.ok(trash.some((f) => f.endsWith("take-2.convert-rvc.wav"))); +}); + +test("the recording session's store: each part on disk as it is kept, a re-split starts over, finish makes the take and clears it", async () => { + const { savePart, discardPart, readSession, finishSession, sessionDirOf } = await import("./recordSession.mjs"); + const p = await project("sess", [item("1", { narration: { script: "one.\n\ntwo." } })]); + const e = () => manifest(p).then((m) => m.timeline[0]); + const bytes = async (k) => { + const f = path.join(ROOT, `sess-${k}.wav`); + ff(["-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono:d=0.3", "-f", "lavfi", "-i", "sine=f=300:d=0.8:r=48000", "-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1", f]); + return new Uint8Array(await readFile(f)); + }; + await assert.rejects(finishSession(p, await e()), /nothing recorded yet/); + let s = await savePart(p.dir, await e(), { n: 1, count: 2, text: "one.", para: 0, bytes: await bytes(1), type: "audio/wav" }); + assert.deepEqual(Object.keys(s.parts), ["1"]); + assert.equal((await readSession(p.dir, await e())).parts["1"].file, "p01.wav"); + await assert.rejects(finishSession(p, await e()), /parts 2 of 2 are not recorded yet/); + // Redo: dropped, then kept again. + s = await discardPart(p.dir, await e(), 1); + assert.deepEqual(s.parts, {}); + await savePart(p.dir, await e(), { n: 1, count: 2, text: "one.", para: 0, bytes: await bytes(1), type: "audio/wav" }); + await savePart(p.dir, await e(), { n: 2, count: 2, text: "two.", para: 1, bytes: await bytes(2), type: "audio/wav" }); + const kept = await finishSession(p, await e(), { manifest: await manifest(p) }); + assert.equal(kept.take.file, "narration/posts/1/take-1.recorded-operator.wav"); + assert.equal(kept.take.parts.length, 2); + assert.equal((await manifest(p)).timeline[0].narration.pick, 0); + await assert.rejects(readdir(sessionDirOf(p.dir, await e(), "operator"))); + // A different split (the script was edited): the parts kept before no longer line up. + await savePart(p.dir, await e(), { n: 1, count: 2, text: "a", para: 0, bytes: await bytes(1), type: "audio/wav" }); + s = await savePart(p.dir, await e(), { n: 1, count: 3, text: "a", para: 0, bytes: await bytes(1), type: "audio/wav" }); + assert.equal(s.count, 3); + assert.deepEqual(Object.keys(s.parts), ["1"]); + await assert.rejects(savePart(p.dir, await e(), { n: 4, count: 3, text: "", para: 0, bytes: await bytes(1) }), /n of count/); +}); diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -0,0 +1,536 @@ +// `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, rename, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { + NARRATION_INDEX, POST_DERIVE_OPS, POST_DERIVE_ROUTES, derivedFileOf, draftScript, takeIdOf, 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> ….", + " --delete <n>: the take out of the list, its file moved to narration/posts/<postId>/.trash/ (soft).", + " --derive <n> --op enhance|convert [--engine e] [--voice v]: a NEW take made from take n by the editor's op", + " (enhance: denoise, level; convert: the performance kept, the timbre a STOCK synthetic voice) -- the original kept.", + " 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 = []; + const absent = []; + 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); + // A take still being made (not on disk yet) comes in with a later run. + if (!m) { + absent.push(t.file); + continue; + } + add.push({ + file: t.file, + engine: t.engine ?? "orpheus", + voice: t.voice ?? "zac", + source: { kind: "tts", engine: t.engine ?? "orpheus", voice: t.voice ?? "zac", script: typeof t.script === "string" ? t.script : String(row.script ?? "") }, + 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, absent }; +} + +const fmtKnob = (k, v) => `${k}=${typeof v === "boolean" ? (v ? "on" : "off") : v}`; + +/** + * @returns {Array<{ n: number, para?: number, text?: string, file?: string, start: number, seconds: number, gapBefore?: number }> | null} + * 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), + source: { kind: "tts", engine: result?.engine ?? eng, voice: result?.voice ?? vox, script: words }, + 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()) return null; + 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, absent } = await importPatches(manifest, rows, measure); + const notYet = absent.length ? `; ${absent.length} take(s) not on disk yet (a later --import brings them): ${absent.slice(0, 5).join(", ")}${absent.length > 5 ? ", …" : ""}` : ""; + 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, absent, 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(", ")}` : ""}${notYet}`); + 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, absent, 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(", ")}` : ""}${notYet}`); + 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 (str("--delete") !== null) { + const k = Number(str("--delete")); + if (!Number.isInteger(k) || k < 1) throw new NarrateError("--delete takes a take's number as --list shows it (1 = the first)"); + const r = await deleteTake(project, e, k - 1); + out(json ? JSON.stringify({ ok: true, id: e.id, narration: r.narration, token: r.token }, null, 2) : `${e.id}: take ${k} moved to the post's .trash/ (out of the list)\n${narrationLines(r.entry, render).join("\n")}`); + return 0; + } + if (str("--derive") !== null) { + const k = Number(str("--derive")); + if (!Number.isInteger(k) || k < 1) throw new NarrateError("--derive takes a take's number as --list shows it (1 = the first)"); + const op = str("--op") ?? ""; + try { + const r = await deriveTake(project, e, { from: k - 1, op, engine: str("--engine"), voice: str("--voice"), emit: (_ev, f) => !json && f?.message && out(f.message) }); + if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take, token: r.result.token }, null, 2)); + else out(`${e.id}: take ${r.take.file} (${r.take.seconds} s), from take ${k} by ${op}, picked`); + return 0; + } catch (err) { + if (err?.name === "OpNotInstalled") throw new NarrateError(err.message); + throw err; + } + } + 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; +} + +/** + * A DERIVED TAKE (post-narration.mjs: "run AI on recorded voice"): take + * `from` (an index) run through the editor's `op` (`enhance`, `convert`) into + * a NEW take -- source `{kind: "take", from: <its id>}`, its step recorded -- + * the original untouched; a parted take part by part (its parts kept). The + * editor's op is a job (`POST /api/ops/voice-enhance|voice-convert` with + * `{file, out, engine?, voice?, params?, parts?}`); one it has no engine for + * throws OpNotInstalled. + */ +export async function deriveTake(project, e, { from, op, engine = null, voice = null, params = null, emit = () => {}, editor = null, ask = null } = {}) { + const takes = e.narration?.takes ?? []; + const t = takes[from]; + if (!t) throw new NarrateError(`${e.id} has no take ${from + 1}`); + if (!POST_DERIVE_OPS.includes(op)) throw new NarrateError(`--op is one of ${POST_DERIVE_OPS.join(", ")}`); + const pid = postIdOf(e); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const n = nextTakeNumber(e, await readdir(dir).catch(() => [])); + const rel = derivedFileOf(pid, n, op, engine ?? voice ?? "default"); + const abs = (r) => path.join(project.dir, ...r.split("/")); + const partsRel = rel.replace(/\.wav$/, ".parts"); + const parts = Array.isArray(t.parts) && t.parts.every((p) => typeof p.file === "string") + ? t.parts.map((p) => ({ ...p, file: `${partsRel}/p${String(p.n).padStart(2, "0")}.wav` })) + : null; + const body = { + file: abs(t.file), out: abs(rel), + ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...(params ? { params } : {}), + ...(parts ? { parts: t.parts.map((p, k) => ({ file: abs(p.file), out: abs(parts[k].file) })) } : {}), + }; + const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp; + const { jobId } = await askOp(POST_DERIVE_ROUTES[op], body, { ...(editor ? { editor } : {}), emit }); + if (!(await stat(abs(rel)).catch(() => null))?.isFile()) throw new NarrateError(`the editor's job ${jobId} finished but ${rel} is not there`); + const m = await measureTake(abs(rel)); + const take = { + file: rel, engine: "derived", voice: voice ?? t.voice ?? "?", seconds: m.seconds ?? t.seconds, + source: { kind: "take", from: takeIdOf(t) }, + steps: [{ op, ...(engine ? { engine } : {}), ...(voice ? { voice } : {}), ...(params ? { params } : {}), ranAt: new Date().toISOString(), job: jobId }], + script: t.script ?? e.narration?.script ?? "", at: new Date().toISOString(), jobId, + ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(parts ? { parts } : {}), + }; + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + return { take, result }; +} + +/** + * DELETE A TAKE, SOFTLY: its file (and its parts) moved into the post's + * `narration/posts/<postId>/.trash/`, the take out of the list (the pick + * follows). Returns the write's result. + */ +export async function deleteTake(project, e, index) { + const t = (e.narration?.takes ?? [])[index]; + if (!t) throw new NarrateError(`${e.id} has no take ${index + 1}`); + const trash = path.join(project.dir, ...takesDirOf(postIdOf(e)).split("/"), ".trash"); + await mkdir(trash, { recursive: true }); + const stamp = new Date().toISOString().replace(/[:.]/g, "-"); + for (const rel of [t.file, String(t.file).replace(/\.wav$/, ".parts")]) { + const from = path.join(project.dir, ...String(rel).split("/")); + if (await stat(from).catch(() => null)) await rename(from, path.join(trash, `${stamp}-${path.basename(from)}`)); + } + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { dropTake: index }, { token: await manifestToken(project.dir) })); + return result; +} diff --git a/umtool/lib/report/postRecord.mjs b/umtool/lib/report/postRecord.mjs @@ -0,0 +1,139 @@ +// A RECORDED TAKE (operator, 2 Nov: "I think I'll record my voice"): a +// person's own reading of a post item's script, recorded on the post bench +// (the browser's MediaRecorder) PART BY PART for a long post, kept as a take +// like a synthesized one -- the render and Play treat it the same. +// +// narration/posts/<postId>/take-<n>.recorded-<label>.wav the joined read +// narration/posts/<postId>/take-<n>.recorded-<label>.parts/pNN.wav each part, trimmed +// +// Each part is decoded by ffmpeg to 48 kHz mono, its leading and trailing +// silence trimmed (detectSilence, cut-points.mjs) leaving a breath of room; +// the parts are joined with post-narration.mjs's pauses (0.6 s between +// paragraphs, 0.25 s inside one); the whole is brought to the level of the +// project's synthesized takes (their measured loudness, else -21 LUFS) by one +// gain under a -1 dBFS limiter. Nothing else: no cloning, no TTS, no effects. +import { execFile } from "node:child_process"; +import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { detectSilence } from "umtool-report-to-video/cut-points"; +import { POST_NARRATION_DEFAULTS, nextTakeNumber, partGapBefore, postIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; +import { measureTake } from "./postNarrationCli.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; + +/** The room kept before and after a part's words when its silence is trimmed. */ +export const RECORD_ROOM = Object.freeze({ head: 0.08, tail: 0.15 }); +/** A recorded voice's label: `operator` unless a guest's. */ +export const RECORD_LABEL_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/; + +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** The span of a part worth keeping, from its silences: `[from, to]` inside `[0, seconds]`. */ +export function trimSpan(silences, seconds, room = RECORD_ROOM) { + let from = 0; + let to = seconds; + const lead = silences.find((x) => x.s <= 0.05); + if (lead && lead.e < seconds) from = Math.max(0, lead.e - room.head); + const tail = [...silences].reverse().find((x) => x.e >= seconds - 0.05); + if (tail && tail.s > from) to = Math.min(seconds, tail.s + room.tail); + if (to - from < 0.2) return { from: 0, to: seconds }; + return { from: r3(from), to: r3(to) }; +} + +/** The level the project's synthesized takes read at (their mean LUFS), else the default. */ +export function targetLufsOf(manifest) { + const v = []; + for (const e of manifest?.timeline ?? []) { + for (const t of e?.narration?.takes ?? []) if (t?.engine && t.engine !== "recorded" && Number.isFinite(t.lufs)) v.push(t.lufs); + } + return v.length ? Math.round((v.reduce((a, b) => a + b, 0) / v.length) * 10) / 10 : POST_NARRATION_DEFAULTS.lufs; +} + +/** + * KEEP A RECORDING: `parts` `[{ file (an uploaded blob, absolute), text, para }]` + * in reading order, made into take-<n>.recorded-<label>.wav and added to + * `entry`'s takes (picked) through the writer. Returns the take. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} entry + * @param {Array<{ file: string, text?: string, para?: number }>} parts + * @param {{ label?: string, manifest?: Record<string, any>, note?: string | null, script?: string | null }} [o] + */ +export async function keepRecording(project, entry, parts, { label = "operator", manifest = null, note = null, script = null } = {}) { + if (!RECORD_LABEL_RE.test(label)) throw new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`); + if (!parts.length) throw new Error("nothing was recorded"); + const pid = postIdOf(entry); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const n = nextTakeNumber(entry, await readdir(dir).catch(() => [])); + const base = `take-${n}.recorded-${label}`; + const rel = `${takesDirOf(pid)}/${base}.wav`; + const partsRel = `${takesDirOf(pid)}/${base}.parts`; + const partsDir = path.join(project.dir, ...partsRel.split("/")); + await mkdir(partsDir, { recursive: true }); + const ff = FFMPEG(); + // Each part: decoded, measured, trimmed of its silence at either end. + const made = []; + for (const [k, p] of parts.entries()) { + const raw = path.join(partsDir, `.p${String(k + 1).padStart(2, "0")}.raw.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", p.file, "-vn", "-ac", "1", "-ar", "48000", "-c:a", "pcm_s16le", raw]); + const { seconds } = await measureTake(raw); + const sil = await detectSilence(raw, { silenceMinDur: 0.15 }).catch(() => []); + const span = trimSpan(sil, seconds ?? 0); + const out = path.join(partsDir, `p${String(k + 1).padStart(2, "0")}.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", raw, "-af", `atrim=${span.from}:${span.to},asetpts=PTS-STARTPTS`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", out]); + await rm(raw, { force: true }); + made.push({ out, seconds: r3(span.to - span.from), text: p.text, para: Number.isInteger(p.para) ? p.para : k }); + } + // Joined with the pauses, then brought to the synthesized takes' level. + const withPara = made.map((m) => ({ ...m })); + const inputs = []; + const chain = []; + let start = 0; + const partsOut = []; + withPara.forEach((m, k) => { + const gap = partGapBefore(withPara, k); + if (gap > 0) chain.push({ silence: gap }); + start += gap; + partsOut.push({ n: k + 1, para: m.para, ...(m.text ? { text: m.text } : {}), file: `${partsRel}/p${String(k + 1).padStart(2, "0")}.wav`, start: r3(start), seconds: m.seconds, gapBefore: gap }); + chain.push({ file: m.out }); + start += m.seconds; + }); + const filters = []; + const labels = []; + for (const [j, c] of chain.entries()) { + if (c.file) { + inputs.push("-i", c.file); + filters.push(`[${inputs.filter((x) => x === "-i").length - 1}:a]aformat=sample_rates=48000:channel_layouts=mono[s${j}]`); + } else { + inputs.push("-f", "lavfi", "-t", String(c.silence), "-i", "anullsrc=channel_layout=mono:sample_rate=48000"); + filters.push(`[${inputs.filter((x) => x === "-i").length - 1}:a]anull[s${j}]`); + } + labels.push(`[s${j}]`); + } + const joined = path.join(dir, `.${base}.joined.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", `${filters.join(";")};${labels.join("")}concat=n=${labels.length}:v=0:a=1[a]`, "-map", "[a]", "-c:a", "pcm_s16le", joined]); + const measured = await measureTake(joined); + const target = targetLufsOf(manifest ?? {}); + const gain = Number.isFinite(measured.lufs) ? Math.max(-20, Math.min(30, target - measured.lufs)) : 0; + const tmp = path.join(dir, `.${base}.tmp.wav`); + await execFileP(ff, ["-nostdin", "-v", "error", "-y", "-i", joined, "-af", `volume=${gain.toFixed(2)}dB,alimiter=limit=0.891251:level=0:latency=1`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp]); + await rm(joined, { force: true }); + const abs = path.join(project.dir, ...rel.split("/")); + await rename(tmp, abs); + if (!(await stat(abs).catch(() => null))?.isFile()) throw new Error(`${rel} was not written`); + const m = await measureTake(abs); + const take = { + file: rel, engine: "recorded", voice: label, label, seconds: m.seconds, source: { kind: "recorded", voice: label }, script: String(script ?? entry.narration?.script ?? ""), + at: new Date().toISOString(), ...(Number.isFinite(m.lufs) ? { lufs: m.lufs } : {}), ...(note ? { note } : {}), + ...(partsOut.length > 1 ? { parts: partsOut } : {}), + }; + const { result, editNotes } = await withEditNotes(project, async () => + updatePostNarration(project.dir, entry.id, { addTake: take, ...(script !== null && script !== entry.narration?.script ? { script } : {}) }, { token: await manifestToken(project.dir) }), + ); + return { take, gain: Math.round(gain * 100) / 100, target, result, editNotes }; +} 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"; import { applyCaptureContext } from "./postContext.mjs"; @@ -325,6 +326,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; @@ -409,10 +474,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 }; } @@ -451,3 +525,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,14 +60,24 @@ 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.", " umtool posts context <project> [--dry-run] [--json]", " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", " none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.", ].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", "--derive", "--op", "--delete"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -340,6 +350,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 === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out }); if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); @@ -413,7 +444,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; } } @@ -558,8 +589,16 @@ async function contextCommand(projectArg, { root, json, dryRun, out }) { return 0; } -/** `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); @@ -575,3 +614,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/recordSession.mjs b/umtool/lib/report/recordSession.mjs @@ -0,0 +1,122 @@ +// THE RECORDING SESSION's store (operator, 3 Nov: "I need to do a dramatic +// reading of this starting tomorrow"): a person reading a cut's posts aloud, +// PART BY PART, on /projects/<p>/narration/record. Every part is written to +// disk the moment it is kept, so nothing is lost on a crash and a reload +// resumes where the reading stopped: +// +// narration/posts/<postId>/.recording-<label>/ +// session.json { version, id, label, count, parts: { "<n>": { file, text, para, at, bytes, type } } } +// p01.webm … each part as the browser recorded it (webm/opus, ogg/opus) +// +// When every part of the post is in, `finishSession` makes them one recorded +// take (postRecord.mjs keepRecording: each part trimmed of its silence, joined +// with the parts' pauses, levelled to the synthesized takes), PICKED, and +// clears the session. Plain ESM. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { RECORD_LABEL_RE, keepRecording } from "./postRecord.mjs"; + +/** A part is at most this large (a minute of opus is well under 1 MB). */ +export const SESSION_PART_MAX = 100 * 1024 * 1024; + +export const sessionDirOf = (projectDir, entry, label) => path.join(projectDir, ...takesDirOf(postIdOf(entry)).split("/"), `.recording-${label}`); + +const checkLabel = (label) => { + if (!RECORD_LABEL_RE.test(String(label))) throw Object.assign(new Error(`"${label}" is not a voice label (a-z, 0-9, - and _)`), { status: 400 }); +}; + +/** The session of `entry` for voice `label` ({ parts: {} } when none). */ +export async function readSession(projectDir, entry, label = "operator") { + checkLabel(label); + const dir = sessionDirOf(projectDir, entry, label); + try { + const doc = JSON.parse(await readFile(path.join(dir, "session.json"), "utf8")); + return { version: 1, id: entry.id, label, count: null, parts: {}, ...doc }; + } catch { + return { version: 1, id: entry.id, label, count: null, parts: {} }; + } +} + +async function writeSession(dir, doc) { + const tmp = path.join(dir, `.session.${process.pid}.${Date.now()}.json`); + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, path.join(dir, "session.json")); +} + +const extOf = (type) => (/ogg/.test(type) ? "ogg" : /wav/.test(type) ? "wav" : /mp4|aac/.test(type) ? "m4a" : "webm"); + +/** + * KEEP ONE PART: its bytes written (through a rename: never half a file), the + * session updated. `n` from 1; `count` how many parts the post's read has. + * + * @param {string} projectDir + * @param {Record<string, any>} entry + * @param {{ n: number, count: number, text: string, para: number, bytes: Uint8Array, type?: string, label?: string }} part + */ +export async function savePart(projectDir, entry, { n, count, text, para, bytes, type = "audio/webm", label = "operator" }) { + checkLabel(label); + if (!Number.isInteger(n) || n < 1 || !Number.isInteger(count) || count < 1 || n > count || count > 200) throw Object.assign(new Error("a part is n of count (1 ≤ n ≤ count ≤ 200)"), { status: 400 }); + if (!bytes?.byteLength) throw Object.assign(new Error("the part is empty"), { status: 400 }); + if (bytes.byteLength > SESSION_PART_MAX) throw Object.assign(new Error("the part is too large"), { status: 413 }); + const dir = sessionDirOf(projectDir, entry, label); + await mkdir(dir, { recursive: true }); + const doc = await readSession(projectDir, entry, label); + // A different split of the script (it was edited): the parts kept so far no longer line up. + if (doc.count !== null && doc.count !== count) doc.parts = {}; + const name = `p${String(n).padStart(2, "0")}.${extOf(type)}`; + const tmp = path.join(dir, `.${name}.${process.pid}.tmp`); + await writeFile(tmp, bytes); + const old = doc.parts[String(n)]; + await rename(tmp, path.join(dir, name)); + if (old && old.file !== name) await rm(path.join(dir, old.file), { force: true }); + doc.count = count; + doc.parts[String(n)] = { file: name, text: String(text ?? ""), para: Number.isInteger(para) ? para : n - 1, at: new Date().toISOString(), bytes: bytes.byteLength, type }; + await writeSession(dir, doc); + return doc; +} + +/** Drop one part of the session (redo it). */ +export async function discardPart(projectDir, entry, n, label = "operator") { + const dir = sessionDirOf(projectDir, entry, label); + const doc = await readSession(projectDir, entry, label); + const p = doc.parts[String(n)]; + if (p) { + await rm(path.join(dir, p.file), { force: true }); + delete doc.parts[String(n)]; + await writeSession(dir, doc); + } + return doc; +} + +/** The absolute file of a session part, or null. */ +export async function partFile(projectDir, entry, n, label = "operator") { + const doc = await readSession(projectDir, entry, label); + const p = doc.parts[String(n)]; + return p ? path.join(sessionDirOf(projectDir, entry, label), p.file) : null; +} + +/** + * FINISH: every part of the post in -> one recorded take (keepRecording), + * picked; the session cleared. Refused, naming the missing parts, otherwise. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} entry + * @param {{ label?: string, manifest?: Record<string, any> | null, script?: string | null }} [o] + */ +export async function finishSession(project, entry, { label = "operator", manifest = null, script = null } = {}) { + const doc = await readSession(project.dir, entry, label); + const count = doc.count ?? 0; + const missing = []; + for (let n = 1; n <= count; n += 1) if (!doc.parts[String(n)]) missing.push(n); + if (!count || missing.length) throw Object.assign(new Error(count ? `parts ${missing.join(", ")} of ${count} are not recorded yet` : "nothing recorded yet"), { status: 400 }); + const dir = sessionDirOf(project.dir, entry, label); + const parts = []; + for (let n = 1; n <= count; n += 1) { + const p = doc.parts[String(n)]; + parts.push({ file: path.join(dir, p.file), text: p.text, para: p.para }); + } + const kept = await keepRecording(project, entry, parts, { label, manifest, script }); + await rm(dir, { recursive: true, force: true }); + return kept; +} 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 @@ -456,6 +456,11 @@ export function threadsGeometry(render) { }; } +/** 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; + /** * Where things sit INSIDE the deck region (region-local pixels). The * composition draws from this; umtool's preview frames the same rect. A @@ -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,114 @@ 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, o = {}) { + return askEditorOp("/api/ops/tts", body, o); +} + +/** The editor has no engine for an op (its route is missing, or it says the engine is not installed). */ +export class OpNotInstalled extends Error { + constructor(route, detail) { + super(`the editor has no engine for ${route} yet (not installed${detail ? `: ${detail}` : ""})`); + this.name = "OpNotInstalled"; + this.route = route; + } +} + +/** The result line of a voice op (`@@voice-result <json>`), else a tts one; null when none. */ +export function opResultIn(lines) { + let found = null; + for (const line of lines ?? []) { + for (const marker of ["@@voice-result ", TTS_RESULT_MARKER]) { + const at = String(line).indexOf(marker); + if (at < 0) continue; + try { + found = JSON.parse(String(line).slice(at + marker.length)); + } catch { + /* a mangled line */ + } + } + } + return found; +} + +/** + * ONE ASK OF ANY OF THE EDITOR's MEDIA OPS, waited for: `POST <route>` with + * `body` (its `out` the absolute file the result is written to), then its job + * followed to the end. Returns `{ jobId, result }` (result: the job's result + * line, null when the op writes none and `out` is given). An op the editor + * has no engine for throws OpNotInstalled. + */ +export async function askEditorOp(route, 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}${route}`, { method: "POST", headers, body: JSON.stringify(clean) }); + const j = await res.json().catch(() => ({})); + if (res.status === 404 || /not installed|no engine|unknown op/i.test(String(j.error ?? ""))) throw new OpNotInstalled(route, j.error ?? (res.status === 404 ? "no such op" : "")); + if (!res.ok || !j.ok || typeof j.jobId !== "string") throw new Error(`the editor refused it (${route}, 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" || opResultIn(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 = opResultIn(tail); + if (!result && !clean.out) throw new Error(`editor job ${jobId} is done, but its log carries no result 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,111 @@ export function mediaSteps(entry) { return indexed.map((m) => ({ kind: m.kind, items: [m], seconds: mediaSeconds(m) })); } -/** 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)); +/** + * 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`. + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + */ +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). + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + */ +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 }} + * @param {Record<string, any>} entry + * @param {Record<string, any>} [render] + * @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 +260,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 +274,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 +430,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 +480,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 +544,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 +592,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 +607,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 +631,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 +644,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 +659,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 +699,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 +734,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 +743,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,585 @@ +// 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", "derived"]); + +/** + * WHAT A TAKE IS (operator, 2 Nov: "pure AI voice, record voice, and run AI on + * recorded voice -- and re-run or re-record"): a `source` and the `steps` + * applied to it, and the file that came out -- + * + * source { kind: "tts", engine, voice, script } a stock voice, the editor's tts op + * { kind: "recorded", voice } a person's own read, recorded on the bench + * { kind: "take", from: <take id> } DERIVED: a new take made from another + * steps [{ op, engine?, params?, ranAt, job? }] the processing that made a derived take + * + * A derived take never overwrites the one it came from. Its ops are the + * editor's (each a job, like tts): `enhance` (denoise, level, de-reverb) and + * `convert` (voice conversion: the performance kept, the timbre swapped for a + * STOCK synthetic voice -- never a real person's). A take's id is its file's + * name without `.wav`. Takes from before this shape (engine and voice only) + * read as their source (takeSourceOf). + */ +export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); +/** The editor's op route for each. */ +export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); + +/** A take's id: its file's name without `.wav`. */ +export const takeIdOf = (t) => String(t?.file ?? "").split("/").pop().replace(/\.wav$/i, ""); + +/** A take's source, its own or read from the older shape. */ +export function takeSourceOf(t) { + if (isObj(t?.source)) return t.source; + if (t?.engine === "recorded") return { kind: "recorded", voice: t.voice ?? t.label ?? "operator" }; + return { kind: "tts", engine: t?.engine ?? "orpheus", voice: t?.voice ?? "zac", ...(typeof t?.script === "string" ? { script: t.script } : {}) }; +} + +/** The root of a take's chain (the source take a derived one came from, followed back), or the take itself. */ +export function rootTakeOf(takes, t) { + let cur = t; + for (let i = 0; i < 20; i += 1) { + const src = takeSourceOf(cur); + if (src.kind !== "take") return cur; + const up = takes.find((x) => takeIdOf(x) === src.from); + if (!up) return cur; + cur = up; + } + return cur; +} + +/** The file a derived take of post `postId` is written to: take-<n>.<op>-<engine>.wav. */ +export const derivedFileOf = (postId, n, op, engine) => `${takesDirOf(postId)}/take-${n}.${op}-${String(engine ?? "default").replace(/[^A-Za-z0-9_-]/g, "")}.wav`; + +/** + * 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", "source", "steps"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]); +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) { + const clean = 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, " "); + // Its paragraphs (blank lines) stay paragraphs -- a long read is recorded and synthesized by them (scriptParts). + const paras = clean + .split(/\n[ \t]*\n/) + .map((para) => + para + .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(), + ) + .filter(Boolean); + return paras.map((p, i) => (i < paras.length - 1 && !/[.!?…,;:—-]["')\]]*$/.test(p) ? `${p}.` : p)).join("\n\n"); +} + +/** + * 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.source !== undefined) { + const src = t.source; + const ok = isObj(src) && ( + (src.kind === "tts" && POST_NARRATION_ENGINES.includes(src.engine) && typeof src.voice === "string") || + (src.kind === "recorded" && typeof src.voice === "string" && VOICE_RE.test(src.voice)) || + (src.kind === "take" && typeof src.from === "string" && n.takes.some((x) => takeIdOf(x) === src.from && x !== t)) + ); + if (!ok) errors.push(`${tw}.source must be {kind: "tts", engine, voice}, {kind: "recorded", voice} or {kind: "take", from: <one of its takes' id>}`); + } + if (t.steps !== undefined) { + if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`); + else t.steps.forEach((st, k) => { + if (!isObj(st) || !POST_DERIVE_OPS.includes(st.op)) errors.push(`${tw}.steps[${k}].op must be one of ${POST_DERIVE_OPS.join(", ")}`); + else for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); + }); + } + 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; + const takes = entry.narration.takes ?? []; + // A voice converted to a stock synthetic one says so; enhanced, the chain's root decides. + const convert = (t.steps ?? []).find((st) => st?.op === "convert"); + if (convert) return `Narration: voice converted to a synthetic voice (${convert.engine ?? "?"} · ${convert.voice ?? "?"})`; + const root = rootTakeOf(takes, t); + // A recorded take is a person's own voice: nothing synthetic to disclose. + if (root.engine === "recorded" || takeSourceOf(root).kind === "recorded") return null; + if (root !== t) return postNarrationDisclosure({ ...entry, narration: { ...entry.narration, takes: [root], pick: 0 } }); + 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 ?? "?"})`; +} + +// --------------------------------------------------------------------------- +// A long read, PART BY PART (operator, 2 Nov: "some of these massive posts +// will need to compose multiple read paragraphs and can't be one-shot"): the +// script split into parts -- its paragraphs (blank lines), a paragraph over +// POST_PART_WORDS words split at its sentence ends -- each synthesized or +// recorded on its own and joined with a pause between them. +// --------------------------------------------------------------------------- + +/** A part reads at most this many words (a paragraph longer than it is split at a sentence end). */ +export const POST_PART_WORDS = 60; +/** The pause the parts are joined with: between paragraphs, and inside one. */ +export const POST_PART_GAP = Object.freeze({ para: 0.6, inside: 0.25 }); + +const wordsOf = (t) => (String(t).trim() ? String(t).trim().split(/\s+/).length : 0); + +/** + * The script's PARTS, pure: `[{ n, para, text }]` (n from 1, para the + * paragraph's index from 0). A script of one short paragraph is one part. + */ +export function scriptParts(script, max = POST_PART_WORDS) { + const paras = String(script ?? "").split(/\n\s*\n/).map((p) => p.replace(/\s+/g, " ").trim()).filter(Boolean); + const out = []; + paras.forEach((p, para) => { + if (wordsOf(p) <= max) { + out.push({ para, text: p }); + return; + } + const sentences = p.match(/[^.!?…]+[.!?…]+["')\]]*\s*|[^.!?…]+$/g) ?? [p]; + let cur = ""; + for (const sen of sentences) { + if (cur && wordsOf(cur) + wordsOf(sen) > max) { + out.push({ para, text: cur.trim() }); + cur = ""; + } + cur += sen; + } + if (cur.trim()) out.push({ para, text: cur.trim() }); + }); + return out.map((p, i) => ({ n: i + 1, ...p })); +} + +/** The pause before part `k` of `parts` (0 before the first). */ +export const partGapBefore = (parts, k) => (k === 0 ? 0 : parts[k].para !== parts[k - 1].para ? POST_PART_GAP.para : POST_PART_GAP.inside); + +/** The part being read at item second `s` (the picked take's parts, on the item's clock), or null. */ +export function partAt(entry, sch, s) { + const t = pickedTake(entry); + const parts = Array.isArray(t?.parts) ? t.parts : []; + if (!parts.length || !sch) return null; + const local = s - sch.at; + let cur = null; + for (const p of parts) if (local >= p.start - 0.05) cur = p; + return cur; +} diff --git a/umtool/report-to-video/post-narration.test.mjs b/umtool/report-to-video/post-narration.test.mjs @@ -0,0 +1,201 @@ +// 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.\n\nI hate the weak"); + assert.equal(speakableText("one\ntwo\n\nthree"), "one. two.\n\nthree"); + 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]]); });