Archilyzer · Source

archilyzer

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

commit e0e9474ca872fb7e0b4c57c5bcf480c2338e1314
parent 3c6cde68c815c116269799dc472a332c3918d64c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 00:40:14 -0400

umtool: narrated cards — a card's words spoken by a stock voice the editor synthesizes (release 25 T2)

A card may carry `narration: {text, voice?, engine?}` and `seconds: "auto"`;
`render.narration` sets engine, voice, speed, level (−17.7 LUFS), lead and
tail. narrate-via-editor.mjs asks `POST /api/ops/tts` once per narration, as
one batch, follows each job to its `@@tts-result` line and keeps the WAV in
out/narration/<key>.{wav,json} (measured seconds and loudness, sha256, the
disclosure). The build swaps the card's `anullsrc` for that WAV (levelled,
limited at −1 dBFS, delayed by the lead, padded and trimmed), resolves "auto",
refuses a shorter authored number as a lint error, and re-encodes a narrated
card only when its key changes (segments/<id>.narration.json). The driver runs
the narration step before the build; busy.mjs sees it. validateNarration runs
in the build and the lint (Orpheus's expressive tags allowed, any other <…>
refused by name; words capped without the tags). The cut's comment metadata
and the description/chapters exports carry "Narration: synthetic voice
(kokoro · af_heart)". A manifest without narration builds byte-for-byte as
before. The e2e editor stub answers the tts door with an ffmpeg tone.

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

Diffstat:
Mumtool/app/api/report/build/route.ts | 5+++++
Mumtool/docs/report-video.md | 16+++++++++++++++-
Mumtool/e2e/fixtures/editor-stub.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 14++++++++++++++
Aumtool/e2e/report-narration.spec.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/busy.mjs | 2+-
Mumtool/lib/report/deliverables.test.mjs | 2++
Mumtool/lib/report/driver.mjs | 22+++++++++++++++++++++-
Mumtool/lib/report/driver.test.mjs | 17+++++++++++++++++
Aumtool/lib/report/export-narration.test.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/export.mjs | 9++++++++-
Mumtool/report-to-video/README.md | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/report-to-video/build-video.mjs | 219++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/deck.mjs | 3+++
Mumtool/report-to-video/lint.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/narrate-via-editor.mjs | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narrate.test.mjs | 297+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration-store.mjs | 131+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration.mjs | 320+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration.test.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/verify-build.mjs | 3++-
22 files changed, 1755 insertions(+), 52 deletions(-)

diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -82,6 +82,7 @@ export async function POST(request: Request) { chaptersOnly?: boolean; chromeOnly?: boolean; preview?: { at: number; dur: number } | null; + narrate?: boolean; } = {}; if (raw.variant !== undefined && raw.variant !== "") { const v = String(raw.variant); @@ -121,6 +122,10 @@ export async function POST(request: Request) { } const clipCount = clipsOf(manifest).length; + // A card that carries narration puts the editor's tts step before the build. + if (manifest.timeline?.some((e: { type?: string; narration?: unknown }) => e?.type === "card" && e.narration)) { + options.narrate = true; + } const steps = buildSteps(project, { preset, only, skipFetch, clipCount, options }); const view = { project: project.id, diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -779,7 +779,21 @@ variant with anything on disk). All derived from the manifest plus the build's offsets — `out/<variant>/chapters.ffmeta` when present, else `segmentOffsets()` over the segments, else a refusal with the reason. `toc-bbcode` reproduces the hand-made `toc.bbcode.txt` shape; `description` adds the source list; `chapters` -is YouTube's form and includes cards. Cite URLs follow the QR's rule. +is YouTube's form and includes cards. Cite URLs follow the QR's rule. A cut +with a narrated card (`narration`, below) ends its `description` and `chapters` +with the disclosure line, `Narration: synthetic voice (kokoro · af_heart)`. + +## Narrated cards + +A card's `narration` (`{text, voice?, engine?}`) is spoken by a stock synthetic +voice that the EDITOR synthesizes (`POST /api/ops/tts`); `render.narration` sets +the engine, voice, speed, level and the quiet around the words, and a card's +`seconds: "auto"` is their length. umtool never synthesizes: when the manifest +carries narration, the build chain gains a step before the build, +`narrate-via-editor.mjs`, which asks the editor (the same `ARCHILYZER_EDITOR_URL` +and `WORKER_TOKEN` as a clip fetch, from the server's environment) and keeps each +sound in `out/narration/`. The README's "Narration" section has the shape, the +rules and the validator. ## Re-checking sources across projects diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -29,6 +29,7 @@ const LOG = process.env.E2E_EDITOR_STUB_LOG ?? path.join(process.cwd(), "editor- const requests = []; const jobs = new Map(); +const ttsJobs = new Map(); let nextJob = 1; // BEST-EFFORT, and it has to be. This process and make-fixture.mjs are started @@ -129,6 +130,61 @@ const server = http.createServer((req, res) => { return; } + // THE TTS DOOR (release 25): POST /api/ops/tts -> { ok, jobId }, the job + // followed on GET /api/ops/job/<id>[?tail=N] to a log whose last line is + // `@@tts-result {wav, seconds, engine, voice, cached, durationMs, waitedMs}`. + // The "voice" is an ffmpeg tone, never a TTS engine: the suite proves the + // narration crossed the wire and landed under the card, not how it sounds. + // An engine other than kokoro / espeak-ng / orpheus is refused, as the + // editor refuses one it does not have. + if (req.method === "POST" && url.pathname === "/api/ops/tts") { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + let body; + try { + body = JSON.parse(raw); + } catch { + return json(res, 400, { ok: false, error: "malformed JSON body" }); + } + requests.push({ route: "tts", ...body, authorization: auth }); + record(); + if (typeof body.text !== "string" || !body.text.trim()) return json(res, 400, { ok: false, error: "text is required" }); + if (body.engine && !["kokoro", "espeak-ng", "orpheus"].includes(body.engine)) { + return json(res, 400, { ok: false, error: `unknown tts engine "${body.engine}"` }); + } + const id = `stub-tts-${nextJob++}`; + const seconds = Math.max(0.5, Math.round(body.text.split(/\s+/).length * 0.3 * 100) / 100); + const wav = path.join(path.dirname(LOG), "tts-cache", `${id}.wav`); + mkdirSync(path.dirname(wav), { recursive: true }); + const r = spawnSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `sine=frequency=262:sample_rate=48000:duration=${seconds}`, + "-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" }); + ttsJobs.set(id, { + polls: 0, + result: { wav, seconds, engine: body.engine ?? "kokoro", voice: body.voice ?? "af_heart", cached: false, durationMs: 5, waitedMs: 0 }, + }); + json(res, 202, { ok: true, jobId: id }); + }); + return; + } + const opsJob = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && opsJob && ttsJobs.has(opsJob[1])) { + req.resume(); + const j = ttsJobs.get(opsJob[1]); + const tail = url.searchParams.get("tail"); + if (!tail) 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, { + ok: true, + job: { id: opsJob[1], kind: "tts-file", status }, + ...(tail ? { tail: ["tts: synthesizing (stub)", `@@tts-result ${JSON.stringify(j.result)}`] } : {}), + }); + } + // GET /api/media/fetch-window/<jobId> const poll = /^\/api\/media\/fetch-window\/(.+)$/.exec(url.pathname); if (req.method === "GET" && poll) { diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1377,6 +1377,19 @@ writeProject( ]), ); +// A NARRATED card (release 25). Its voice is asked of the editor stub (a tone, +// never a TTS engine) by the narration step before the build, kept in +// out/narration/, and played under the card; `seconds: "auto"` is its length. +// The plain card beside it stays digital silence. +writeProject( + "narration-fixture", + manifest("narration-fixture", "The Narration Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "card", id: "k01", style: "chapter", seconds: "auto", heading: "Then", narration: { text: "Six months later, the county said yes." } }, + { type: "clip", id: "c01", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence" }, + { type: "card", id: "k02", style: "chapter", seconds: 1, heading: "Now" }, + ]), +); + // -- THE ON-SCREEN DECK ------------------------------------------------------- // // A stub HYPERFRAMES_BIN, so a deck build renders offline in a second instead @@ -1917,4 +1930,5 @@ console.log(` onscreen-posts-fixture (writable, deck on, three posts, console.log(` onscreen-feed-fixture (writable, posts feed, built by the spec)`); console.log(` deliver-stop-fixture (writable: six confirmed clips to cut, for Stop and resume)`); console.log(` takes-fixture (writable: takes/ with 4 takes over 2 groups, 1 skipped)`); +console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`); console.log(` ${taken} candidate files copied, 2 mix tracks synthesised`); diff --git a/umtool/e2e/report-narration.spec.ts b/umtool/e2e/report-narration.spec.ts @@ -0,0 +1,101 @@ +import { test, expect } from "@playwright/test"; +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// A narrated card (release 25, T2), built through the driver. +// +// The voice is asked of the EDITOR, never synthesized here: the chain's +// narration step posts the card's words to `/api/ops/tts`, follows the job to +// its `@@tts-result` line, and keeps the sound in out/narration/; the build +// puts it under the card. The editor is the suite's stub +// (e2e/fixtures/editor-stub.mjs), whose "voice" is an ffmpeg tone -- what this +// proves is that the words, the engine and the voice crossed the wire and the +// sound landed under the right card, and that the plain card beside it stayed +// silent. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/narration-fixture"; +const OUT = path.join(FIXTURE, "reports", "narration-fixture", "out"); +const SEGS = path.join(OUT, "sourced", "segments"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const DISCLOSURE = "Narration: synthetic voice (kokoro · af_heart)"; + +type Job = { id: string; state: string; error: string | null; events?: { ev: string; id?: string; cached?: boolean }[] }; + +async function waitFor(request: import("@playwright/test").APIRequestContext, id: string, ms = 180_000): Promise<Job> { + const until = Date.now() + ms; + while (Date.now() < until) { + const j = (await (await request.get(`/api/report/build?job=${id}`)).json()) as Job; + if (j.state !== "running") return j; + await new Promise((r) => setTimeout(r, 400)); + } + throw new Error("the job never finished"); +} + +/** The loudest sample of a file's sound, in dB; -91 is digital silence. */ +function maxVolume(file: string): number { + const r = spawnSync("ffmpeg", ["-nostdin", "-hide_banner", "-i", file, "-af", "volumedetect", "-f", "null", "-"], { encoding: "utf8" }); + const m = /max_volume:\s*(-?[\d.]+) dB/.exec(r.stderr); + return m ? Number(m[1]) : NaN; +} + +const ttsAsks = (): { route?: string; text?: string; engine?: string; voice?: string; speed?: number; authorization?: string }[] => { + try { + return (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string }[]).filter((r) => r.route === "tts"); + } catch { + return []; + } +}; + +test("the chain asks the editor for the narration before the build", async ({ request }) => { + const r = await request.post("/api/report/build?dry=1", { data: { project: PROJECT, preset: "fast" } }); + const j = (await r.json()) as { steps: { label: string; argv: string[] }[] }; + const scripts = j.steps.map((s) => path.basename(s.argv[1] ?? "")); + const at = scripts.indexOf("narrate-via-editor.mjs"); + expect(at).toBeGreaterThan(0); + expect(scripts[at + 1]).toBe("build-video.mjs"); + // Nothing was asked by a dry run. + expect(ttsAsks()).toHaveLength(0); +}); + +test("a narrated card speaks, its length is the narration's, the plain card is silent, and the exports disclose the voice", async ({ request }) => { + const start = await request.post("/api/report/build", { data: { project: PROJECT, preset: "fast" } }); + expect(start.ok()).toBeTruthy(); + const { job } = (await start.json()) as { job: Job }; + const done = await waitFor(request, job.id); + expect(done.state, done.error ?? "").toBe("done"); + + // One ask, the words verbatim, the engine and voice named, the token sent. + const asks = ttsAsks(); + expect(asks).toHaveLength(1); + expect(asks[0]).toMatchObject({ + text: "Six months later, the county said yes.", engine: "kokoro", voice: "af_heart", speed: 1, + authorization: "Bearer umtool-e2e-token", + }); + expect((done.events ?? []).some((e) => e.ev === "narrate" && e.id === "k01" && e.cached === false)).toBe(true); + + // Kept beside the build, with its disclosure. + const records = readdirSync(path.join(OUT, "narration")).filter((n) => n.endsWith(".json")); + expect(records).toHaveLength(1); + const rec = JSON.parse(readFileSync(path.join(OUT, "narration", records[0]), "utf8")) as { disclosure: string; seconds: number }; + expect(rec.disclosure).toBe(DISCLOSURE); + + // "auto": 7 words at the stub's 0.3 s = 2.1 s, plus the lead and the tail (0.8 + 0.8) -> 3.7 s. + const seg = JSON.parse(readFileSync(path.join(SEGS, "k01.narration.json"), "utf8")) as { seconds: number }; + expect(seg.seconds).toBe(3.7); + const dur = Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path.join(SEGS, "k01.mp4")]).toString()); + expect(Math.abs(dur - 3.7)).toBeLessThan(0.15); + expect(maxVolume(path.join(SEGS, "k01.mp4"))).toBeGreaterThan(-30); + expect(maxVolume(path.join(SEGS, "k02.mp4"))).toBe(-91); + + for (const format of ["description", "chapters"]) { + const text = await (await request.get(`/api/report/export?project=${encodeURIComponent(PROJECT)}&format=${format}`)).text(); + expect(text, format).toContain(DISCLOSURE); + } + expect(existsSync(path.join(OUT, "narration-fixture.mp4"))).toBe(true); +}); diff --git a/umtool/lib/report/busy.mjs b/umtool/lib/report/busy.mjs @@ -26,7 +26,7 @@ import { readdirSync, readFileSync, readlinkSync, realpathSync } from "node:fs"; import path from "node:path"; export const PIPELINE_SCRIPTS = - /(build-video|check-availability|render-cards|compose-chrome|verify-build|fetch-via-editor|resolve-windows|cut-from-cache|share-batch)\.mjs/; + /(build-video|check-availability|render-cards|compose-chrome|verify-build|fetch-via-editor|narrate-via-editor|resolve-windows|cut-from-cache|share-batch)\.mjs/; const OWN_SCRIPTS = /(^|\/)(apply-manifest|build)\.py$/; /** diff --git a/umtool/lib/report/deliverables.test.mjs b/umtool/lib/report/deliverables.test.mjs @@ -377,6 +377,8 @@ test("namesProject: a script names a project by path, or by --project id, name o // A build step names the manifest by path. assert.equal(namesProject(["node", "build-video.mjs", "/r/folder/proj/video.manifest.json"], null, p), true); assert.equal(namesProject(["node", "build-video.mjs", "/r/folder/proj-2/video.manifest.json"], null, p), false); + // The narration step, which writes out/narration/, is a pipeline process too. + assert.equal(namesProject(["node", "narrate-via-editor.mjs", "/r/folder/proj/video.manifest.json", "--out", "/r/folder/proj/out"], null, p), true); // The report's own scripts, by working directory. assert.equal(namesProject(["python3", "apply-manifest.py"], "/r/folder/proj", p), true); assert.equal(namesProject(["python3", "build.py"], "/r/folder/proj-2", p), false); diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -61,7 +61,12 @@ export const buildTimeoutMs = (clipCount, xfade) => * five-minute cap; a deck re-render is a render plus a concat of the whole * cut, so it keeps the build's own timeout. * - * @typedef {{ variant?: string, xfade?: boolean, chaptersOnly?: boolean, chromeOnly?: boolean, preview?: { at: number, dur: number } | null }} BuildOptions + * narrate the manifest carries card narration (release 25): a step + * before the build asks the editor for every voice not yet + * kept (narrate-via-editor.mjs). Not for the runs that build + * no segment from the manifest's words. + * + * @typedef {{ variant?: string, xfade?: boolean, chaptersOnly?: boolean, chromeOnly?: boolean, preview?: { at: number, dur: number } | null, narrate?: boolean }} BuildOptions */ /** The step-1 preflight alone, reused by the check-sources job. */ @@ -105,6 +110,21 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch = }, ]; + // The narration, asked of the editor before the build: the editor's tts + // queue is serial, and a voice synthesized here is kept beside the build + // (out/narration/), so the build reads it rather than asking mid-render. + if (options.narrate && !quick && !options.chromeOnly) { + const narrateArgv = ["node", script("narrate-via-editor.mjs"), manifest, "--out", outDir, "--progress", "ndjson"]; + if (options.variant) narrateArgv.push("--variant", options.variant); + steps.push({ + ...base, + label: "synthesize the narration (asks the editor)", + argv: narrateArgv, + ndjson: true, + timeoutMs: 30 * 60_000, + }); + } + const buildArgv = [ "node", script("build-video.mjs"), diff --git a/umtool/lib/report/driver.test.mjs b/umtool/lib/report/driver.test.mjs @@ -49,3 +49,20 @@ test("a whole-source fetch asks at the manifest's maxHeightSource, unless told a // A bad explicit height falls through to the manifest's. assert.equal(heightOf(argvOf({ manifest, maxHeight: "tall" })), "720"); }); + +test("narrate: the editor's tts step goes before the build, told the cut; never for a run that builds no card", () => { + const steps = buildSteps(project, { preset: "final", options: { narrate: true, variant: "full" } }); + const labels = steps.map((s) => s.label); + const at = labels.indexOf("synthesize the narration (asks the editor)"); + assert.ok(at > 0, labels.join(" | ")); + assert.ok(steps[at + 1].argv.some((a) => a.endsWith("build-video.mjs"))); + const argv = steps[at].argv; + assert.ok(argv[1].endsWith("narrate-via-editor.mjs")); + assert.deepEqual(argv.slice(2), ["/r/p/video.manifest.json", "--out", "/r/p/out", "--progress", "ndjson", "--variant", "full"]); + assert.equal(steps[at].ndjson, true); + // Without narration, or for chapters, a preview or the deck alone: no step. + for (const opts of [{ preset: "final" }, { preset: "final", options: { narrate: true, chaptersOnly: true } }, + { preset: "final", options: { narrate: true, chromeOnly: true } }, { preset: "final", options: { narrate: true, preview: { at: 0, dur: 1 } } }]) { + assert.ok(buildSteps(project, opts).every((s) => !s.argv.some((a) => a.endsWith("narrate-via-editor.mjs"))), JSON.stringify(opts)); + } +}); diff --git a/umtool/lib/report/export-narration.test.mjs b/umtool/lib/report/export-narration.test.mjs @@ -0,0 +1,46 @@ +// The posting exports of a NARRATED cut carry the disclosure line (release 25, +// T2): the description and the chapters list say "Narration: synthetic voice +// (<engine> · <voice>)"; a cut without narration exports exactly as it did. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { exportProject } from "./export.mjs"; + +const FFMETA = (n) => + [";FFMETADATA1", "", ...Array.from({ length: n }, (_, i) => ["[CHAPTER]", "TIMEBASE=1/1000", `START=${i * 5000}`, `END=${(i + 1) * 5000}`, `title=Entry ${i + 1}`, ""]).flat()].join("\n"); + +function project(root, timeline) { + const dir = path.join(root, `p-${Math.random().toString(36).slice(2)}`); + mkdirSync(path.join(dir, "out", "sourced"), { recursive: true }); + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify({ + slug: "s", title: "A cut", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { fps: 30 }, timeline, + })); + writeFileSync(path.join(dir, "out", "sourced", "chapters.ffmeta"), FFMETA(timeline.length)); + return dir; +} + +test("description and chapters disclose a narrated cut's synthetic voice; a plain cut's are unchanged", async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "umtool-export-narration-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const clip = { id: "c1", type: "clip", video: "v1", start: 1, end: 4 }; + const narrated = project(root, [ + { id: "k1", type: "card", heading: "Then", seconds: "auto", narration: { text: "Then it happened." } }, + clip, + ]); + const plain = project(root, [{ id: "k1", type: "card", heading: "Then", seconds: 4 }, clip]); + const line = "Narration: synthetic voice (kokoro · af_heart)"; + + const desc = (await exportProject(narrated, "description")).text; + assert.ok(desc.trimEnd().endsWith(line), desc); + const chapters = (await exportProject(narrated, "chapters")).text; + assert.equal(chapters, `00:00 Then\n00:05 2. v1\n\n${line}\n`); + + assert.ok(!(await exportProject(plain, "description")).text.includes("Narration")); + assert.equal((await exportProject(plain, "chapters")).text, "00:00 Then\n00:05 2. v1\n"); +}); diff --git a/umtool/lib/report/export.mjs b/umtool/lib/report/export.mjs @@ -19,6 +19,7 @@ import path from "node:path"; import { DEFAULT_VARIANT, selectVariant, segmentOffsets } from "umtool-report-to-video/build-video"; import { citeUrlFor, channelFor, readAvailability, readManifest } from "../projects/report.mjs"; import { teaserTitle } from "umtool-report-to-video/deck"; +import { narrationDisclosure } from "umtool-report-to-video/narration"; import { outDirState } from "./storage.mjs"; export const EXPORT_FORMATS = ["toc-bbcode", "toc-markdown", "description", "chapters"]; @@ -156,6 +157,8 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = cite: e.type === "clip" ? citeUrlFor(m, e) : null, })); const clipRows = rows.filter((r) => r.e.type === "clip"); + // "Narration: synthetic voice (kokoro · af_heart)", or null for a cut with none. + const disclosure = narrationDisclosure(m); let text; if (format === "toc-bbcode") { @@ -179,7 +182,10 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = ].join("\n"); } else if (format === "chapters") { // YouTube needs the first at 00:00 and every entry present, cards included. - text = rows.map((r) => `${ytTime(r.i === 0 ? 0 : r.at)} ${r.title}`).join("\n") + "\n"; + // A narrated cut says so below them (narrationDisclosure); one without + // narration exports exactly as it did. + text = rows.map((r) => `${ytTime(r.i === 0 ? 0 : r.at)} ${r.title}`).join("\n") + "\n" + + (disclosure ? `\n${disclosure}\n` : ""); } else { const avail = await readAvailability(dir); const titles = new Map((avail?.sources ?? []).map((s) => [s.key, s.title])); @@ -197,6 +203,7 @@ export async function exportProject(dir, format, { variant = DEFAULT_VARIANT } = "Sources:", ...[...seen.values()].map((s) => `- ${s.title ? `${s.title} (${s.key})` : s.key} — ${s.cite}`), "", + ...(disclosure ? [disclosure, ""] : []), ].join("\n"); } return { text, format, variant, offsets: { source: off.source, file: off.file, ...(off.note ? { note: off.note } : {}) } }; diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -248,7 +248,7 @@ about a window, a format string or the Rumble retry. Three additions exist for t - **`--progress ndjson`** — one JSON object per line instead of prose: `start`, `card`, `clip`, `fetch`, `snap`, `segment`, `entry-failed`, `concat`, - `chapters`, `note`, `done`, `error`. The event set is exactly what was already + `chapters`, `narrate`, `note`, `done`, `error`. The event set is exactly what was already being printed; making it a format switch is what stops a wording change from breaking the driver. - **`--continue-on-error`** — record a failed entry and carry on. A dead source at @@ -1065,6 +1065,74 @@ form (one field per line with a break picker), and a preview — a still of the composition at a chosen second through compose-chrome's `--still`, which the deck's true-still route already does for its region. +### Narration: `narration` on a card, and `render.narration` + +A card may carry words spoken by a **stock synthetic voice** (release 25). It is +opt-in and explicit: the words are the author's, never derived from the card, +so "show, don't tell" stays the default and a manifest without narration builds +exactly as it did — every card's sound is still `anullsrc`. + +```jsonc +{ "type": "card", "id": "ch3", "style": "chapter", "heading": "Then: the county", + "seconds": "auto", // the narration's length + lead + tail + "narration": { "text": "Six months later, the county said yes.", + "voice": "af_heart", // optional: a stock voice of the engine + "engine": "kokoro" } } // optional: kokoro | orpheus | espeak-ng + +"render": { "narration": { // every key optional + "engine": "kokoro", "voice": "af_heart", // the ruled defaults, sent on every ask + "speed": 1, // 0.5–2 + "lufs": -17.7, // the voice's level (−30 to −10): the clips' (the teaser level) + "lead": 0.8, "tail": 0.8 } } // quiet before / after the words, each ≥ the crossfade +``` + +- **The voice comes from the editor**, never from this directory: + `narrate-via-editor.mjs <manifest> [--out <dir>] [--variant v] [--progress ndjson]` + posts each card's words to `POST /api/ops/tts` (`{text, engine, voice, speed}`, + Bearer `WORKER_TOKEN`, the editor at `ARCHILYZER_EDITOR_URL`), as one batch, + follows each job (`GET /api/ops/job/<id>`) to the `@@tts-result` line of its + log, and copies the WAV it names into `out/narration/<key>.wav` beside a + record `<key>.json` (the words, engine, voice, speed, measured seconds and + LUFS, the copy's sha256, the editor job, the disclosure). `<key>` is a hash of + the words, engine, voice and speed: a changed word is a new ask; an unchanged + one is never asked again. The driver runs it as a step before the build; a + build that finds a narration missing asks the editor itself, unless + `--skip-fetch`, which refuses naming the card. +- **The card's sound** is the WAV in place of `anullsrc` + (`narrationAudioFilter`, narration.mjs): resampled to `audioRate` and + `audioChannels`, levelled from its measured loudness to `lufs`, limited at + −1 dBFS, delayed by `lead`, padded and trimmed to exactly the card's seconds. + The picture is the card's, unchanged. +- **`seconds: "auto"`** is `lead` + the words + `tail`, up to the tenth. A + number shorter than that is a lint ERROR, which refuses the build before it + renders (`--lint` judges the narrations already kept in `out/narration/`). + Before a build, the deck's estimated schedule reckons 2.7 words a second. +- **Rebuilt only on change**: `segments/<id>.narration.json` records the key the + segment was encoded from (the card as resolved, the render block, the + narration's sha256, the sound's filter, the encode); a build whose key matches + leaves the segment alone, and one that differs writes a new file through a + rename. +- **The disclosure** — `Narration: synthetic voice (kokoro · af_heart)`, each + engine · voice once — is in the cut's `comment` metadata, at the end of the + `description` and `chapters` exports, and in each narration's record. +- **Validated** by `validateNarration` (narration.mjs), which the build runs + before a single fetch and the lint reports: narration on cards only; text + non-empty, at most 300 words (tags not counted); the only `<…>` allowed are + Orpheus's expressive tags `<laugh> <chuckle> <sigh> <cough> <sniffle> <groan> + <yawn> <gasp>` (Kokoro's side strips them); an engine of the three, a voice + that is a stock voice's id, each setting in its range, `lead`/`tail` at least + the crossfade, and `seconds: "auto"` only beside a narration. Voices are stock + voices only — no reference audio, no cloning, ever. + +#### Writing narration + +Write it for the ear: short sentences, the beat before the turn, a little warmth +or weariness where the moment has it — a tag like `<sigh>` is a delivery note, +not a claim. The drama never outruns the sources. Every factual claim in a +narration is exactly what the cited clips and posts support: the same numbers, +the same dates, the same hedges, nothing a viewer could not check against the +QR on the next clip. When in doubt, cut the line and let the clip say it. + ## Chrome, not cards **The ferret-rescue cut has no cards at all** — no title, no chapter breaks, no @@ -2102,9 +2170,9 @@ usual reason a naive concat produces a broken or audio-desynced file. ## Not done yet -- **Narration is silent by design.** Cards carry the connective text; the only - audio is the clips'. A TTS layer would attach per card (`seconds` already gives - it a duration to fill) — deliberately deferred rather than designed out. +- **Narration is on cards only.** A card may carry a synthetic voice (see + "Narration" above); narration UNDER a clip — mixed into the join graph — is + not built, and neither is narration derived from a card's own words. - **Snapping is silence-based, not word-based.** It finds gaps in the audio, which is usually the same thing as a word boundary but is not guaranteed to be — a speaker who does not pause gets the unsnapped cut. Forced alignment against diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -134,8 +134,16 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; +// A card's `narration` (release 25): validated, resolved and levelled in +// narration.mjs (pure); its synthesized sound is kept in out/narration/ +// (narration-store.mjs) by asking the editor (narrate-via-editor.mjs). +import { + hasNarration, narratedCardSeconds, narrationAudioFilter, narrationDisclosure, narrationGainDb, narrationsOf, + cardNarrationSeconds, resolveNarrationRender, validateNarration, +} from "./narration.mjs"; +import { narrationDir, narrationWavPath, readNarrationRecords } from "./narration-store.mjs"; // The lint a build runs before it renders, and the prune after its final mux. -import { lintManifest, lintManifestFile } from "./lint.mjs"; +import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. @@ -389,7 +397,7 @@ export function variantPaths(outRoot, slug, variant) { // printed -- this is a formatting switch, not new instrumentation. // // Events: start, card, clip, fetch, snap, segment, entry-failed, concat, -// chapters, chrome, note, done. +// chapters, chrome, narrate, note, done. const HUMAN = { start: (e) => `${e.title} — ${e.entries} entr(ies)`, card: (e) => `card ${e.id}`, @@ -407,6 +415,9 @@ const HUMAN = { ` snap ${e.id}: ${e.start ? "start✓" : "start–"} ${e.end ? "end✓" : "end–"} ` + `(${Number(e.seconds).toFixed(1)}s)`, segment: () => null, + // A card's narration: kept already, or synthesized by the editor just now. + narrate: (e) => + ` narration ${e.id}: ${e.cached ? "kept" : "synthesized"} — ${Number(e.seconds).toFixed(2)}s (${e.engine} · ${e.voice})`, "entry-failed": (e) => ` ** ${e.id} failed: ${e.message}`, concat: (e) => `${e.mode === "xfade" ? "crossfading" : "hard-cutting"} ${e.n} segments…`, chapters: (e) => `chapters: ${e.n} marker(s) -> ${e.file}`, @@ -1321,7 +1332,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, * The files an entry's segment build writes in `segments/`: the picture and * the records beside it. */ -export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".quote.txt", ".attrib.txt", ".channel.txt"]); +export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".narration.json", ".quote.txt", ".attrib.txt", ".channel.txt"]); /** * Before an entry's segment is rebuilt: each of its files in `segDir` that is @@ -1395,41 +1406,131 @@ async function qrForEntry(entry, provenance, render, outDir) { return { png, url }; } -async function buildCardSegment(card, render, outDir, nodes, framing = null) { - const png = await renderCard(card, render, outDir, nodes); - const seg = path.join(outDir, "segments", `${card.id}.mp4`); - const dur = String(card.seconds); - // Under the deck a card is either full frame -- `overCards: "hide"`, the - // deck slides away over it, and the card encodes exactly as it always has -- - // or framed into the footage box like a clip, so the deck can stay up over - // it without covering its bottom rows. +/** + * A card's framing under the deck: either full frame -- `overCards: "hide"`, + * the deck slides away over it, and the card encodes exactly as it always has + * -- or framed into the footage box like a clip, so the deck can stay up over + * it without covering its bottom rows. `fr` is null when full frame. + */ +function cardFraming(render, framing) { const framed = deckOn(render) && resolveDeck(render).overCards === "show"; const fr = framed ? framing ?? segmentFraming(render) : null; const vf = framed ? deckFramingFilter(render, { feed: fr.layout === "feed" }) : `fps=${render.fps},setsar=1`; + return { fr, vf }; +} - await execFileP( - FFMPEG, - [ - "-nostdin", "-v", "error", "-y", - // Without -framerate the image demuxer runs at its 25 fps default and the - // `-vf fps=30` below DUPLICATES a frame — at the segment's first frame, - // which is exactly where the next xfade seam lands. - "-loop", "1", "-framerate", String(render.fps), "-t", dur, "-i", png, - "-f", "lavfi", "-t", dur, - "-i", `anullsrc=channel_layout=stereo:sample_rate=${render.audioRate}`, - "-vf", vf, - ...encodeArgs(render), - "-shortest", - seg, - ], - { maxBuffer: 1 << 24 }, - ); +/** + * A card's encode: its still for `seconds`, and DIGITAL SILENCE (`anullsrc`) + * for its sound -- every card without a narration, exactly as it always was. + */ +export function cardEncodeArgs({ png, seconds, vf, render, outPath }) { + const dur = String(seconds); + return [ + "-nostdin", "-v", "error", "-y", + // Without -framerate the image demuxer runs at its 25 fps default and the + // `-vf fps=30` below DUPLICATES a frame — at the segment's first frame, + // which is exactly where the next xfade seam lands. + "-loop", "1", "-framerate", String(render.fps), "-t", dur, "-i", png, + "-f", "lavfi", "-t", dur, + "-i", `anullsrc=channel_layout=stereo:sample_rate=${render.audioRate}`, + "-vf", vf, + ...encodeArgs(render), + "-shortest", + outPath, + ]; +} + +/** + * A NARRATED card's encode: the same still and picture chain, and for its sound + * the narration's WAV in place of `anullsrc`, through `audio` + * (narrationAudioFilter: levelled, limited, delayed by the lead, padded and + * trimmed to exactly `seconds`). + */ +export function narratedCardEncodeArgs({ png, wav, seconds, vf, audio, render, outPath }) { + const dur = String(seconds); + return [ + "-nostdin", "-v", "error", "-y", + "-loop", "1", "-framerate", String(render.fps), "-t", dur, "-i", png, + "-i", wav, + "-map", "0:v", "-map", "1:a", + "-vf", vf, + "-af", audio, + ...encodeArgs(render), + "-t", dur, + "-shortest", + outPath, + ]; +} + +async function buildCardSegment(card, render, outDir, nodes, framing = null) { + const png = await renderCard(card, render, outDir, nodes); + const seg = path.join(outDir, "segments", `${card.id}.mp4`); + const { fr, vf } = cardFraming(render, framing); + await execFileP(FFMPEG, cardEncodeArgs({ png, seconds: card.seconds, vf, render, outPath: seg }), { maxBuffer: 1 << 24 }); if (fr) await writeCutRecord(seg, { version: 1, id: card.id, framing: fr }); return seg; } +/** The record beside a narrated card's segment: the key it was encoded from. */ +export const narrationSegmentRecordPath = (seg) => seg.replace(/\.mp4$/, ".narration.json"); + +/** + * A narrated card's segment key: everything its picture and sound are made + * from -- the card as this run resolved it (its words, its seconds), the + * render block, the footer's nodes, the framing, the narration's sound (by the + * copy's sha256), the sound's filter and the encode's parameters. A segment + * whose recorded key differs is re-encoded; one whose key matches is not. + */ +export const narratedCardKey = ({ card, render, nodes, framing, narrationSha, audio, vf }) => + createHash("sha256") + .update(JSON.stringify({ v: 1, card, render, nodes: nodes ?? null, framing: framing ?? null, narration: narrationSha, audio, vf, encode: encodeArgs(render) })) + .digest("hex"); + +/** + * A card with a `narration`: its still with the narration's sound under it + * (narratedCardEncodeArgs). `rec` is its narration's record (narration-store); + * without one the card cannot be built, and says how to make one. Re-encoded + * only when its key changed (`<id>.narration.json`); written beside the + * segment and renamed over it, as a teaser's is, so a segment that is a link + * to another take's file is replaced, never written through. + */ +async function buildNarratedCardSegment(card, render, outDir, nodes, framing, rec, dir) { + if (!rec) { + throw new Error( + `${card.id}: its narration has not been synthesized — run narrate-via-editor.mjs on the manifest ` + + "(a build without --skip-fetch asks the editor itself)", + ); + } + const seconds = typeof card.seconds === "number" ? card.seconds : narratedCardSeconds(rec.seconds, render); + const resolved = { ...card, seconds }; + const nr = resolveNarrationRender(render); + const seg = path.join(outDir, "segments", `${card.id}.mp4`); + const { fr, vf } = cardFraming(render, framing); + const audio = narrationAudioFilter({ seconds, lead: nr.lead, gainDb: narrationGainDb(rec.lufs, nr.lufs), render }); + const key = narratedCardKey({ card: resolved, render, nodes, framing: fr, narrationSha: rec.sha256, audio, vf }); + const recPath = narrationSegmentRecordPath(seg); + const old = await readFile(recPath, "utf8").then(JSON.parse, () => null); + if (old?.key === key && (await exists(seg))) { + EMIT("note", { id: card.id, message: `${card.id}: narrated card unchanged (key ${key.slice(0, 12)})` }); + return seg; + } + const png = await renderCard(resolved, render, outDir, nodes); + const tmp = path.join(path.dirname(seg), `.${card.id}.${process.pid}.tmp.mp4`); + try { + await execFileP(FFMPEG, narratedCardEncodeArgs({ + png, wav: narrationWavPath(dir, rec.key), seconds, vf, audio, render, outPath: tmp, + }), { maxBuffer: 1 << 24 }); + await rename(tmp, seg); + } finally { + await rm(tmp, { force: true }); + } + if (fr) await replaceFile(cutRecordPath(seg), JSON.stringify({ version: 1, id: card.id, framing: fr }) + "\n"); + await replaceFile(recPath, JSON.stringify({ key, narration: rec.key, seconds, voiceSeconds: rec.seconds, engine: rec.engine, voice: rec.voice }) + "\n"); + return seg; +} + // ---- the teaser ----------------------------------------------------------- // A `teaser` entry is a full-frame graphic card -- a season teaser's "coming // soon" screen -- drawn by a HyperFrames composition from the entry's words @@ -3835,7 +3936,7 @@ export async function measureChromeSchedule({ manifest, entries, segments, D }) return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [] }); } -async function muxChapters(finalPath, entries, segments, D, outDir, provenance, fps, deck = false, joins = null) { +async function muxChapters(finalPath, entries, segments, D, outDir, provenance, fps, deck = false, joins = null, { disclosure = null } = {}) { if (segments.length < 2) return; // The cut's own offsets: under the deck a held clip is longer in the cut // than its file, and every chapter after it starts that much later. @@ -3863,7 +3964,11 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, await execFileP( FFMPEG, ["-nostdin", "-v", "error", "-y", "-i", finalPath, "-i", metaPath, - "-map", "0", "-map_metadata", "0", "-map_chapters", "1", "-c", "copy", tmp], + "-map", "0", "-map_metadata", "0", "-map_chapters", "1", + // A narrated cut says so in its own metadata (narrationDisclosure); a cut + // without narration is muxed exactly as it always was. + ...(disclosure ? ["-metadata", `comment=${disclosure}`] : []), + "-c", "copy", tmp], { maxBuffer: 1 << 24 }, ); await rename(tmp, finalPath); @@ -4009,7 +4114,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly { const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), - ...validateFlipEntries(whole), + ...validateFlipEntries(whole), ...validateNarration(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } @@ -4148,6 +4253,42 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } } + // A card's `narration`: its sound kept in out/narration/ (narration-store), + // asked of the editor for any that is not (narrate-via-editor -- the driver + // runs it as a step before this, so a build usually finds them all kept), + // never under --skip-fetch or by a run that rebuilds no segment. Then each + // narrated card's length: `seconds: "auto"` becomes the words' length plus + // the lead and the tail, on this run's copy -- and a number shorter than + // that refuses the build, as a lint error, before anything renders. + const narration = new Map(); // card id -> its record + const wantNarration = narrationsOf(manifest).filter((n) => !only || n.id === only); + const narrationStore = narrationDir(outRoot); + if (wantNarration.length && !opts.chaptersOnly && !opts.railOnly && !opts.chromePreview) { + for (const [id, rec] of await readNarrationRecords(narrationStore, wantNarration)) narration.set(id, rec); + const missing = wantNarration.filter((n) => !narration.has(n.id)); + if (missing.length && !opts.skipFetch && !opts.chromeOnly) { + EMIT("note", { message: `narration: ${missing.length} card(s) to synthesize — asking the editor` }); + const { narrateCut, editorFromEnv } = await import("./narrate-via-editor.mjs"); + const got = await narrateCut({ + narrations: missing, dir: narrationStore, editor: opts.editor ?? editorFromEnv(), + emit: (ev, f) => EMIT(ev, f), ...(opts.narrationPollMs ? { pollMs: opts.narrationPollMs } : {}), + }); + for (const [id, rec] of got) narration.set(id, rec); + } else { + for (const n of wantNarration) { + const rec = narration.get(n.id); + if (rec) EMIT("narrate", { id: n.id, key: n.key, cached: true, seconds: rec.seconds, engine: rec.engine, voice: rec.voice }); + } + } + const secondsById = new Map([...narration].map(([id, rec]) => [id, rec.seconds])); + const short = narrationLengthErrors(manifest, secondsById, { only: only ?? null }); + if (short.length) throw new Error(`lint: ${short.join("; ")} — --lint lists them`); + manifest.timeline = manifest.timeline.map((e) => { + if (!hasNarration(e) || !secondsById.has(e.id)) return e; + return { ...e, seconds: cardNarrationSeconds(e, secondsById.get(e.id), render).seconds }; + }); + } + // `--no-network`: every clip's source is found on disk BEFORE anything is // rendered, and a build that would have to fetch even one is refused here, // naming each -- not twenty minutes in, at the first one. (The runs that @@ -4211,6 +4352,14 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // file only when its render changed (buildTeaserSegment). Returns the // segment's path. const buildEntrySegment = async (entry, i, o = opts) => { + // A narrated card checks its own record first and writes through a + // rename, as a teaser does (buildNarratedCardSegment). + if (hasNarration(entry)) { + EMIT("card", { id: entry.id, i, n: entries.length }); + return buildNarratedCardSegment( + entry, render, outDir, manifest.timelineNodes, framing, narration.get(entry.id) ?? null, narrationStore, + ); + } if (entry.type !== "teaser" && entry.type !== "clip") { await detachSegmentFiles(path.join(outDir, "segments"), entry.id); } @@ -4283,7 +4432,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } // Under the deck the cut's offsets include the holds: measured, not written. const joins = deck ? segmentJoins(await measureChromeSchedule({ manifest, entries, segments: segs, D })) : null; - await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins); + await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: narrationDisclosure(manifest) }); return { out: finalPath, failures: [] }; } @@ -4318,7 +4467,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // applyRail re-encodes, so the chapters muxed onto the previous final are // gone. Put them back, or --rail-only quietly ships a chapterless cut. if (!opts.noChapters) { - await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render)); + await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: narrationDisclosure(manifest) }); } } EMIT("done", { out, failures: [] }); @@ -4425,7 +4574,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } await assertConcatLength(dirs.final, schedule.total, render.fps, "deck build"); // The overlay re-encodes, so the chapters on the previous final are gone. - if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins); + if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: narrationDisclosure(manifest) }); await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; @@ -4548,7 +4697,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // shortest=1), and a hang means an unbounded -loop 1. if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build"); - if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins); + if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: narrationDisclosure(manifest) }); // A branded cut with a `thumbnail` gets one beside it. The cut is already // done, so a thumbnail that cannot be made is said, not thrown. diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -22,6 +22,7 @@ import { } from "./factcheck.mjs"; import { threadOf, threadSchedule, threadsOn, validateThreads } from "./threads.mjs"; import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs"; +import { estimatedNarratedCardSeconds, hasNarration } from "./narration.mjs"; /** Is the left panel on: the thread rail (threads.mjs) or the flips panel (flips.mjs) -- one region, one or the other. */ export const railOn = (render) => threadsOn(render) || flipsOn(render); @@ -510,6 +511,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render)) if (entry.type === "image") return Number(entry.seconds ?? 4); // A teaser's dip makes its segment longer by the dissolve and the black (`teaserLead`). if (entry.type === "teaser") return teaserSeconds(entry, D, render.fps ?? 30); + // A narrated card's `"auto"` is its words' length, estimated until a build measures it. + if (hasNarration(entry)) return estimatedNarratedCardSeconds(entry, render); return Number(entry.seconds ?? 5); } diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -20,9 +20,14 @@ // - a QR below MIN_QR_PX_PER_MODULE_720P pixels per module once the cut is // watched at 720p, or a link too long for a QR at all; // - everything the manifest validators say -- validateThreadEntries and -// validateFlipEntries (threads.mjs, flips.mjs), and the cut edits, teasers, -// claims and posts validators a build runs first -- so `--lint` alone -// reports what a build would refuse, all at once. +// validateFlipEntries (threads.mjs, flips.mjs), validateNarration +// (narration.mjs), and the cut edits, teasers, claims and posts validators +// a build runs first -- so `--lint` alone reports what a build would +// refuse, all at once; +// - a narrated card whose `seconds` is a number shorter than its narration +// needs (the lead, the words, the tail). The words' length is known once +// the voice is synthesized: the build checks it then, and `--lint` reads +// the kept narrations (out/narration/) and checks those it finds. // WARNINGS // - a teaser line over TEASER_HOUSE_CHARS -- an overline's or a kicker's // first tier, or any line's break: house style, not a fit. (A title's @@ -61,6 +66,7 @@ import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { qrUrlFor } from "./render-cards.mjs"; +import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; export const TEASER_HOUSE_CHARS = 34; export const MIN_QR_PX_PER_MODULE_720P = 1.5; @@ -193,7 +199,7 @@ export function imageSrcsOf(manifest, { only = null } = {}) { export function validatorErrors(whole) { const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), - ...validateThreadEntries(whole), ...validateFlipEntries(whole), + ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); @@ -202,18 +208,44 @@ export function validatorErrors(whole) { } /** + * The narrated cards whose authored `seconds` is shorter than their narration + * needs, as errors. `secondsById` maps a card id to its synthesized + * narration's seconds; a card not in it (not synthesized yet) is not judged. + * + * @param {any} manifest the cut + * @param {Map<string, number>} secondsById + * @param {{ only?: string|null }} [opts] + */ +export function narrationLengthErrors(manifest, secondsById, { only = null } = {}) { + const out = []; + for (const e of manifest.timeline ?? []) { + if (!hasNarration(e) || (only && e.id !== only) || !secondsById.has(e.id)) continue; + const words = secondsById.get(e.id); + const { need, short } = cardNarrationSeconds(e, words, manifest.render); + if (short) { + out.push( + `timeline ${e.id}: seconds is ${e.seconds}, and its narration needs ${need}s ` + + `(${Number(words).toFixed(2)}s of words plus the lead and the tail) — set "auto" or at least ${need}`, + ); + } + } + return out; +} + +/** * The lint of one cut. * * @param {any} manifest the cut, as selectVariant returns it * @param {{ manifestDir?: string, whole?: any, exists?: (p: string) => boolean, - * only?: string|null, validators?: boolean }} [opts] + * only?: string|null, validators?: boolean, narrationSeconds?: Map<string, number> | null }} [opts] * `whole` is the manifest as written (what the validators read); * `validators: false` leaves them out (a build has run them already); - * `only` lints one timeline entry (and the posts attached to it). + * `only` lints one timeline entry (and the posts attached to it); + * `narrationSeconds` the kept narrations' seconds by card id (null: not read). * @returns {{ errors: string[], warnings: string[] }} */ export function lintManifest(manifest, { - manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, + manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, narrationSeconds = null, } = {}) { const errors = []; const warnings = []; @@ -263,6 +295,15 @@ export function lintManifest(manifest, { } } + if (narrationSeconds) { + errors.push(...narrationLengthErrors(manifest, narrationSeconds, { only })); + for (const e of manifest.timeline ?? []) { + if (hasNarration(e) && (!only || e.id === only) && !narrationSeconds.has(e.id)) { + warnings.push(`timeline ${e.id}: its narration is not synthesized yet — its length is checked once it is`); + } + } + } + if (validators && !only) errors.push(...validatorErrors(whole)); return { errors, warnings }; } @@ -280,7 +321,15 @@ export async function lintManifestFile(manifestPath, { variant = "sourced", only const manifestDir = path.dirname(path.resolve(manifestPath)); try { const manifest = selectVariant(whole, variant); - return { ...lintManifest(manifest, { manifestDir, whole, only }), variant }; + // The narrations already kept beside the build (out/narration/), so a + // narrated card's authored seconds can be judged without asking for a voice. + let narrationSeconds = null; + if (narrationsOf(manifest).length) { + const { narrationDir, readNarrationRecords } = await import("./narration-store.mjs"); + const recs = await readNarrationRecords(narrationDir(path.join(manifestDir, "out")), narrationsOf(manifest)); + narrationSeconds = new Map([...recs].map(([id, r]) => [id, r.seconds])); + } + return { ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds }), variant }; } catch (err) { return { errors: [err?.message ?? String(err)], warnings: [], variant }; } diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -0,0 +1,257 @@ +#!/usr/bin/env node +// Synthesize a cut's narration BY ASKING THE EDITOR, never by running a TTS +// engine here (release 25, T2 -- the "no ASR by hand" rule's twin). +// +// node umtool/report-to-video/narrate-via-editor.mjs <manifest.json> +// [--out <dir>] [--variant sourced|full] [--progress ndjson] +// +// Every card `narration` in the manifest (or in one cut of it, `--variant`) is +// one `POST /api/ops/tts` -- `{ text, engine, voice, speed }`, the engine and +// voice always named (narration.mjs's defaults: kokoro · af_heart) -- all asked +// up front, as one batch; then each job is followed (`GET /api/ops/job/<id>`) +// to its end, and its log's `@@tts-result <json>` line names the WAV the +// editor wrote. That sound is copied in beside the build and measured +// (narration-store.mjs, `out/narration/<key>.{wav,json}`), so build-video +// reads it from there. A narration already kept is not asked again; the editor +// answers a repeat ask from its own cache too. +// +// The editor is `ARCHILYZER_EDITOR_URL` (default http://localhost:3001), asked +// with the shared `WORKER_TOKEN` -- both from the environment, never argv, as +// fetch-via-editor.mjs. It waits as long as the jobs do (the editor's tts +// queue is serial), saying a queued job's place as it moves; Ctrl-C stops +// waiting (exit 130) and the jobs finish on the editor, so the next ask is a +// cache hit. +// +// The build runs the same code (`narrateCut`) for any narration it finds +// missing, unless `--skip-fetch`; the driver runs this script as its own step +// before the build, so the build finds them all kept. +import { readFile } from "node:fs/promises"; +import path from "node:path"; + +import { narrationsOf } from "./narration.mjs"; +import { keepNarration, narrationDir, readNarrationRecord } from "./narration-store.mjs"; + +export const DEFAULT_EDITOR = "http://localhost:3001"; +/** The log line a tts job's result is on: this marker, then the result as compact JSON. */ +export const TTS_RESULT_MARKER = "@@tts-result "; + +const POLL_MS = Number(process.env.NARRATE_VIA_EDITOR_POLL_MS) > 0 ? Number(process.env.NARRATE_VIA_EDITOR_POLL_MS) : 1000; +const MAX_POLL_FAILURES = 10; +const MAX_BACKOFF_MS = 30_000; +const TAIL_LINES = 80; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** The editor to ask and the token to ask with, from the environment; throws naming the variable. */ +export function editorFromEnv(env = process.env) { + const url = (env.ARCHILYZER_EDITOR_URL || DEFAULT_EDITOR).replace(/\/+$/, ""); + const token = env.WORKER_TOKEN ?? ""; + if (!token) { + throw new Error( + "WORKER_TOKEN is not set, so the editor cannot be asked for the narration. " + + "Set WORKER_TOKEN to the same value the editor runs with.", + ); + } + return { url, token }; +} + +/** The `@@tts-result` in a job's log lines, parsed; null when there is none. The last one wins. */ +export function ttsResultIn(lines) { + let found = null; + for (const line of lines ?? []) { + const at = String(line).indexOf(TTS_RESULT_MARKER); + if (at < 0) continue; + try { + found = JSON.parse(String(line).slice(at + TTS_RESULT_MARKER.length)); + } catch { + /* a mangled line: the next one may be whole */ + } + } + return found; +} + +/** The body one narration is asked with: its words, and the engine, voice and speed always named. */ +export const ttsBody = (n) => ({ text: n.text, engine: n.engine, voice: n.voice, speed: n.speed }); + +/** + * Ask the editor for every narration in `narrations` (narrationsOf) not yet + * kept in `dir`, wait for each, keep each. Returns the records by card id -- + * the ones already kept included. + * + * @param {{ narrations: any[], dir: string, editor?: { url: string, token: string }, + * emit?: (ev: string, fields?: object) => void, pollMs?: number, + * onWaiting?: (jobIds: Set<string>) => void }} opts + */ +export async function narrateCut({ narrations, dir, editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onWaiting = () => {} }) { + const records = new Map(); + const ask = []; + for (const n of narrations) { + const rec = await readNarrationRecord(dir, n.key); + if (rec) { + records.set(n.id, rec); + emit("narrate", { id: n.id, key: n.key, cached: true, seconds: rec.seconds, engine: rec.engine, voice: rec.voice }); + } else { + ask.push(n); + } + } + if (!ask.length) return records; + + 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}`); + } + }; + + // One batch: every ask posted before any is waited for. Two cards with the + // same words, voice and speed are one ask. + const pending = new Map(); // jobId -> { ns: narration[], last: status, place: line } + const byKey = new Map(); + for (const n of ask) { + if (byKey.has(n.key)) { + byKey.get(n.key).ns.push(n); + continue; + } + const res = await reach(`${editor.url}/api/ops/tts`, { method: "POST", headers, body: JSON.stringify(ttsBody(n)) }); + const body = await res.json().catch(() => ({})); + if (!res.ok || !body.ok || typeof body.jobId !== "string") { + // Verbatim: the editor's operator is the person who can act on it. + throw new Error(`the editor refused ${n.id}'s narration (HTTP ${res.status}): ${body.error ?? "no reason given"}`); + } + const slot = { ns: [n], last: "", place: "" }; + byKey.set(n.key, slot); + pending.set(body.jobId, slot); + emit("note", { message: ` ${n.id}: narration asked of the editor as job ${body.jobId} (${n.engine} · ${n.voice})` }); + } + onWaiting(new Set(pending.keys())); + + // Polls one job; retries an unanswered poll with a back-off. + const poll = async (jobId, tail) => { + let backoff = pollMs; + for (let failures = 1; ; failures += 1) { + let res; + try { + res = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}${tail ? `?tail=${TAIL_LINES}` : ""}`, { headers }); + } catch (err) { + if (failures >= MAX_POLL_FAILURES) { + throw new Error(`lost contact with the editor at ${editor.url}: ${failures} polls of job ${jobId} in a row went unanswered (${err?.message ?? err}); it may still be running there`); + } + await sleep(backoff); + backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); + continue; + } + const j = await res.json().catch(() => ({})); + if (!res.ok || !j.ok) throw new Error(`polling editor job ${jobId} failed (HTTP ${res.status}): ${j.error ?? ""}`); + return j; + } + }; + + const failed = []; + while (pending.size) { + for (const [jobId, slot] of pending) { + const j = await poll(jobId, false); + const status = j.job?.status ?? "unknown"; + const label = slot.ns.map((n) => n.id).join(", "); + if (status !== slot.last) { + slot.last = status; + emit("note", { message: ` editor job ${jobId} (${label}): ${status}` }); + } + const q = j.job?.queue; + if (status === "queued" && q && Number(q.position) > 0) { + const line = `queued — position ${q.position}${Number(q.queued) > 0 ? ` of ${q.queued}` : ""}${q.key ? ` on ${q.key}` : ""}`; + if (line !== slot.place) emit("note", { message: ` editor job ${jobId} (${label}): ${line}` }); + slot.place = line; + } + if (status === "queued" || status === "running") continue; + pending.delete(jobId); + const done = await poll(jobId, true); + if (status !== "done") { + const why = (done.tail ?? []).slice(-3).join(" / "); + failed.push(`${label}: editor job ${jobId} ${status === "archived" ? "was lost by the editor (restarted?)" : status}${why ? ` — ${why}` : ""}`); + continue; + } + const result = ttsResultIn(done.tail); + if (!result) { + failed.push(`${label}: editor job ${jobId} is done, but its log carries no ${TTS_RESULT_MARKER.trim()} line`); + continue; + } + // Kept once, under its key; every card that asked for it reads that record. + const rec = await keepNarration(dir, slot.ns[0], result, { jobId }); + for (const n of slot.ns) { + records.set(n.id, rec); + emit("narrate", { + id: n.id, key: n.key, cached: false, editorCached: result.cached === true, + seconds: rec.seconds, engine: rec.engine, voice: rec.voice, jobId, + }); + } + } + onWaiting(new Set(pending.keys())); + if (pending.size) await sleep(pollMs); + } + if (failed.length) throw new Error(`not every narration was synthesized:\n ${failed.join("\n ")}`); + return records; +} + +async function main() { + const argv = process.argv.slice(2); + const flag = (n) => { + const i = argv.indexOf(n); + return i < 0 ? undefined : argv[i + 1]; + }; + const valued = new Set(["--out", "--variant", "--progress"]); + const manifestPath = argv.find((a, i) => !a.startsWith("--") && !valued.has(argv[i - 1])); + let EMIT = (ev, f = {}) => { + if (ev === "note") console.log(f.message); + else if (ev === "narrate") console.log(` ${f.id}: ${f.cached ? "kept already" : "synthesized"} — ${f.seconds}s (${f.engine} · ${f.voice})`); + else if (ev === "done") console.log(`narration: ${f.narrations} card(s)`); + else if (ev === "error") console.error(f.message); + }; + if (flag("--progress") === "ndjson") EMIT = (ev, f = {}) => process.stdout.write(JSON.stringify({ ev, ...f }) + "\n"); + const die = (message, code = 1) => { + EMIT("error", { message }); + if (flag("--progress") === "ndjson") process.stderr.write(`${message}\n`); + process.exit(code); + }; + if (!manifestPath) die("usage: narrate-via-editor.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--progress ndjson]", 2); + + const whole = JSON.parse(await readFile(manifestPath, "utf8")); + // Validated as the build validates it: a manifest the build would refuse is + // never sent to the editor. + const { validateNarration } = await import("./narration.mjs"); + const errors = validateNarration(whole); + if (errors.length) die(`manifest: ${errors.join("; ")}`); + let cut = whole; + if (flag("--variant")) { + const { selectVariant } = await import("./build-video.mjs"); + cut = selectVariant(whole, flag("--variant")); + } + const narrations = narrationsOf(cut); + if (!narrations.length) { + EMIT("note", { message: "no card carries a narration — nothing to synthesize" }); + EMIT("done", { narrations: 0 }); + return; + } + const outRoot = flag("--out") ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); + let waiting = new Set(); + process.on("SIGINT", () => { + if (waiting.size) EMIT("note", { message: `stopped waiting; editor job(s) ${[...waiting].join(", ")} keep running there (ask again and the narration is cached)` }); + process.exit(130); + }); + try { + const records = await narrateCut({ + narrations, dir: narrationDir(outRoot), editor: editorFromEnv(), emit: EMIT, onWaiting: (s) => { waiting = s; }, + }); + EMIT("done", { narrations: records.size, dir: narrationDir(outRoot) }); + } catch (err) { + die(err?.message ?? String(err)); + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((err) => { + console.error(err?.message ?? err); + process.exit(1); + }); +} diff --git a/umtool/report-to-video/narrate.test.mjs b/umtool/report-to-video/narrate.test.mjs @@ -0,0 +1,297 @@ +// A card's narration, end to end against a FAKE editor: narrate-via-editor's +// one batch of `POST /api/ops/tts` asks, the jobs followed to their +// `@@tts-result` line, the sound kept and measured in out/narration/; then a +// build that puts it under the card -- `seconds: "auto"` measured, the record +// beside the segment re-encoding only on change, a card without narration +// still `anullsrc`, the disclosure in the cut's metadata. +// +// The editor is a scripted HTTP server on a loopback port. Its "voice" is an +// ffmpeg tone (`sine`), never a TTS engine. Real encodes, kept tiny; skipped +// without ffmpeg/ffprobe (and the build tests without ImageMagick). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFile, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import http from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { buildVideo, cardEncodeArgs, narratedCardEncodeArgs, setProgressMode } from "./build-video.mjs"; +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; +import { TTS_RESULT_MARKER, narrateCut, ttsResultIn } from "./narrate-via-editor.mjs"; +import { narrationKey, narrationsOf } from "./narration.mjs"; +import { narrationDir, readNarrationRecord } from "./narration-store.mjs"; + +const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "narrate-via-editor.mjs"); +const haveFf = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const haveMagick = spawnSync("magick", ["-version"]).status === 0; +const TOKEN = "tok"; + +/** + * The editor's tts door, stubbed: each ask is a job that is queued for one + * poll, running for one, then done, its log ending in `@@tts-result`. Words + * containing FAIL make a job that fails; a token other than `tok` is a 401. + */ +async function fakeEditor(dir) { + const asks = []; + const jobs = new Map(); + let n = 0; + const server = http.createServer((req, res) => { + const send = (status, body) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); + }; + if (req.headers.authorization !== `Bearer ${TOKEN}`) { + req.resume(); + return send(401, { ok: false, error: "missing bearer token" }); + } + const url = new URL(req.url, "http://x"); + if (req.method === "POST" && url.pathname === "/api/ops/tts") { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + const body = JSON.parse(raw); + asks.push(body); + if (body.engine === "piper") return send(400, { ok: false, error: `unknown tts engine "${body.engine}"` }); + const id = `tts-${++n}`; + const words = String(body.text).split(/\s+/).length; + const seconds = Math.round(words * 0.35 * 100) / 100; + const wav = path.join(dir, `${id}.wav`); + const r = spawnSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `sine=frequency=330:sample_rate=48000:duration=${seconds}`, + "-ac", "1", "-c:a", "pcm_s16le", wav, + ]); + assert.equal(r.status, 0, String(r.stderr)); + jobs.set(id, { polls: 0, fail: /FAIL/.test(body.text), result: { wav, seconds, engine: body.engine, voice: body.voice, cached: false, durationMs: 12, waitedMs: 3 } }); + send(202, { ok: true, jobId: id }); + }); + return; + } + const m = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && m && jobs.has(m[1])) { + req.resume(); + const j = jobs.get(m[1]); + const tail = url.searchParams.get("tail"); + if (!tail) j.polls += 1; + const status = j.polls <= 1 ? "queued" : j.polls === 2 ? "running" : j.fail ? "failed" : "done"; + return send(200, { + ok: true, + job: { id: m[1], kind: "tts-file", status, ...(status === "queued" ? { queue: { key: "tts", position: 1, queued: 2 } } : {}) }, + ...(tail ? { tail: j.fail ? ["synthesizing", "kokoro: the model is missing"] : ["synthesizing", `${TTS_RESULT_MARKER}${JSON.stringify(j.result)}`] } : {}), + }); + } + req.resume(); + send(404, { ok: false, error: "not found" }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const { port } = /** @type {import("node:net").AddressInfo} */ (server.address()); + return { asks, url: `http://127.0.0.1:${port}`, close: () => new Promise((r) => server.close(r)) }; +} + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const RENDER = { + width: 640, height: 360, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2, + palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, qr: false, +}; +const MANIFEST = (timeline, render = {}) => ({ + slug: "narrated", title: "Narrated", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { ...RENDER, ...render }, timeline, +}); +const NARRATED = { id: "k1", type: "card", style: "chapter", heading: "Then", seconds: "auto", narration: { text: "Six months later the county said yes." } }; +const PLAIN = { id: "k0", type: "card", style: "chapter", heading: "Now", seconds: 1 }; + +async function quietly(fn) { + const events = []; + setProgressMode((e) => events.push(e)); + try { + return { result: await fn().catch((err) => ({ err })), events }; + } finally { + setProgressMode("human"); + } +} + +const probe = (file, entries) => { + const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", file], { encoding: "utf8" }); + return JSON.parse(r.stdout); +}; +/** The loudest sample of a file's sound, in dB (volumedetect); -91 is digital silence. */ +const maxVolume = (file) => { + const r = spawnSync("ffmpeg", ["-nostdin", "-hide_banner", "-i", file, "-af", "volumedetect", "-f", "null", "-"], { encoding: "utf8" }); + const m = /max_volume:\s*(-?[\d.]+|-inf) dB/.exec(r.stderr); + return m ? (m[1] === "-inf" ? -Infinity : Number(m[1])) : NaN; +}; + +test("the result line is found anywhere on a log line, the last one winning", () => { + assert.equal(ttsResultIn(["a", "b"]), null); + assert.deepEqual(ttsResultIn([`${TTS_RESULT_MARKER}{"wav":"/a.wav"}`, `[12:00] ${TTS_RESULT_MARKER}{"wav":"/b.wav"}`]), { wav: "/b.wav" }); + assert.deepEqual(ttsResultIn([`${TTS_RESULT_MARKER}{broken`, `${TTS_RESULT_MARKER}{"wav":"/c.wav"}`]), { wav: "/c.wav" }); +}); + +test("narrateCut: one batch, engine and voice always named, followed to the result, kept and measured; a kept one is not asked again", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-")); + const ed = await fakeEditor(root); + t.after(async () => { + await ed.close(); + rmSync(root, { recursive: true, force: true }); + }); + const m = MANIFEST([ + NARRATED, + { ...NARRATED, id: "k2" }, // the same words: one ask + { ...NARRATED, id: "k3", narration: { text: "A second voice <laugh> speaks.", voice: "am_adam" } }, + PLAIN, + ], { narration: { speed: 1.1 } }); + const dir = narrationDir(path.join(root, "out")); + const events = []; + const recs = await narrateCut({ + narrations: narrationsOf(m), dir, editor: { url: ed.url, token: TOKEN }, pollMs: 5, emit: (ev, f) => events.push({ ev, ...f }), + }); + assert.equal(ed.asks.length, 2, "k1 and k2 share their words, voice and speed"); + assert.deepEqual(ed.asks[0], { text: "Six months later the county said yes.", engine: "kokoro", voice: "af_heart", speed: 1.1 }); + assert.deepEqual(ed.asks[1], { text: "A second voice <laugh> speaks.", engine: "kokoro", voice: "am_adam", speed: 1.1 }); + assert.deepEqual([...recs.keys()].sort(), ["k1", "k2", "k3"]); + const rec = recs.get("k1"); + assert.equal(rec.key, narrationKey({ text: NARRATED.narration.text, engine: "kokoro", voice: "af_heart", speed: 1.1 })); + assert.ok(Math.abs(rec.seconds - 2.45) < 0.05, `seconds ${rec.seconds}`); + assert.ok(rec.lufs < -10 && rec.lufs > -40, `lufs ${rec.lufs}`); + assert.match(rec.sha256, /^[0-9a-f]{64}$/); + assert.equal(rec.disclosure, "Narration: synthetic voice (kokoro · af_heart)"); + assert.equal(rec.editor.jobId, "tts-1"); + // A copy beside the build, not the editor's file. + assert.ok(statSync(path.join(dir, `${rec.key}.wav`)).size > 0); + assert.deepEqual(await readNarrationRecord(dir, rec.key), rec); + // The wait said the queue place, and each card's narration. + assert.ok(events.some((e) => e.ev === "note" && /queued — position 1 of 2 on tts/.test(e.message)), JSON.stringify(events)); + assert.equal(events.filter((e) => e.ev === "narrate" && !e.cached).length, 3); + + // Asked again: everything is kept, nothing is asked. + const again = []; + await narrateCut({ narrations: narrationsOf(m), dir, editor: { url: ed.url, token: TOKEN }, pollMs: 5, emit: (ev, f) => again.push({ ev, ...f }) }); + assert.equal(ed.asks.length, 2); + assert.equal(again.filter((e) => e.ev === "narrate" && e.cached).length, 3); +}); + +test("narrateCut: a refusal is the editor's words; a failed job names its card and its log's last lines", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-fail-")); + const ed = await fakeEditor(root); + t.after(async () => { + await ed.close(); + rmSync(root, { recursive: true, force: true }); + }); + const dir = narrationDir(path.join(root, "out")); + const editor = { url: ed.url, token: TOKEN }; + await assert.rejects( + narrateCut({ narrations: [{ id: "k9", text: "Hi.", engine: "piper", voice: "x", speed: 1, key: "a" }], dir, editor, pollMs: 5 }), + /the editor refused k9's narration \(HTTP 400\): unknown tts engine "piper"/, + ); + await assert.rejects( + narrateCut({ narrations: narrationsOf(MANIFEST([{ ...NARRATED, narration: { text: "This will FAIL." } }])), dir, editor, pollMs: 5 }), + /not every narration was synthesized:\n {2}k1: editor job tts-\d+ failed — synthesizing \/ kokoro: the model is missing/, + ); + await assert.rejects( + narrateCut({ narrations: narrationsOf(MANIFEST([NARRATED])), dir, editor: { url: ed.url, token: "wrong" }, pollMs: 5 }), + /HTTP 401\): missing bearer token/, + ); +}); + +test("the CLI: NDJSON events, the token from the environment, refused when it is not set", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-cli-")); + const ed = await fakeEditor(root); + t.after(async () => { + await ed.close(); + rmSync(root, { recursive: true, force: true }); + }); + const manifest = path.join(root, "video.manifest.json"); + writeFileSync(manifest, JSON.stringify(MANIFEST([NARRATED, PLAIN]))); + const run = (env) => new Promise((resolve) => { + execFile(process.execPath, [SCRIPT, manifest, "--progress", "ndjson"], { + env: { ...process.env, NARRATE_VIA_EDITOR_POLL_MS: "5", ARCHILYZER_EDITOR_URL: ed.url, ...env }, + }, (err, stdout) => resolve({ code: err ? err.code : 0, events: stdout.split("\n").filter(Boolean).map((l) => JSON.parse(l)) })); + }); + const ok = await run({ WORKER_TOKEN: TOKEN }); + assert.equal(ok.code, 0, JSON.stringify(ok.events)); + assert.deepEqual(ok.events.filter((e) => e.ev === "narrate").map((e) => e.id), ["k1"]); + assert.equal(ok.events.at(-1).ev, "done"); + assert.equal(ok.events.at(-1).narrations, 1); + assert.ok(existsSync(path.join(root, "out", "narration"))); + const none = await run({ WORKER_TOKEN: "" }); + assert.equal(none.code, 1); + assert.ok(none.events.some((e) => e.ev === "error" && /WORKER_TOKEN is not set/.test(e.message))); + // A manifest the build would refuse is never sent. + writeFileSync(manifest, JSON.stringify(MANIFEST([{ ...NARRATED, narration: { text: "<whisper> hi" } }]))); + const bad = await run({ WORKER_TOKEN: TOKEN }); + assert.equal(bad.code, 1); + assert.ok(bad.events.some((e) => e.ev === "error" && /<whisper>/.test(e.message))); + assert.equal(ed.asks.length, 1); +}); + +test("the encode args: a plain card keeps anullsrc; a narrated one reads the WAV through the narration filter", () => { + const plain = cardEncodeArgs({ png: "/c.png", seconds: 4, vf: "fps=30,setsar=1", render: { fps: 30, audioRate: 48000, audioChannels: 2 }, outPath: "/s.mp4" }); + assert.deepEqual(plain.slice(0, 17), [ + "-nostdin", "-v", "error", "-y", "-loop", "1", "-framerate", "30", "-t", "4", "-i", "/c.png", + "-f", "lavfi", "-t", "4", "-i", + ]); + assert.equal(plain[17], "anullsrc=channel_layout=stereo:sample_rate=48000"); + assert.equal(plain.at(-2), "-shortest"); + const narrated = narratedCardEncodeArgs({ png: "/c.png", wav: "/n.wav", seconds: 4.9, vf: "fps=30,setsar=1", audio: "AUDIO", render: { fps: 30, audioRate: 48000, audioChannels: 2 }, outPath: "/s.mp4" }); + assert.ok(!narrated.some((a) => /anullsrc/.test(a))); + assert.deepEqual(narrated.slice(narrated.indexOf("/n.wav") - 1, narrated.indexOf("/n.wav") + 5), ["-i", "/n.wav", "-map", "0:v", "-map", "1:a"]); + assert.equal(narrated[narrated.indexOf("-af") + 1], "AUDIO"); +}); + +test("a build: the narrated card's sound is the voice, \"auto\" its length, rebuilt only on change; the plain card is silence; the cut discloses", { skip: (!haveFf || !haveMagick) && "needs ffmpeg, ffprobe and ImageMagick" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-build-")); + const ed = await fakeEditor(root); + t.after(async () => { + await ed.close(); + rmSync(root, { recursive: true, force: true }); + }); + const proj = path.join(root, "proj"); + mkdirSync(proj); + const manifestPath = path.join(proj, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify(MANIFEST([PLAIN, NARRATED]))); + const opts = { editor: { url: ed.url, token: TOKEN }, narrationPollMs: 5, noXfade: true }; + const segs = path.join(proj, "out", "sourced", "segments"); + + // The whole cut, hard cuts: the build asks the editor itself. + const first = await quietly(() => buildVideo({ manifestPath, opts })); + assert.ok(!first.result?.err, String(first.result?.err?.stack)); + assert.equal(ed.asks.length, 1); + const rec = JSON.parse(readFileSync(path.join(segs, "k1.narration.json"), "utf8")); + // 2.45 s of voice + 0.8 + 0.8 -> 4.1 s, to the tenth. + assert.equal(rec.seconds, 4.1); + const dur = Number(probe(path.join(segs, "k1.mp4"), "format=duration").format.duration); + assert.ok(Math.abs(dur - 4.1) < 0.12, `k1 is ${dur}s`); + assert.ok(maxVolume(path.join(segs, "k1.mp4")) > -30, "the narrated card speaks"); + assert.equal(maxVolume(path.join(segs, "k0.mp4")), -91, "a card without narration is digital silence (anullsrc)"); + const tags = probe(path.join(proj, "out", "narrated.mp4"), "format_tags=comment").format.tags ?? {}; + assert.equal(tags.comment, "Narration: synthetic voice (kokoro · af_heart)"); + + // Again, unchanged: no ask, no encode. + const before = statSync(path.join(segs, "k1.mp4")).mtimeMs; + const second = await quietly(() => buildVideo({ manifestPath, opts: { ...opts }, only: "k1" })); + assert.ok(!second.result?.err, String(second.result?.err?.message)); + assert.equal(ed.asks.length, 1); + assert.ok(second.events.some((e) => e.ev === "note" && /k1: narrated card unchanged/.test(e.message))); + assert.equal(statSync(path.join(segs, "k1.mp4")).mtimeMs, before); + + // New words: a new ask and a new segment. + writeFileSync(manifestPath, JSON.stringify(MANIFEST([PLAIN, { ...NARRATED, narration: { text: "Six months later, the county said yes, twice over." } }]))); + const third = await quietly(() => buildVideo({ manifestPath, opts, only: "k1" })); + assert.ok(!third.result?.err, String(third.result?.err?.message)); + assert.equal(ed.asks.length, 2); + assert.notEqual(statSync(path.join(segs, "k1.mp4")).mtimeMs, before); + + // --skip-fetch never asks: a narration not kept refuses, naming the card. + writeFileSync(manifestPath, JSON.stringify(MANIFEST([{ ...NARRATED, narration: { text: "Words nobody asked for yet." } }]))); + const fourth = await quietly(() => buildVideo({ manifestPath, opts: { ...opts, skipFetch: true }, only: "k1" })); + assert.match(String(fourth.result?.err?.message), /k1: its narration has not been synthesized — run narrate-via-editor\.mjs/); + assert.equal(ed.asks.length, 2); + + // An authored seconds too short for the words is refused before anything renders. + writeFileSync(manifestPath, JSON.stringify(MANIFEST([{ ...NARRATED, seconds: 2 }]))); + const fifth = await quietly(() => buildVideo({ manifestPath, opts, only: "k1" })); + assert.match(String(fifth.result?.err?.message), /lint: timeline k1: seconds is 2, and its narration needs 4\.1s/); +}); diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs @@ -0,0 +1,131 @@ +// Where a cut's synthesized narration is kept: `out/narration/`, beside the +// build, shared by its variants (a narration is named by its content, not by +// the cut that asked for it). +// +// out/narration/<key>.wav the editor's sound, copied in (48 kHz mono PCM) +// out/narration/<key>.json its record: the words, engine, voice and speed it +// was asked with, its measured seconds and loudness, +// the copy's sha256, the editor job it came from, +// and the disclosure line +// +// `<key>` is narration.mjs's narrationKey: a changed word, voice or speed is a +// new file and a new ask; an unchanged one is never asked again. A COPY, not +// the editor's path: the editor's cache may be pruned or moved, and a rebuild +// must not depend on it. +import { createHash } from "node:crypto"; +import { execFile } from "node:child_process"; +import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; + +import { narrationDisclosure } from "./narration.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; + +/** `<outRoot>/narration`. */ +export const narrationDir = (outRoot) => path.join(outRoot, "narration"); +export const narrationWavPath = (dir, key) => path.join(dir, `${key}.wav`); +export const narrationRecordPath = (dir, key) => path.join(dir, `${key}.json`); + +/** One narration's record, or null when it was never kept (or its sound is gone). */ +export async function readNarrationRecord(dir, key) { + const rec = await readFile(narrationRecordPath(dir, key), "utf8").then(JSON.parse, () => null); + if (!rec || rec.key !== key) return null; + const st = await stat(narrationWavPath(dir, key)).catch(() => null); + return st?.isFile() && st.size > 0 ? rec : null; +} + +/** The records a list of narrations (narrationsOf) already has, by card id. */ +export async function readNarrationRecords(dir, narrations) { + const out = new Map(); + for (const n of narrations) { + const rec = await readNarrationRecord(dir, n.key); + if (rec) out.set(n.id, rec); + } + return out; +} + +/** A file's duration in seconds, by ffprobe. */ +export async function probeSeconds(file) { + const { stdout } = await execFileP(FFPROBE(), [ + "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file, + ]); + const s = Number(stdout.trim()); + if (!Number.isFinite(s) || s <= 0) throw new Error(`ffprobe reads no duration from ${file}`); + return s; +} + +/** A sound's integrated loudness (EBU R128, LUFS), by ffmpeg's ebur128; null when it has none (silence). */ +export async function measureLufs(file) { + const { stderr } = await execFileP( + FFMPEG(), + ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], + { maxBuffer: 1 << 24 }, + ); + // The summary's "I:" is the last one printed. + const all = [...String(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; +} + +const sha256File = async (file) => createHash("sha256").update(await readFile(file)).digest("hex"); + +/** + * Keep one synthesized narration: copy the editor's WAV in (through a rename, + * so a half-copied file is never read as kept), measure it, write its record. + * + * @param {string} dir narrationDir(outRoot) + * @param {{ id: string, key: string, text: string, engine: string, voice: string, speed: number }} n + * @param {{ wav: string, seconds?: number, engine?: string, voice?: string, cached?: boolean, + * durationMs?: number, waitedMs?: number }} result the editor's `@@tts-result` + * @param {{ jobId?: string }} [meta] + * @returns the record + */ +export async function keepNarration(dir, n, result, { jobId = null } = {}) { + if (!result || typeof result.wav !== "string" || !path.isAbsolute(result.wav)) { + throw new Error(`${n.id}: the editor's tts result names no absolute wav (${JSON.stringify(result?.wav)})`); + } + await mkdir(dir, { recursive: true }); + const wav = narrationWavPath(dir, n.key); + const tmp = path.join(dir, `.${n.key}.${process.pid}.tmp.wav`); + try { + await copyFile(result.wav, tmp); + await rename(tmp, wav); + } finally { + await rm(tmp, { force: true }); + } + const seconds = await probeSeconds(wav); + const lufs = await measureLufs(wav); + // The engine and voice the editor says it used: the ones asked for, which + // the disclosure names. + const engine = result.engine ?? n.engine; + const voice = result.voice ?? n.voice; + const record = { + v: 1, + key: n.key, + id: n.id, + text: n.text, + engine, + voice, + speed: n.speed, + seconds: Number(seconds.toFixed(3)), + lufs: lufs === null ? null : Number(lufs.toFixed(2)), + sha256: await sha256File(wav), + wav: path.basename(wav), + editor: { + jobId, + cached: result.cached === true, + ...(Number.isFinite(Number(result.seconds)) ? { seconds: Number(result.seconds) } : {}), + ...(Number.isFinite(Number(result.durationMs)) ? { durationMs: Number(result.durationMs) } : {}), + ...(Number.isFinite(Number(result.waitedMs)) ? { waitedMs: Number(result.waitedMs) } : {}), + }, + disclosure: narrationDisclosure({ timeline: [{ type: "card", id: n.id, narration: { text: n.text, engine, voice } }] }), + createdAt: new Date().toISOString(), + }; + const recTmp = path.join(dir, `.${n.key}.${process.pid}.tmp.json`); + await writeFile(recTmp, JSON.stringify(record, null, 2) + "\n", "utf8"); + await rename(recTmp, narrationRecordPath(dir, n.key)); + return record; +} diff --git a/umtool/report-to-video/narration.mjs b/umtool/report-to-video/narration.mjs @@ -0,0 +1,320 @@ +// Narration on cards: a card's `narration` spoken by a stock synthetic voice +// (release 25, T2). Opt-in and explicit -- the words are the author's, never +// derived from the card -- so a manifest without it builds exactly as it did: +// a card's sound stays `anullsrc`. +// +// { "type": "card", "id": "ch2", "seconds": "auto", "heading": "…", +// "narration": { "text": "Six months later, the county said yes.", "voice": "af_heart" } } +// +// "render": { "narration": { "engine": "kokoro", "voice": "af_heart", "speed": 1, +// "lufs": -17.7, "lead": 0.8, "tail": 0.8 } } +// +// The voice is synthesized by the EDITOR (`pnpm ops tts`, the `tts-file` job), +// never here: narrate-via-editor.mjs asks for it and keeps a copy beside the +// build (narration-store.mjs). This file is the pure part -- the validator the +// build AND the lint run, the resolved settings, the card's length, the sound's +// filter and the disclosure line -- shared by the build, the lint, the deck's +// estimate and the exports. No ffmpeg, no fs, no network. +import { createHash } from "node:crypto"; + +/** The engines a manifest may name (`orpheus` is refused by the editor until it lands there). */ +export const NARRATION_ENGINES = Object.freeze(["kokoro", "orpheus", "espeak-ng"]); + +/** + * Every `render.narration` setting and its default. The engine and voice are + * the ruled ones (Kokoro-82M, `af_heart`); they are SENT on every ask, so a + * change of the editor's own default never changes a cut that did not ask for it. + * `lufs` sits a narrated card with the clips (README, "the teaser level": the + * ferret cut measures −17.7 LUFS integrated). `lead`/`tail` are the quiet before + * and after the words, each at least the crossfade, so no word plays under a + * dissolve. + */ +export const NARRATION_DEFAULTS = Object.freeze({ + engine: "kokoro", + voice: "af_heart", + speed: 1, + lufs: -17.7, + lead: 0.8, + tail: 0.8, +}); + +/** The limits each setting is checked against. */ +export const NARRATION_LIMITS = Object.freeze({ + speed: [0.5, 2], + lufs: [-30, -10], + lead: [0, 5], + tail: [0, 5], + // Words, counted without the expressive tags: a card's narration is a few + // sentences; past this it is a script, which belongs in clips or a podcast. + words: 300, +}); + +/** + * The expressive tags a narration may carry: Orpheus speaks them; Kokoro has + * none, and the editor strips them before it synthesizes. Any other `<…>` is + * refused, by name. + */ +export const NARRATION_TAGS = Object.freeze(["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]); + +const RENDER_KEYS = new Set(Object.keys(NARRATION_DEFAULTS)); +const CARD_KEYS = new Set(["text", "voice", "engine"]); +// A stock voice's id: `af_heart`, `bm_george`, `en-us` (espeak-ng). Never a path. +const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; +const TAG_RE = /<([^<>]*)>/g; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const numIn = (v, [lo, hi]) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; + +/** The text without its expressive tags, whitespace collapsed. */ +export const stripNarrationTags = (text) => String(text ?? "").replace(TAG_RE, " ").replace(/\s+/g, " ").trim(); + +/** Words in a narration, its tags not counted. */ +export function narrationWords(text) { + const plain = stripNarrationTags(text); + return plain ? plain.split(" ").filter((w) => /[\p{L}\p{N}]/u.test(w)).length : 0; +} + +/** Does this entry carry a narration (a card's, the only kind that may)? */ +export const hasNarration = (entry) => entry?.type === "card" && isObj(entry.narration); + +/** `render.narration` with every default filled in. */ +export function resolveNarrationRender(render) { + const r = isObj(render?.narration) ? render.narration : {}; + return { ...NARRATION_DEFAULTS, ...Object.fromEntries(Object.entries(r).filter(([, v]) => v !== undefined && v !== null)) }; +} + +/** + * One card's narration as it is asked for: its text (trimmed), and the engine, + * voice and speed it is spoken with -- the card's own, else the manifest's, + * else the defaults. Null for an entry without one. + */ +export function resolveNarration(entry, render) { + if (!hasNarration(entry)) return null; + const r = resolveNarrationRender(render); + const n = entry.narration; + return { + text: String(n.text ?? "").trim(), + engine: n.engine ?? r.engine, + voice: n.voice ?? r.voice, + speed: r.speed, + }; +} + +/** + * The content key of one narration: what the synthesized sound depends on. + * The record and its copy of the sound are named by it, so a changed word, a + * different voice or speed is a new ask and the old one is never reused. + */ +export function narrationKey({ text, engine, voice, speed }) { + return createHash("sha256") + .update(JSON.stringify({ v: 1, text: String(text), engine, voice, speed: Number(speed) })) + .digest("hex"); +} + +/** Every narration a cut asks for, by card id, in timeline order: `[{ id, ...resolveNarration, key }]`. */ +export function narrationsOf(manifest) { + const out = []; + for (const e of manifest?.timeline ?? []) { + const n = resolveNarration(e, manifest.render); + if (n) out.push({ id: e.id, ...n, key: narrationKey(n) }); + } + return out; +} + +/** The problems with one narration's text, as sentences (no `where`). */ +function textProblems(text) { + const out = []; + if (typeof text !== "string" || !text.trim()) return ["text must be non-empty words"]; + for (const m of text.matchAll(TAG_RE)) { + const tag = m[1].trim().toLowerCase(); + if (!NARRATION_TAGS.includes(tag)) { + out.push(`the tag <${m[1]}> is not one of ${NARRATION_TAGS.map((t) => `<${t}>`).join(" ")}`); + } + } + const words = narrationWords(text); + if (words === 0) out.push("text has no words outside its tags"); + if (words > NARRATION_LIMITS.words) out.push(`text is ${words} words; at most ${NARRATION_LIMITS.words} (tags not counted)`); + return out; +} + +const engineProblem = (v) => + NARRATION_ENGINES.includes(v) ? null : `engine must be one of ${NARRATION_ENGINES.join(", ")} (got ${JSON.stringify(v)})`; +const voiceProblem = (v) => + typeof v === "string" && VOICE_RE.test(v) ? null : `voice must be a stock voice's id, e.g. "af_heart" (got ${JSON.stringify(v)})`; + +/** + * The manifest's narration, checked: `render.narration` and every timeline + * entry's `narration` and `seconds: "auto"`. The ONE validator -- the build + * runs it before a single fetch, the lint reports it -- over the WHOLE + * manifest (every variant's entries). Returns sentences; empty is valid. + */ +export function validateNarration(whole) { + const errors = []; + const render = whole?.render ?? {}; + const D = Number(render.transition ?? 0.5) || 0; + const rn = render.narration; + if (rn !== undefined && rn !== null) { + if (!isObj(rn)) { + errors.push("render.narration must be an object"); + } else { + for (const k of Object.keys(rn)) { + if (!RENDER_KEYS.has(k)) errors.push(`render.narration.${k} is not a setting (${[...RENDER_KEYS].join(", ")})`); + } + if (rn.engine !== undefined) { + const p = engineProblem(rn.engine); + if (p) errors.push(`render.narration.${p}`); + } + if (rn.voice !== undefined) { + const p = voiceProblem(rn.voice); + if (p) errors.push(`render.narration.${p}`); + } + for (const k of ["speed", "lufs", "lead", "tail"]) { + if (rn[k] !== undefined && !numIn(rn[k], NARRATION_LIMITS[k])) { + errors.push(`render.narration.${k} must be a number from ${NARRATION_LIMITS[k][0]} to ${NARRATION_LIMITS[k][1]} (got ${JSON.stringify(rn[k])})`); + } + } + for (const k of ["lead", "tail"]) { + const v = rn[k] ?? NARRATION_DEFAULTS[k]; + if (typeof v === "number" && v < D - 1e-9) { + errors.push(`render.narration.${k} is ${v}s, shorter than the ${D}s crossfade: the words would play under the dissolve`); + } + } + } + } else { + for (const k of ["lead", "tail"]) { + if (NARRATION_DEFAULTS[k] < D - 1e-9 && (whole?.timeline ?? []).some(hasNarration)) { + errors.push(`render.narration.${k} (default ${NARRATION_DEFAULTS[k]}s) is shorter than the ${D}s crossfade: set it to at least ${D}`); + } + } + } + + for (const [i, e] of (whole?.timeline ?? []).entries()) { + if (!e) continue; + const where = `timeline[${i}] ${e.id ?? "?"}`; + if (e.narration !== undefined && e.narration !== null) { + if (e.type !== "card") { + errors.push(`${where}: narration is on cards only (this is a ${e.type ?? "typeless"} entry)`); + continue; + } + if (!isObj(e.narration)) { + errors.push(`${where}.narration must be an object { text, voice?, engine? }`); + continue; + } + for (const k of Object.keys(e.narration)) { + if (!CARD_KEYS.has(k)) errors.push(`${where}.narration.${k} is not a key (${[...CARD_KEYS].join(", ")})`); + } + for (const p of textProblems(e.narration.text)) errors.push(`${where}.narration: ${p}`); + if (e.narration.engine !== undefined) { + const p = engineProblem(e.narration.engine); + if (p) errors.push(`${where}.narration.${p}`); + } + if (e.narration.voice !== undefined) { + const p = voiceProblem(e.narration.voice); + if (p) errors.push(`${where}.narration.${p}`); + } + } + if (e.seconds === "auto" && !hasNarration(e)) { + errors.push(`${where}: seconds "auto" is the narration's length, and this entry has no narration`); + } else if (hasNarration(e) && e.seconds !== "auto" && e.seconds !== undefined && !(typeof e.seconds === "number" && e.seconds > 0)) { + errors.push(`${where}.seconds must be a number of seconds or "auto" (got ${JSON.stringify(e.seconds)})`); + } + } + return errors; +} + +/** Seconds rounded UP to the tenth, as a teaser's are. */ +const upTenth = (s) => Math.ceil(s * 10 - 1e-6) / 10; + +/** + * The seconds a narrated card needs: the quiet before the words, the words, the + * quiet after, rounded up to the tenth. What `seconds: "auto"` becomes. + */ +export function narratedCardSeconds(narrationSeconds, render) { + const r = resolveNarrationRender(render); + return upTenth(Number(narrationSeconds) + r.lead + r.tail); +} + +/** + * A narrated card's length in the cut, once its narration's length is known: + * `"auto"` (or no `seconds`) is narratedCardSeconds; a number is itself. + * Returns `{ seconds, need, short }` -- `short` when an authored number is less + * than the words need, which the lint refuses. + */ +export function cardNarrationSeconds(entry, narrationSeconds, render) { + const need = narratedCardSeconds(narrationSeconds, render); + if (typeof entry?.seconds === "number") return { seconds: entry.seconds, need, short: entry.seconds < need - 1e-9 }; + return { seconds: need, need, short: false }; +} + +/** + * Before the voice exists: an estimate of a narration's seconds from its words + * (a brisk stock voice speaks about 2.7 words a second at speed 1). For the + * deck's estimated schedule and nothing else -- a build measures. + */ +export function estimateNarrationSeconds(text, speed = 1) { + return narrationWords(text) / (2.7 * (Number(speed) || 1)); +} + +/** A narrated card's estimated length (seconds "auto" before any build). */ +export function estimatedNarratedCardSeconds(entry, render) { + const n = resolveNarration(entry, render); + if (!n) return Number(entry?.seconds ?? 5); + if (typeof entry.seconds === "number") return entry.seconds; + return narratedCardSeconds(estimateNarrationSeconds(n.text, n.speed), render); +} + +/** 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 gain that brings a narration measured at `measuredLufs` to `targetLufs`, held to ±24 dB. */ +export function narrationGainDb(measuredLufs, targetLufs) { + // Unmeasured (silence reads as none): played as it came. + if (measuredLufs === null || measuredLufs === undefined || measuredLufs === "") return 0; + const m = Number(measuredLufs); + if (!Number.isFinite(m)) return 0; + return Math.max(-24, Math.min(24, Number(targetLufs) - m)); +} + +/** The ceiling the levelled voice is limited to: −1 dBFS. */ +export const NARRATION_LIMIT = 0.891251; + +/** + * The narrated card's sound, as one `-af` chain over the voice's WAV: at the + * segment's rate and layout, levelled by `gainDb` (narrationGainDb), held + * under −1 dBFS (no auto-level, latency compensated), delayed by `lead`, then + * padded and trimmed to exactly `seconds`. Deterministic: the string is part + * of the card's segment key. + */ +export function narrationAudioFilter({ seconds, lead, gainDb, render }) { + const layout = render.audioChannels === 1 ? "mono" : "stereo"; + const len = f6(seconds); + const ms = Math.round(Number(lead) * 1000); + return [ + `aresample=${render.audioRate}`, + `aformat=sample_fmts=fltp:channel_layouts=${layout}`, + `volume=${f6(gainDb)}dB`, + `alimiter=limit=${f6(NARRATION_LIMIT)}:level=0:latency=1:attack=5:release=50`, + `adelay=${ms}:all=1`, + `apad=whole_dur=${len}`, + `atrim=end=${len}`, + "asetpts=PTS-STARTPTS", + ].join(","); +} + +/** + * The disclosure a narrated output carries -- in its description and chapters + * export, its show notes, its file's metadata: + * "Narration: synthetic voice (kokoro · af_heart)". Each engine · voice pair + * used, in order, once. Null when nothing in the cut is narrated. + */ +export function narrationDisclosure(manifest) { + const pairs = []; + for (const n of narrationsOf(manifest)) { + const p = `${n.engine} · ${n.voice}`; + if (!pairs.includes(p)) pairs.push(p); + } + return pairs.length ? `Narration: synthetic voice (${pairs.join("; ")})` : null; +} diff --git a/umtool/report-to-video/narration.test.mjs b/umtool/report-to-video/narration.test.mjs @@ -0,0 +1,145 @@ +// narration.mjs: the validator (the build's and the lint's), the resolved +// settings, `seconds: "auto"`, the sound's filter, the key and the disclosure. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + NARRATION_DEFAULTS, NARRATION_TAGS, cardNarrationSeconds, estimatedNarratedCardSeconds, narratedCardSeconds, + narrationAudioFilter, narrationDisclosure, narrationGainDb, narrationKey, narrationWords, narrationsOf, + resolveNarration, stripNarrationTags, validateNarration, +} from "./narration.mjs"; +import { estimatedDuration } from "./deck.mjs"; +import { lintManifest, narrationLengthErrors } from "./lint.mjs"; + +const card = (extra = {}) => ({ type: "card", id: "k1", heading: "Then", seconds: "auto", narration: { text: "Six months later, the county said yes." }, ...extra }); +const M = (timeline, render = {}) => ({ render: { transition: 0.5, ...render }, timeline }); + +test("a valid narration, and a manifest without any, say nothing", () => { + assert.deepEqual(validateNarration(M([card()])), []); + assert.deepEqual(validateNarration(M([{ type: "card", id: "a", seconds: 4 }, { type: "clip", id: "c" }])), []); + assert.deepEqual(validateNarration(M([card()], { narration: { engine: "orpheus", voice: "tara", speed: 1.1, lufs: -16, lead: 1, tail: 0.5 } })), []); +}); + +test("the text: non-empty, the expressive tags only, words capped without the tags", () => { + const errs = (text) => validateNarration(M([card({ narration: { text } })])); + assert.match(errs(" ")[0], /k1\.narration: text must be non-empty words/); + assert.deepEqual(errs("Well <laugh> that went well <SIGH>."), []); + for (const t of NARRATION_TAGS) assert.deepEqual(errs(`Then <${t}> on.`), [], t); + const bad = errs("Then <whisper> on, and <b>this</b>."); + assert.equal(bad.length, 3, bad.join("\n")); + assert.match(bad[0], /the tag <whisper> is not one of <laugh> <chuckle>/); + assert.match(bad[1], /<b>/); + assert.match(bad[2], /<\/b>/); + assert.match(errs("<laugh> <sigh>")[0], /no words outside its tags/); + // 300 words pass, 301 do not -- the tags never count. + const words = (n) => Array.from({ length: n }, (_, i) => `w${i}`).join(" "); + assert.deepEqual(errs(`${words(300)} <laugh> <gasp>`), []); + assert.match(errs(words(301))[0], /301 words; at most 300 \(tags not counted\)/); + assert.equal(narrationWords("A <laugh> b, c — d!"), 4); + assert.equal(stripNarrationTags("A <laugh> b"), "A b"); +}); + +test("the keys, the engine, the voice, the settings and their bounds", () => { + const one = (narration, render) => validateNarration(M([card({ narration })], render)); + assert.match(one({ text: "Hi.", tone: "warm" })[0], /k1\.narration\.tone is not a key/); + assert.match(one({ text: "Hi.", engine: "piper" })[0], /engine must be one of kokoro, orpheus, espeak-ng/); + assert.match(one({ text: "Hi.", voice: "../ref.wav" })[0], /voice must be a stock voice's id/); + assert.deepEqual(one({ text: "Hi.", voice: "bm_george", engine: "kokoro" }), []); + assert.match(one({ text: "Hi." }, { narration: { speed: 3 } })[0], /render\.narration\.speed must be a number from 0\.5 to 2/); + assert.match(one({ text: "Hi." }, { narration: { lufs: -5 } })[0], /lufs must be a number from -30 to -10/); + assert.match(one({ text: "Hi." }, { narration: { reference: "x.wav" } })[0], /render\.narration\.reference is not a setting/); + assert.match(one({ text: "Hi." }, { narration: "loud" })[0], /render\.narration must be an object/); + // The lead and the tail at least the crossfade: no word under a dissolve. + const short = one({ text: "Hi." }, { transition: 1, narration: { lead: 0.5 } }); + assert.equal(short.length, 2, short.join("\n")); + assert.match(short[0], /render\.narration\.lead is 0\.5s, shorter than the 1s crossfade/); + assert.match(short[1], /render\.narration\.tail is 0\.8s, shorter than the 1s crossfade/); + assert.deepEqual(one({ text: "Hi." }, { transition: 0, narration: { lead: 0, tail: 0 } }), []); +}); + +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[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 })])), []); +}); + +test("resolved settings: the card's own, else the manifest's, else kokoro · af_heart", () => { + assert.deepEqual(resolveNarration(card(), {}), { text: "Six months later, the county said yes.", engine: "kokoro", voice: "af_heart", speed: 1 }); + assert.deepEqual( + resolveNarration(card({ narration: { text: " Hi. ", voice: "am_adam" } }), { narration: { voice: "bf_emma", speed: 0.9 } }), + { text: "Hi.", engine: "kokoro", voice: "am_adam", speed: 0.9 }, + ); + assert.equal(resolveNarration({ type: "card", id: "x" }, {}), null); + assert.equal(resolveNarration({ type: "clip", id: "x", narration: { text: "a" } }, {}), null); + assert.equal(NARRATION_DEFAULTS.lufs, -17.7); +}); + +test("the key moves with the words, the voice and the speed, and nothing else", () => { + const base = { text: "Hi.", engine: "kokoro", voice: "af_heart", speed: 1 }; + const k = narrationKey(base); + assert.match(k, /^[0-9a-f]{64}$/); + assert.equal(narrationKey({ ...base }), k); + for (const change of [{ text: "Hi!" }, { voice: "am_adam" }, { speed: 1.1 }, { engine: "orpheus" }]) { + assert.notEqual(narrationKey({ ...base, ...change }), k, JSON.stringify(change)); + } + const list = narrationsOf(M([card(), { type: "card", id: "plain", seconds: 3 }, card({ id: "k2" })])); + assert.deepEqual(list.map((n) => n.id), ["k1", "k2"]); + assert.equal(list[0].key, list[1].key, "the same words, voice and speed are one sound"); +}); + +test("seconds \"auto\": lead + words + tail, up to the tenth; a number is itself, and short when under", () => { + assert.equal(narratedCardSeconds(3.21, {}), 4.9); // 0.8 + 3.21 + 0.8 = 4.81 -> 4.9 + assert.equal(narratedCardSeconds(3.2, { narration: { lead: 1, tail: 1 } }), 5.2); + assert.deepEqual(cardNarrationSeconds(card(), 3.21, {}), { seconds: 4.9, need: 4.9, short: false }); + assert.deepEqual(cardNarrationSeconds(card({ seconds: 6 }), 3.21, {}), { seconds: 6, need: 4.9, short: false }); + assert.deepEqual(cardNarrationSeconds(card({ seconds: 4.5 }), 3.21, {}), { seconds: 4.5, need: 4.9, short: true }); +}); + +test("before a build, the deck estimates a narrated card from its words", () => { + // 7 words at 2.7 a second ≈ 2.59 s, plus 1.6 s of lead and tail -> 4.2. + assert.equal(estimatedNarratedCardSeconds(card(), {}), 4.2); + assert.equal(estimatedDuration(card(), { transition: 0.5 }), 4.2); + assert.equal(estimatedDuration(card({ seconds: 9 }), { transition: 0.5 }), 9); + assert.equal(estimatedDuration({ type: "card", id: "x", seconds: 3 }, {}), 3); +}); + +test("the sound's filter: rate, layout, level, limit, lead, exact length", () => { + const render = { audioRate: 48000, audioChannels: 2 }; + assert.equal( + narrationAudioFilter({ seconds: 4.9, lead: 0.8, gainDb: 2.25, render }), + "aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,volume=2.25dB," + + "alimiter=limit=0.891251:level=0:latency=1:attack=5:release=50,adelay=800:all=1," + + "apad=whole_dur=4.9,atrim=end=4.9,asetpts=PTS-STARTPTS", + ); + assert.match(narrationAudioFilter({ seconds: 3, lead: 0, gainDb: 0, render: { audioRate: 44100, audioChannels: 1 } }), /^aresample=44100,aformat=sample_fmts=fltp:channel_layouts=mono,volume=0dB,.*adelay=0:all=1/); + assert.equal(narrationGainDb(-21.2, -17.7), 3.5); + assert.equal(narrationGainDb(-60, -17.7), 24); + assert.equal(narrationGainDb(null, -17.7), 0); +}); + +test("the disclosure line: each engine · voice once, none without narration", () => { + assert.equal(narrationDisclosure(M([card()])), "Narration: synthetic voice (kokoro · af_heart)"); + assert.equal( + narrationDisclosure(M([card(), card({ id: "k2", narration: { text: "Two.", voice: "am_adam" } }), card({ id: "k3" })])), + "Narration: synthetic voice (kokoro · af_heart; kokoro · am_adam)", + ); + assert.equal(narrationDisclosure(M([{ type: "card", id: "a", seconds: 3 }])), null); +}); + +test("the lint: an authored seconds shorter than the narration is an ERROR; an unsynthesized one is a note", () => { + const m = M([card({ seconds: 3 }), card({ id: "k2" }), card({ id: "k3", seconds: 10 })]); + const errs = narrationLengthErrors(m, new Map([["k1", 3.21], ["k2", 3.21], ["k3", 3.21]])); + assert.equal(errs.length, 1); + assert.match(errs[0], /timeline k1: seconds is 3, and its narration needs 4\.9s \(3\.21s of words plus the lead and the tail\) — set "auto" or at least 4\.9/); + const lint = lintManifest(m, { narrationSeconds: new Map([["k1", 3.21]]) }); + assert.equal(lint.errors.filter((e) => /narration needs/.test(e)).length, 1); + assert.equal(lint.warnings.filter((w) => /not synthesized yet/.test(w)).length, 2); + // The validator speaks through the lint too. + const bad = lintManifest(M([card({ narration: { text: "a <whisper> b" } })])); + assert.ok(bad.errors.some((e) => /<whisper>/.test(e)), bad.errors.join("\n")); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -29,6 +29,7 @@ "./lint": "./lint.mjs", "./local-media": "./local-media.mjs", "./mute": "./mute.mjs", + "./narration": "./narration.mjs", "./package.json": "./package.json", "./post-links": "./post-links.mjs", "./prune-frames": "./prune-frames.mjs", diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs @@ -76,7 +76,8 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n n + (e.type === "clip" ? Math.max(0, (e.cutEnd ?? e.end ?? 0) - (e.cutStart ?? e.start ?? 0)) - : (e.seconds ?? 0)), + // A narrated card's "auto" is measured by the build: no floor from it here. + : (typeof e.seconds === "number" ? e.seconds : 0)), 0, ); if (wanted > 0 && duration < wanted * 0.5) {