Archilyzer · Source

archilyzer

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

commit 7747d3cfa66b2d9480f29e6388de53a3afc82877
parent 252c34fb52fbbe5ab15088f9511532685fa7a791
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 01:45:18 -0400

Merge r25/tts-video (release 25 T2 report-video narration, T3 podcast export) into r25/integration

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

Diffstat:
Meditor/CHANGELOG.md | 2++
Mplans/release-25.md | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/build/route.ts | 18++++++++++++++----
Aumtool/app/api/report/podcast/route.ts | 30++++++++++++++++++++++++++++++
Aumtool/components/projects/PodcastExport.tsx | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ReportProject.tsx | 16++++++++++++++++
Mumtool/docs/report-video.md | 22+++++++++++++++++++++-
Mumtool/e2e/fixtures/editor-stub.mjs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 14++++++++++++++
Aumtool/e2e/report-narration.spec.ts | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/busy.mjs | 2+-
Mumtool/lib/report/deliverables.test.mjs | 3+++
Mumtool/lib/report/driver.mjs | 34+++++++++++++++++++++++++++++++++-
Mumtool/lib/report/driver.test.mjs | 26++++++++++++++++++++++++++
Aumtool/lib/report/export-narration.test.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/export.mjs | 10+++++++++-
Mumtool/lib/report/serve.mjs | 37+++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/README.md | 119++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Aumtool/report-to-video/build-podcast.mjs | 446+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/build-podcast.test.mjs | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 219++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mumtool/report-to-video/deck.mjs | 3+++
Mumtool/report-to-video/lint.mjs | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/report-to-video/narrate-via-editor.mjs | 271+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narrate.test.mjs | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration-store.mjs | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration.mjs | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration.test.mjs | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 2++
Mumtool/report-to-video/verify-build.mjs | 3++-
30 files changed, 2851 insertions(+), 56 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -145,6 +145,8 @@ - **Different e2e suites run side by side, and `pnpm e2e:all` runs them all with one summary.** Each package's suite now waits only for another run of the SAME suite (`e2e-editor`, `e2e-export`, `e2e-homepage`, `e2e-umtool`), so the editor, export, homepage and umtool suites can run at once. `pnpm e2e:all` starts one per package, writes each suite's output to `test-results-e2e-all/`, and ends with one table — passed, failed, flaky and skipped per suite, how long each waited, every failed test by file and line — and the wall time against the sum of the suites' own. - **The heavy slot admits jobs by memory, one build at a time.** An e2e suite (1.5 GB) or a capped `next build` (its 5 GB cap) now starts beside other heavy work while the memory left after what the running jobs were promised stays above the 6000 MB floor; two `next build`s still never run at once. A job that declares no estimate — a render, a hand `pnpm heavy -- …`, a publish stage's build — runs alone, as before. A waiter is told what it waits for (`waiting for memory — … MB promised to 2 running jobs`, `waiting for the build slot`). - **The editor suite can run on several workers, each with servers of its own.** `E2E_WORKERS=2` (or `auto`, from memory, up to 3) gives every worker its own editor, export server and Ollama stub over its own data directory; specs that write into the checkout's build outputs or time a wall clock run afterwards on one worker. One worker stays the default until the parallel runs are measured. +- **A report video's cards can be narrated by a stock synthetic voice.** A card may carry `narration: {text, voice?, engine?}` — the author's words, never derived from the card — and `seconds: "auto"`, its words' length plus a lead and a tail; `render.narration` sets the engine and voice (Kokoro, `af_heart`, by default), speed, level (−17.7 LUFS, with the clips) and the quiet around the words. The voice is synthesized by the editor (`pnpm ops tts`), never by umtool: the build chain's new step, `narrate-via-editor.mjs`, asks for every narration not yet kept and keeps each in the project's `out/narration/`, and the build plays it under its card. A number of seconds shorter than the words need is a lint error. A narrated cut says "Narration: synthetic voice (Kokoro-82M · af_heart)" — the editor's own line — in its file's metadata and at the end of its description and chapters exports. Stock voices only; a manifest without narration builds exactly as before. +- **A report video can be exported as a podcast.** The project page's export row has a **podcast** button per cut (`build-podcast.mjs <manifest>` on the command line): the built cut as sound only — the clips, the narrated cards and the teasers' hits, each silent card left out (`render.podcast.skipSilentCards`) — levelled to −16 LUFS, as `out/<variant>/podcast.m4a` and `podcast.mp3` with the video's chapter titles at the podcast's own times, and `show-notes.md`: the chapters, every cited source's link and, for a narrated cut, the disclosure line. It is made from the segments of the last build, so build the cut first. ## [0.11.0] - 2026-09-30 - **Transcripts that arrived after a video was first seen are counted.** The stats behind the homepage, the hub and every site's charts were cached per video and refreshed only when the video's metadata changed, so a transcript that came later — a Whisper run days after the download, or a video downloaded after the last index build — never reached them, and a video with YouTube captions alone had no transcription date. Counts and charts were low; the homepage could show a site with 0 transcripts, 0 channels and 0 hours while it served its videos. A stat is now also redone whenever the index re-reads the video, every transcript has a date, and a captioned video is dated by when its captions arrived rather than by a later Normalize run, so its place on "Transcribed over time" can move. **After updating, rebuild and restart the editor before anything else:** until then, **Build stats dataset** runs the old code and would undo the new stats, while a site, hub or homepage build already runs the new code — and the first stats build of any kind re-reads every video once (about 10–30 minutes on a large archive; it can be stopped and picks up where it stopped). Then build the index, the stats, the homepage, the hub, and the sites. diff --git a/plans/release-25.md b/plans/release-25.md @@ -129,3 +129,94 @@ Not done here: the four `next build`s and `pnpm e2e:all` (the orchestrator's); n runs a real synthesis in-process). Found and left: a job's `done` settles when its log stream is ended, not flushed (`runManagedFunction`), so a near-instant job (a cache hit) can settle before its log is on disk — `pnpm ops --wait` polls over HTTP and does not see it; the unit tests poll for the marker. + +### T2, as shipped — report-video narration (`r25/tts-video`) + +A card may carry words spoken by a stock synthetic voice. Opt-in and explicit: the words are the author's, never +derived from the card, and a manifest without narration builds byte-for-byte as before. + +- **Manifest.** A `card`'s `narration: {text, voice?, engine?}` and `seconds: "auto"`; `render.narration {engine + (kokoro), voice (af_heart), speed (1, 0.5–2), lufs (−17.7, −30 to −10), lead (0.8), tail (0.8)}`. Engine + `kokoro | orpheus | espeak-ng` (the editor refuses `orpheus` until T1b); the engine and voice are always sent, so a + change of the editor's default never changes a cut that did not ask for it. +- **`validateNarration`** (`report-to-video/narration.mjs`, pure; the build before a single fetch, and the lint): + narration on cards only; text non-empty and at most 300 words, the tags not counted; the only `<…>` are the + expressive tags, lowercase and exact (the editor's rule; a case slip gets "did you mean <sigh>?"; a test holds the + list equal to `TTS_EXPRESSIVE_TAGS`); a stock voice's id, never a path; each setting in range; `lead`/`tail` at least + the crossfade; `seconds: "auto"` only beside a narration. +- **`narrate-via-editor.mjs`** asks `POST /api/ops/tts` `{text, engine, voice, speed}` once per distinct narration (a + key over words, engine, voice, speed), as one batch, follows each job on `GET /api/ops/job/<id>` (its queue place + said as it moves), reads the last `@@tts-result` line of its tail (re-read briefly when a done job's line is not on + disk yet), and COPIES the WAV into `out/narration/<key>.wav` beside `<key>.json`: the words, engine, voice, speed, + measured seconds and LUFS, the copy's sha256, the editor job, and the editor's `disclosure`, verbatim. `out` is + never sent. A narration kept is never asked again. The driver runs it as a step before the build when the manifest + carries narration (`options.narrate`, set by the build route); `busy.mjs` sees it. A build that finds one missing + asks itself; `--skip-fetch` refuses, naming the card. +- **The card's sound**: the WAV in place of `anullsrc` (`narratedCardEncodeArgs`, `narrationAudioFilter`): resampled + to `audioRate`/`audioChannels`, levelled from its measured loudness to `lufs` (±24 dB), limited at −1 dBFS, delayed + by `lead`, padded and trimmed to exactly the card's seconds. `cardEncodeArgs` is the un-narrated encode, argument for + argument as before. +- **`seconds: "auto"`** = lead + words + tail, up to the tenth, on the run's copy of the timeline. An authored number + shorter than that is a lint ERROR (`narrationLengthErrors`): the build refuses before it renders; `--lint` judges the + narrations already kept. The deck's estimate reckons 2.7 words a second (`estimatedDuration`); `verify-build`'s + length floor takes no number from "auto". +- **Rebuilt only on change**: `segments/<id>.narration.json` holds the key (the card as resolved, the render block, + the nodes, the framing, the narration's sha256, the sound's filter, the encode); a match leaves the segment, a + change writes a new file through a rename (a take's linked segment is never written through). + `SEGMENT_FILE_SUFFIXES` gains `.narration.json`. +- **Disclosure**: the editor's own lines from the kept records ("Narration: synthetic voice (Kokoro-82M · af_heart)"), + each once — in the cut's `comment` metadata (muxed with the chapters), and at the end of the `description` and + `chapters` exports (`readCutDisclosure`). A narration not kept says the line in the editor's form. +- README "Narration" (with "Writing narration": for the ear, the drama never outrunning the sources); docs + `report-video.md` "Narrated cards"; "Not done yet" now says narration is on cards only. + +| commit | what | +|---|---| +| `96bab418` | narrated cards: validator, narrate-via-editor, the store, the card encode, "auto", the record, driver step, disclosure, e2e stub + spec | +| `219f9967` | T1 as shipped: the editor's disclosure verbatim, exact tags (+ the `TTS_EXPRESSIVE_TAGS` test), a late result line re-read | + +### T3, as shipped — the podcast (`r25/tts-video`) + +`build-podcast.mjs <manifest> [--out] [--variant] [--progress ndjson]` renders the cut as sound only, **from its built +segments**, so it plays exactly what the video plays. Takes the heavy slot. + +- **The plan** (`podcastPlan`, pure): heard — each clip (its `muteFrom` honoured, `muteSegmentSeconds` as the join + does), each narrated card, each teaser with hits; left out — every entry with no sound of its own, or + `render.podcast.silence` seconds of quiet each with `skipSilentCards: false`. Holds, moves, dips and the end fade are + picture and are not in it. +- **The sound**: joined end to end with 10 ms edges, levelled in two `loudnorm` passes (linear) to −16 LUFS / −1.5 + dBTP; `podcast.m4a` (AAC 160k, faststart) and `podcast.mp3` (128k, ID3v2.3 chapters), each with the chapters — the + video's `chapters.ffmeta` titles at the podcast's own offsets — the title, and the disclosure as `comment`. +- **`show-notes.md`**: title, subtitle, length, the chapters with times, every cited source's link once (a heard + clip's by the QR's rule, a still's `citeUrl`, a post's `url`), the disclosure. **`podcast.json`**: the plan, each + item's seconds, what was left out, the measured loudness, the files. +- **Refusals**, naming each: a segment not built ("build the cut first — a fast build is enough"); a narrated card's + segment made from other words than the manifest's (its `.narration.json` key). `validatePodcast` (`render.podcast`: + `skipSilentCards, silence, lufs, truePeak, bitrate, mp3, mp3Bitrate`) runs in the render and the lint. +- **umtool**: the build route's `options.podcast` runs it alone (no preflight, no verify, no overwrite guard; job + `podcast <project>`); `GET /api/report/podcast?project&variant&file=m4a|mp3|notes` serves the three by name + (`podcastFor`, `PODCAST_FILES`); the project page's export row has a **podcast** button per cut + (`PodcastExport.tsx`), then links to the three files. + +| commit | what | +|---|---| +| `094b64fb` | build-podcast, validatePodcast, the route option, the file route, the export-row button, driver/busy, docs | +| `1f48aa9c` | a post's label without a nested template literal (`next-build-trace.test.mjs` misread it as running to the file's end) | + +#### Gates (T2 + T3) + +| gate | result | +|---|---| +| tsc (`pnpm -r … exec tsc --noEmit`) | clean at every commit | +| umtool unit (`report-to-video/*.test.mjs`, `lib/*.test.mjs`, `lib/report/*.test.mjs`) | 655: 653 pass, 2 skip (new: `narration.test.mjs` 12, `narrate.test.mjs` 6 — a fake editor, three real builds, `build-podcast.test.mjs` 6 — a real render, `export-narration.test.mjs` 1, `driver.test.mjs` +2, `deliverables.test.mjs` +2 asserts) | +| `pnpm run test:scripts` (after the T1 merge) | 825: 822 pass, 3 skip | +| un-narrated byte-identity | the same manifest (two cards, a still, hard cuts, chapters) built by `9d805472`'s and this branch's `build-video.mjs`: every segment and the final mp4 md5-identical | +| umtool e2e `report-narration.spec.ts` (new; start mode, at `219f9967`) | 3 passed (14.9 s): the chain's narration step, a fixture build voiced by the e2e editor stub's tone (one ask, the words, engine and voice on the wire; the card audible, "auto" 3.7 s; the plain card −91 dB; the exports' disclosure), the export row's podcast (files, 2 chapters, `left: ["k02"]`, served by name, a traversal name a 400) | +| umtool e2e `build.spec.ts onscreen.spec.ts` | 14 passed (35.9 s) | +| umtool capped `next build`, corpus linked (`pnpm heavy`, 5 GB cap) | compiled in 7.1 s, TypeScript 15.0 s; link removed | +| counts-only privacy greps over `9d805472..` (home paths, the operator's names and email, session links and trailers) | 0 each | + +Not done here: no real Kokoro synthesis through the live editor (the fake editor and the e2e stub stand in; T1's +gate ran one through the route), the editor/export/homepage builds and `pnpm e2e:all` (the orchestrator's). +**Found and left.** A podcast is made from the last build's segments: a clip re-cut since is heard as it was built +(only a narrated card's words are checked). Narration under clips, and a podcast's RSS enclosure (T4), are not built. diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -82,6 +82,8 @@ export async function POST(request: Request) { chaptersOnly?: boolean; chromeOnly?: boolean; preview?: { at: number; dur: number } | null; + narrate?: boolean; + podcast?: boolean; } = {}; if (raw.variant !== undefined && raw.variant !== "") { const v = String(raw.variant); @@ -105,9 +107,13 @@ export async function POST(request: Request) { } options.preview = { at, dur }; } - if ([options.chaptersOnly, options.chromeOnly, options.preview].filter(Boolean).length > 1) { + // The cut as sound only (build-podcast.mjs), from the segments on disk. It + // writes out/<variant>/podcast.*, never the deliverable, so the overwrite + // guard below does not apply. + if (raw.podcast) options.podcast = true; + if ([options.chaptersOnly, options.chromeOnly, options.preview, options.podcast].filter(Boolean).length > 1) { return Response.json( - { error: "chaptersOnly, chromeOnly and preview are different runs — pick one" }, + { error: "chaptersOnly, chromeOnly, preview and podcast are different runs — pick one" }, { status: 400 }, ); } @@ -121,6 +127,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 (!options.podcast && 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, @@ -150,7 +160,7 @@ export async function POST(request: Request) { // the same file in place by design, and a preview writes a different one, so // neither is guarded. const finalPath = variantPaths(path.join(project.dir, "out"), manifest.slug, options.variant ?? DEFAULT_VARIANT).final; - if (!only && !options.chaptersOnly && !options.chromeOnly && !options.preview) { + if (!only && !options.chaptersOnly && !options.chromeOnly && !options.preview && !options.podcast) { const [fin, man] = await Promise.all([ stat(finalPath).catch(() => null), stat(path.join(project.dir, "video.manifest.json")).catch(() => null), @@ -185,7 +195,7 @@ export async function POST(request: Request) { } try { - const job = startJob(`build ${project.id} (${preset})`, steps, { project: project.id }); + const job = startJob(options.podcast ? `podcast ${project.id}` : `build ${project.id} (${preset})`, steps, { project: project.id }); return Response.json({ ok: true, ...view, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); diff --git a/umtool/app/api/report/podcast/route.ts b/umtool/app/api/report/podcast/route.ts @@ -0,0 +1,30 @@ +import { PODCAST_FILES, podcastFor, rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; + +export const dynamic = "force-dynamic"; + +// A cut's podcast (build-podcast.mjs): ?project&variant&file=m4a|mp3|notes. +// Names, never paths: the file is out/<variant>/ under the pipeline's own +// variantPaths() for the manifest's slug. Rendered by the build route's +// `options.podcast` run; a 404 until then, said in words. +export async function GET(request: Request) { + const url = new URL(request.url); + const which = url.searchParams.get("file") ?? "m4a"; + if (!(which in PODCAST_FILES)) { + return new Response(`file must be one of ${Object.keys(PODCAST_FILES).join(", ")}`, { status: 400 }); + } + const r = await resolveReport(url.searchParams.get("project") ?? "", url.searchParams.get("variant")); + if ("error" in r) return new Response(r.error, { status: r.status }); + const f = await podcastFor(r.project, r.manifest, r.variant, which as keyof typeof PODCAST_FILES); + if (!f) return new Response("no podcast has been rendered for this cut yet", { status: 404 }); + return rangeResponse(request, { + abs: f.abs, + size: f.size, + headers: { + "content-type": f.type, + "accept-ranges": "bytes", + "cache-control": "private, no-store", + "content-disposition": `${url.searchParams.get("download") === "1" ? "attachment" : "inline"}; filename="${f.download}"`, + "x-podcast-mtime": String(f.mtimeMs), + }, + }); +} diff --git a/umtool/components/projects/PodcastExport.tsx b/umtool/components/projects/PodcastExport.tsx @@ -0,0 +1,104 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// The cut as SOUND ONLY, beside the video's exports (release 25, T3). +// +// "podcast" starts one build-route job with `options.podcast` -- build-podcast.mjs +// over the segments on disk -- and follows it by id; when it ends the page is +// refreshed, so the links below are the server's word on what is there, never +// a guess from here. A running build is a 409 that is shown, not swallowed; a +// cut with a segment missing fails with the pipeline's own sentence. + +type File = { size: number; mtimeMs: number } | null; + +export default function PodcastExport({ + project, + variant, + files, +}: { + project: string; + variant: string; + files: { m4a: File; mp3: File; notes: File }; +}) { + const router = useRouter(); + const [job, setJob] = useState<string | null>(null); + const [state, setState] = useState<"idle" | "busy" | "running" | "done" | "failed">("idle"); + const [msg, setMsg] = useState<string | null>(null); + + useEffect(() => { + if (!job) return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/build?job=${encodeURIComponent(job)}`, { cache: "no-store" }); + if (!r.ok) return; + const j = (await r.json()) as { state: string; error: string | null }; + if (j.state === "running") return; + clearInterval(t); + setJob(null); + setState(j.state === "done" ? "done" : "failed"); + setMsg(j.state === "done" ? null : j.error ?? "the podcast was not rendered"); + router.refresh(); + }, 700); + return () => clearInterval(t); + }, [job, router]); + + const href = (file: string, download = false) => + `/api/report/podcast?project=${encodeURIComponent(project)}&variant=${encodeURIComponent(variant)}&file=${file}` + + (download ? "&download=1" : "") + + // The mtime, so a re-render is a new URL and never a cached old one. + `&v=${(files as Record<string, File>)[file]?.mtimeMs ?? 0}`; + + return ( + <span className="flex flex-wrap items-center gap-1.5" data-podcast={variant} data-podcast-state={state}> + <button + type="button" + data-action="podcast" + disabled={state === "busy" || state === "running"} + title={`render the ${variant} cut as sound only: podcast.m4a, podcast.mp3 and show-notes.md, from the segments on disk`} + className={buttonVariants({ size: "sm" })} + onClick={async () => { + setState("busy"); + setMsg(null); + try { + const r = await fetch("/api/report/build", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, preset: "fast", options: { podcast: true, variant } }), + }); + const j = (await r.json()) as { error?: string; job?: { id: string } }; + if (!r.ok || !j.job) throw new Error(j.error ?? String(r.status)); + setJob(j.job.id); + setState("running"); + } catch (e) { + setState("failed"); + setMsg(e instanceof Error ? e.message : String(e)); + } + }} + > + {state === "running" || state === "busy" ? "rendering the podcast…" : files.m4a ? "re-render podcast" : "podcast"} + </button> + {files.m4a && ( + <a href={href("m4a", true)} data-podcast-file="m4a" className="font-mono text-[var(--color-sel)] hover:underline"> + podcast.m4a + </a> + )} + {files.mp3 && ( + <a href={href("mp3", true)} data-podcast-file="mp3" className="font-mono text-[var(--color-sel)] hover:underline"> + podcast.mp3 + </a> + )} + {files.notes && ( + <a href={href("notes")} target="_blank" rel="noreferrer" data-podcast-file="notes" className="font-mono text-[var(--color-sel)] hover:underline"> + show-notes.md + </a> + )} + {msg && ( + <span data-podcast-error="" className="text-[var(--color-bad)]"> + {msg} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -18,9 +18,11 @@ import { EXPORT_FORMATS, exportableVariants } from "@/lib/report/export.mjs"; import { diffManifests, formatChange } from "@/lib/report/manifest-diff.mjs"; import { listSnapshots, readSnapshot } from "@/lib/report/snapshots.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; +import { podcastFor } from "@/lib/report/serve.mjs"; import DeliverSection from "./DeliverSection"; import FetchUnfetchedButton from "./FetchUnfetchedButton"; import OnscreenSection from "./OnscreenSection"; +import PodcastExport from "./PodcastExport"; import ReportBuildChain from "./ReportBuildChain"; import SnapshotButton from "./SnapshotButton"; import TagCitedButton from "./TagCitedButton"; @@ -131,6 +133,15 @@ export default async function ReportProject({ const noteFiles = names.filter((n) => /\.md$/i.test(n) && !/^readme\.md$/i.test(n) && n !== "sweep-report.md").sort(); const noteTexts = await Promise.all(noteFiles.map((n) => readFile(path.join(project.dir, n), "utf8").catch(() => ""))); const variants = await exportableVariants(project.dir); + // Each exportable cut's podcast files, as they are on disk (build-podcast.mjs). + const podcastOf = async (v: string) => { + const f = async (which: "m4a" | "mp3" | "notes") => { + const got = await podcastFor(project, m, v, which); + return got ? { size: got.size, mtimeMs: got.mtimeMs } : null; + }; + return { m4a: await f("m4a"), mp3: await f("mp3"), notes: await f("notes") }; + }; + const podcasts = new Map(await Promise.all(variants.map(async (v) => [v, await podcastOf(v)] as const))); const takes = await listTakes(project.dir); // Provenance splits by SHAPE: a scalar or a URL stays in the table; a long @@ -733,6 +744,11 @@ export default async function ReportProject({ url={`/api/report/export?project=${encodeURIComponent(project.id)}&format=${f}&variant=${v}`} /> ))} + <PodcastExport + project={project.id} + variant={v} + files={podcasts.get(v) ?? { m4a: null, mp3: null, notes: null }} + /> </div> )) )} diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -779,7 +779,27 @@ 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 editor's disclosure line, `Narration: synthetic voice (Kokoro-82M · af_heart)`. + +**podcast** (one button per cut in the same row) is a build-route run with +`options.podcast`: `build-podcast.mjs` renders the built cut as sound only — +`out/<variant>/podcast.m4a`, `podcast.mp3`, `show-notes.md` — and the row then +links the three, served by name through `GET /api/report/podcast?project&variant&file=m4a|mp3|notes`. +It needs the cut's segments on disk; the README's "The podcast" has the rules. + +## 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,66 @@ 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, + sha: id, sampleRate: 48000, speed: body.speed ?? 1, + // The editor's own line, which umtool uses verbatim. + disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice ?? "af_heart"})`, + }, + }); + 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,141 @@ +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-82M · 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); +}); + +// --------------------------------------------------------------------------- +// The podcast (release 25, T3): the export row's "podcast" renders the built +// cut as sound only -- the narrated card's voice and the clip, the plain card +// left out -- and offers the files. Runs on the build above. +// --------------------------------------------------------------------------- + +test("the export row renders the cut as a podcast and offers the files", async ({ page, request }) => { + await page.goto("/browse/reports/narration-fixture"); + const row = page.locator('[data-export-variant="sourced"]'); + const podcast = row.locator('[data-podcast="sourced"]'); + await expect(podcast.getByRole("button", { name: "podcast" })).toBeVisible(); + await expect(podcast.locator("[data-podcast-file]")).toHaveCount(0); + + await podcast.getByRole("button", { name: "podcast" }).click(); + await expect(podcast.locator('[data-podcast-file="m4a"]')).toBeVisible({ timeout: 120_000 }); + await expect(podcast.locator('[data-podcast-file="mp3"]')).toBeVisible(); + await expect(podcast.locator('[data-podcast-file="notes"]')).toBeVisible(); + await expect(podcast.getByRole("button", { name: "re-render podcast" })).toBeVisible(); + + // The m4a: the narrated card and the clip, the silent card left out, with chapters. + const m4a = path.join(OUT, "sourced", "podcast.m4a"); + const info = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_chapters", "-show_entries", "format=duration:format_tags=comment", "-of", "json", m4a]).toString()) as { + chapters: { tags: { title: string } }[]; format: { duration: string; tags?: Record<string, string> }; + }; + expect(info.chapters).toHaveLength(2); + expect(info.format.tags?.comment).toBe(DISCLOSURE); + const rec = JSON.parse(readFileSync(path.join(OUT, "sourced", "podcast.json"), "utf8")) as { left: string[] }; + expect(rec.left).toEqual(["k02"]); + + // Served by name, never by path. + const got = await request.get(`/api/report/podcast?project=${encodeURIComponent(PROJECT)}&variant=sourced&file=m4a`); + expect(got.status()).toBe(200); + expect(got.headers()["content-type"]).toBe("audio/mp4"); + const notes = await (await request.get(`/api/report/podcast?project=${encodeURIComponent(PROJECT)}&variant=sourced&file=notes`)).text(); + expect(notes).toContain("## Chapters"); + expect(notes).toContain("https://archive.example/?v=testchan%2Fvid1&t=9"); + expect(notes).toContain(DISCLOSURE); + expect((await request.get(`/api/report/podcast?project=${encodeURIComponent(PROJECT)}&variant=sourced&file=../../x`)).status()).toBe(400); +}); 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|build-podcast|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,9 @@ 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); + assert.equal(namesProject(["node", "build-podcast.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,17 @@ 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. + * + * podcast `build-podcast.mjs` alone (release 25, T3): the cut as sound + * only, from the segments on disk -- out/<variant>/podcast.m4a, + * podcast.mp3 and show-notes.md. No preflight, no build, no + * verify: it refuses by itself when a segment is missing. + * + * @typedef {{ variant?: string, xfade?: boolean, chaptersOnly?: boolean, chromeOnly?: boolean, preview?: { at: number, dur: number } | null, narrate?: boolean, podcast?: boolean }} BuildOptions */ /** The step-1 preflight alone, reused by the check-sources job. */ @@ -88,6 +98,13 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch = const base = { cwd: PIPELINE_DIR, env }; const quick = !!(options.chaptersOnly || options.preview); + // The podcast: one step, over the segments already built. + if (options.podcast) { + const argv = ["node", script("build-podcast.mjs"), manifest, "--out", outDir, "--progress", "ndjson"]; + if (options.variant) argv.push("--variant", options.variant); + return [{ ...base, label: "render the podcast (sound only)", argv, ndjson: true, timeoutMs: 15 * 60_000 }]; + } + const steps = quick || options.chromeOnly ? [] : [ @@ -105,6 +122,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,29 @@ 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)); + } +}); + +test("podcast: one step, build-podcast over the segments on disk, told the cut", () => { + const steps = buildSteps(project, { preset: "final", options: { podcast: true, variant: "full", narrate: true } }); + assert.equal(steps.length, 1); + assert.equal(steps[0].label, "render the podcast (sound only)"); + assert.ok(steps[0].argv[1].endsWith("build-podcast.mjs")); + assert.deepEqual(steps[0].argv.slice(2), ["/r/p/video.manifest.json", "--out", "/r/p/out", "--progress", "ndjson", "--variant", "full"]); + assert.equal(steps[0].ndjson, true); +}); 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-82M · 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 { narrationDir, readCutDisclosure } from "umtool-report-to-video/narration-store"; import { outDirState } from "./storage.mjs"; export const EXPORT_FORMATS = ["toc-bbcode", "toc-markdown", "description", "chapters"]; @@ -156,6 +157,9 @@ 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"); + // The editor's own line for each voice the cut's narration kept + // ("Narration: synthetic voice (Kokoro-82M · af_heart)"), or null for a cut with none. + const disclosure = await readCutDisclosure(narrationDir(path.join(dir, "out")), m, "\n"); let text; if (format === "toc-bbcode") { @@ -179,7 +183,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 (the disclosure lines); 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 +204,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/lib/report/serve.mjs b/umtool/lib/report/serve.mjs @@ -251,6 +251,43 @@ export async function videoFor(project, manifest, variant, kind) { }; } +/** + * A cut's podcast files (build-podcast.mjs, release 25 T3): `out/<variant>/` + * `podcast.m4a`, `podcast.mp3` and `show-notes.md`, by a NAME from this table, + * never a path. + */ +export const PODCAST_FILES = Object.freeze({ + m4a: { name: "podcast.m4a", type: "audio/mp4" }, + mp3: { name: "podcast.mp3", type: "audio/mpeg" }, + notes: { name: "show-notes.md", type: "text/markdown; charset=utf-8" }, +}); + +/** + * One of a cut's podcast files, or null when it has not been rendered. + * @param {{ dir: string }} project + * @param {{ slug?: string }} manifest + * @param {string} variant + * @param {keyof typeof PODCAST_FILES} which + */ +export async function podcastFor(project, manifest, variant, which) { + const f = PODCAST_FILES[which]; + if (!f) return null; + const slug = manifest.slug ?? path.basename(project.dir); + const dirs = variantPaths(path.join(project.dir, "out"), slug, variant); + const abs = resolveInRoots(path.join(dirs.dir, f.name)); + if (!abs) return null; + const st = await stat(abs).catch(() => null); + if (!st?.isFile()) return null; + return { + abs, + size: st.size, + mtimeMs: Math.round(st.mtimeMs), + type: f.type, + // What a download is saved as: the cut's name, not "podcast.m4a" times every project. + download: `${variant === DEFAULT_VARIANT ? slug : `${slug}-${variant}`}.${which === "notes" ? "show-notes.md" : `podcast.${which}`}`, + }; +} + // --------------------------------------------------------------------------- // The deck's preview composition. // 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,117 @@ 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** is the editor's own line from the job's result, used + verbatim — `Narration: synthetic voice (Kokoro-82M · af_heart)`, plus an + attribution sentence for an engine whose licence asks for one — each line + once. It is in each narration's record, the cut's `comment` metadata, and at + the end of the `description` and `chapters` exports. +- **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>`, lowercase and exact — the editor's `TTS_EXPRESSIVE_TAGS` + (Kokoro's side strips them); an engine of the three (the editor refuses + `orpheus` until it has it), 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. + +### The podcast: `build-podcast.mjs` + +``` +node umtool/report-to-video/build-podcast.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--progress ndjson] +``` + +The same cut as **sound only** (release 25), made from the cut's BUILT +segments, so the podcast plays exactly what the video plays: + +- **Heard:** each clip's sound as cut and snapped (its `muteFrom` honoured), + each narrated card's voice with its lead and tail, each teaser's hits. **Left + out:** an entry with no sound of its own — a card without narration, a still, + a scroll, a chart, a ledger, a teaser with `hits: false`. With + `render.podcast.skipSilentCards: false` each is `render.podcast.silence` + seconds of quiet instead. Holds, moves, dips and the end fade are picture. +- **Joined** end to end (10 ms edges, so no join clicks), then **levelled** in + two passes of `loudnorm` (linear) to the podcast norm: −16 LUFS integrated, + −1.5 dBTP. +- **Written** to `out/<variant>/podcast.m4a` (AAC, 160k) and `podcast.mp3` + (128k, ID3 chapters), each with the chapters — the video's titles + (`chapters.ffmeta`), at the podcast's own offsets — the cut's title, and for a + narrated cut the disclosure as its comment; `show-notes.md` (the title, the + length, the chapters with their times, every cited source's link — the QR's + rule for a clip, a still's `citeUrl`, a post's `url` — and the disclosure); + and `podcast.json`, what was made from what. +- **Refuses**, naming each, when a segment it needs is not built (build the cut + first — a fast build is enough), or a narrated card's segment was made from + other words than the manifest's. Takes the heavy slot. + +```jsonc +"render": { "podcast": { // every key optional + "skipSilentCards": true, "silence": 1, // 0.1–10 s + "lufs": -16, "truePeak": -1.5, // −24 to −10; −6 to 0 + "bitrate": "160k", "mp3": true, "mp3Bitrate": "128k" } } +``` + +umtool's project page offers it in the export row, beside the video's: a +**podcast** button per cut, then the three files to download. + ## Chrome, not cards **The ferret-rescue cut has no cards at all** — no title, no chapter breaks, no @@ -2102,9 +2213,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-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -0,0 +1,446 @@ +#!/usr/bin/env node +// The cut as SOUND ONLY: a podcast of the same entry list (release 25, T3). +// +// node umtool/report-to-video/build-podcast.mjs <manifest.json> +// [--out <dir>] [--variant sourced|full] [--progress ndjson] +// +// Made from the cut's BUILT segments (`out/<variant>/segments/`), so what the +// podcast plays is exactly what the video plays: each clip's sound as cut and +// snapped (its `muteFrom` honoured), each narrated card's voice with its lead +// and tail, each teaser's hits. An entry with no sound of its own -- a card +// without narration, a still, a scroll, a chart, a ledger, a teaser with +// `hits: false` -- is left out (`render.podcast.skipSilentCards`, default +// true), or is `render.podcast.silence` seconds of quiet when that is false. +// Holds, moves, dips and the end fade are picture, and are not in it. +// +// The sound is joined end to end (10 ms edges, so no join clicks), levelled to +// the podcast norm in two passes (`loudnorm`, −16 LUFS integrated, −1.5 dBTP, +// linear), and written as +// +// out/<variant>/podcast.m4a AAC, with the chapters +// out/<variant>/podcast.mp3 MP3 (ID3 chapters), unless render.podcast.mp3 is false +// out/<variant>/show-notes.md the chapters with their times, every cited +// source's link, and the disclosure line for +// a narrated cut +// out/<variant>/podcast.json what was made from what: the plan, the +// lengths, the measured loudness +// +// The chapters are the video's (`out/<variant>/chapters.ffmeta`'s titles, the +// same names), at the podcast's own offsets. A narrated cut's files carry +// "Narration: synthetic voice (<engine> · <voice>)" in their metadata and its +// show notes. +// +// Refuses, naming each, when a segment it needs is not on disk (build the cut +// first -- a fast build is enough) or a narrated card's segment was made from +// other words than the manifest's. Takes the machine's heavy slot (heavy-gate.mjs). +import { execFile } from "node:child_process"; +import { readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { promisify } from "node:util"; + +import { deckOn, deckQrUrl, muteSegmentSeconds, teaserTitle } from "./deck.mjs"; +import { hasNarration, narrationsOf } from "./narration.mjs"; +import { narrationDir, readCutDisclosure } from "./narration-store.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; + +/** Every `render.podcast` setting and its default. */ +export const PODCAST_DEFAULTS = Object.freeze({ + skipSilentCards: true, + silence: 1, + lufs: -16, + truePeak: -1.5, + bitrate: "160k", + mp3: true, + mp3Bitrate: "128k", +}); +const PODCAST_LIMITS = Object.freeze({ silence: [0.1, 10], lufs: [-24, -10], truePeak: [-6, 0] }); +const BITRATE_RE = /^\d{2,3}k$/; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** `render.podcast` with its defaults. */ +export function resolvePodcast(render) { + const p = isObj(render?.podcast) ? render.podcast : {}; + return { ...PODCAST_DEFAULTS, ...Object.fromEntries(Object.entries(p).filter(([, v]) => v !== undefined && v !== null)) }; +} + +/** `render.podcast`, checked: sentences, empty when valid (or absent). */ +export function validatePodcast(whole) { + const p = whole?.render?.podcast; + if (p === undefined || p === null) return []; + if (!isObj(p)) return ["render.podcast must be an object"]; + const errors = []; + for (const k of Object.keys(p)) { + if (!(k in PODCAST_DEFAULTS)) errors.push(`render.podcast.${k} is not a setting (${Object.keys(PODCAST_DEFAULTS).join(", ")})`); + } + for (const k of ["skipSilentCards", "mp3"]) { + if (p[k] !== undefined && typeof p[k] !== "boolean") errors.push(`render.podcast.${k} must be true or false`); + } + for (const [k, [lo, hi]] of Object.entries(PODCAST_LIMITS)) { + if (p[k] !== undefined && !(typeof p[k] === "number" && p[k] >= lo && p[k] <= hi)) { + errors.push(`render.podcast.${k} must be a number from ${lo} to ${hi}`); + } + } + for (const k of ["bitrate", "mp3Bitrate"]) { + if (p[k] !== undefined && !(typeof p[k] === "string" && BITRATE_RE.test(p[k]))) errors.push(`render.podcast.${k} must be like "128k"`); + } + return errors; +} + +/** Does an entry's segment carry sound of its own? A clip, a narrated card, a teaser with hits. */ +export function soundOf(entry) { + if (entry?.type === "clip") return "clip"; + if (hasNarration(entry)) return "narration"; + if (entry?.type === "teaser" && entry.hits !== false) return "teaser"; + return null; +} + +/** + * The entry → audio plan: which entries are heard, in cut order, and how. + * `{ id, index, type, kind: "segment", sound }` plays the entry's segment; + * `{ ..., kind: "silence", seconds }` is quiet in a silent entry's place + * (skipSilentCards false); a silent entry is otherwise left out. + */ +export function podcastPlan(manifest) { + const p = resolvePodcast(manifest.render); + const items = []; + (manifest.timeline ?? []).forEach((e, index) => { + const sound = soundOf(e); + if (sound) items.push({ id: e.id, index, type: e.type, kind: "segment", sound }); + else if (!p.skipSilentCards) items.push({ id: e.id, index, type: e.type, kind: "silence", seconds: p.silence }); + }); + return items; +} + +/** One entry's chapter name when the build wrote none: the export's own rule. */ +export function fallbackTitle(entry, index, { deck = false } = {}) { + if (entry.chapter) return entry.chapter; + if (deck && entry.onscreen?.title) return entry.onscreen.title; + if (entry.type === "teaser") return teaserTitle(entry) || `Teaser ${index + 1}`; + if (entry.type === "clip") return entry.title ?? `${index + 1}. ${entry.video ?? entry.id}`; + return entry.title ?? entry.heading ?? `Card ${index + 1}`; +} + +/** `m:ss`, `h:mm:ss` past the hour, floored. */ +export const clock = (t) => { + const s = Math.max(0, Math.floor(Number(t) || 0)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = String(s % 60).padStart(2, "0"); + return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`; +}; + +/** The podcast's chapters: each heard entry's start (the sum of what came before) and its title. */ +export function podcastChapters(items, durations, titles) { + let at = 0; + return items.map((it, i) => { + const c = { id: it.id, start: Number(at.toFixed(3)), end: Number((at + durations[i]).toFixed(3)), title: titles[it.index] }; + at += durations[i]; + return c; + }); +} + +/** ffmetadata of the chapters (and the disclosure, as the file's comment). */ +export function podcastFfmeta(chapters, { title = null, disclosure = null } = {}) { + const esc = (s) => String(s).replace(/([=;#\\\n])/g, "\\$1"); + const lines = [";FFMETADATA1"]; + if (title) lines.push(`title=${esc(title)}`); + if (disclosure) lines.push(`comment=${esc(disclosure)}`); + lines.push(""); + for (const c of chapters) { + lines.push("[CHAPTER]", "TIMEBASE=1/1000", `START=${Math.round(c.start * 1000)}`, `END=${Math.round(c.end * 1000)}`, `title=${esc(c.title)}`, ""); + } + return lines.join("\n"); +} + +/** + * Every source the podcast cites, once, in cut order: each heard clip's link + * (the QR's rule: its citeUrl, else its moment on the archive; none for a `src` + * clip without one), each still's citeUrl, each post's own url. + */ +export function citedSources(manifest, items, titles) { + const heard = new Set(items.filter((i) => i.kind === "segment").map((i) => i.id)); + const out = []; + const seen = new Set(); + const add = (label, url) => { + if (!url || seen.has(url)) return; + seen.add(url); + out.push({ label, url }); + }; + (manifest.timeline ?? []).forEach((e, i) => { + if (e.type === "clip" && heard.has(e.id)) add(titles[i], deckQrUrl(e, manifest.provenance ?? {})); + else if (e.type === "image" && e.citeUrl) add(titles[i], e.citeUrl); + }); + for (const p of Array.isArray(manifest.posts) ? manifest.posts : []) { + if (!p || p.hide) continue; + const who = p.author ?? (p.handle ? "@" + p.handle : "a post"); + const about = [p.platform, p.date ? String(p.date).slice(0, 10) : null].filter(Boolean).join(", "); + add(about ? who + " (" + about + ")" : who, p.url); + } + return out; +} + +/** The show notes, as Markdown. */ +export function showNotes({ manifest, chapters, sources, disclosure = null, duration = null }) { + const lines = [`# ${manifest.title ?? manifest.slug ?? "Podcast"}`]; + if (manifest.subtitle) lines.push("", manifest.subtitle); + if (duration != null) lines.push("", `Length: ${clock(duration)}`); + lines.push("", "## Chapters", "", ...chapters.map((c) => `- ${clock(c.start)} — ${c.title}`)); + if (sources.length) lines.push("", "## Sources", "", ...sources.map((s) => `- ${s.label} — <${s.url}>`)); + if (disclosure) lines.push("", disclosure); + return lines.join("\n") + "\n"; +} + +/** A number for a filter argument: 3 decimals, no trailing zeros. */ +const f3 = (v) => String(Math.round(Number(v) * 1000) / 1000); + +/** + * The join's filtergraph: each input to the podcast's rate and layout, a + * clip's mute (`mutes[i]`, seconds into its segment) applied, 10 ms fades at + * both edges, then all of them end to end into `[mix]`. + */ +export function podcastMixGraph(durations, { rate, layout, mutes = [] }) { + const edge = 0.01; + const parts = durations.map((d, i) => { + const chain = [`aresample=${rate}`, `aformat=sample_fmts=fltp:channel_layouts=${layout}`]; + if (mutes[i] != null) { + const at = mutes[i]; + chain.push(at > 0 ? `afade=t=out:st=${f3(Math.max(0, at - 0.04))}:d=${f3(Math.min(0.04, at))}` : "volume=0"); + } + chain.push(`afade=t=in:d=${edge}`, `afade=t=out:st=${f3(Math.max(0, d - edge))}:d=${edge}`, `atrim=end=${f3(d)}`, "asetpts=PTS-STARTPTS"); + return `[${i}:a]${chain.join(",")}[a${i}]`; + }); + const cat = `${durations.map((_, i) => `[a${i}]`).join("")}concat=n=${durations.length}:v=0:a=1[mix]`; + return [...parts, cat].join(";"); +} + +/** loudnorm's measured values, out of its pass-1 JSON on stderr. */ +export function parseLoudnorm(stderr) { + const m = /\{[^{}]*"input_i"[^{}]*\}/s.exec(String(stderr)); + if (!m) throw new Error("loudnorm printed no measurement"); + const j = JSON.parse(m[0]); + return { + i: Number(j.input_i), tp: Number(j.input_tp), lra: Number(j.input_lra), thresh: Number(j.input_thresh), offset: Number(j.target_offset), + }; +} + +/** loudnorm's pass-2 filter: linear, from pass 1's measurement, back to the podcast's rate. */ +export function loudnormPass2({ lufs, truePeak, measured, rate }) { + const fin = (v, d) => (Number.isFinite(v) ? v : d); + return `loudnorm=I=${lufs}:TP=${truePeak}:LRA=11:measured_I=${fin(measured.i, -70)}:measured_TP=${fin(measured.tp, -70)}` + + `:measured_LRA=${fin(measured.lra, 0)}:measured_thresh=${fin(measured.thresh, -70)}:offset=${fin(measured.offset, 0)}:linear=true:print_format=summary,aresample=${rate}`; +} + +async function probeSeconds(file) { + const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file]); + const s = Number(stdout.trim()); + if (!Number.isFinite(s) || s <= 0) throw new Error(`ffprobe reads no duration from ${file}`); + return s; +} + +/** The chapter titles in an ffmetadata text, in order, unescaped. */ +export function ffmetaTitles(text) { + const out = []; + let inChapter = false; + for (const raw of String(text).split("\n")) { + const line = raw.trim(); + if (line === "[CHAPTER]") { + inChapter = true; + out.push(""); + continue; + } + if (inChapter && line.startsWith("title=")) out[out.length - 1] = line.slice(6).replace(/\\([=;#\\])/g, "$1"); + } + return out; +} + +/** The video's chapter titles, by entry index, when its ffmeta describes this cut. */ +async function videoTitles(dir, entries) { + const text = await readFile(path.join(dir, "chapters.ffmeta"), "utf8").catch(() => null); + if (!text) return null; + const titles = ffmetaTitles(text); + return titles.length === entries.length ? titles : null; +} + +/** + * Render the podcast of one cut. `emit(ev, fields)` hears `podcast` (phase + * plan | mix | loudness | encode | notes), `note` and `done`. + * + * @returns {Promise<{ m4a: string, mp3: string|null, notes: string, duration: number, chapters: any[] }>} + */ +export async function buildPodcast({ manifestPath, variant = "sourced", out = null, emit = () => {} }) { + const { selectVariant, variantPaths, readCutRecord } = await import("./build-video.mjs"); + const { narrationKey } = await import("./narration.mjs"); + const whole = JSON.parse(await readFile(manifestPath, "utf8")); + const errors = validatePodcast(whole); + if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); + const manifest = selectVariant(whole, variant); + const { render } = manifest; + const settings = resolvePodcast(render); + const outRoot = out ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); + const dirs = variantPaths(outRoot, manifest.slug, variant); + const segDir = path.join(dirs.dir, "segments"); + const entries = manifest.timeline ?? []; + const items = podcastPlan(manifest); + if (!items.length) throw new Error("nothing in this cut has sound: no clip, no narrated card, no teaser with hits"); + emit("podcast", { phase: "plan", heard: items.filter((i) => i.kind === "segment").length, silences: items.filter((i) => i.kind === "silence").length, left: entries.length - items.length }); + + // Every segment it needs, on disk and of THIS manifest's words. + const missing = []; + const stale = []; + const keys = new Map(narrationsOf(manifest).map((n) => [n.id, n.key])); + for (const it of items) { + if (it.kind !== "segment") continue; + const seg = path.join(segDir, `${it.id}.mp4`); + if (!(await stat(seg).then((s) => s.isFile(), () => false))) { + missing.push(it.id); + continue; + } + if (it.sound === "narration") { + const rec = await readFile(seg.replace(/\.mp4$/, ".narration.json"), "utf8").then(JSON.parse, () => null); + if (!rec || rec.narration !== keys.get(it.id)) stale.push(it.id); + } + } + if (missing.length) { + throw new Error(`the podcast is made from the cut's segments, and ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not built — build the cut first (a fast build is enough)`); + } + if (stale.length) { + throw new Error(`${stale.join(", ")}: the narrated card's segment was made from other words than the manifest's — rebuild the cut first`); + } + + // The lengths, and each clip's mute. + const durations = []; + const mutes = []; + for (const it of items) { + if (it.kind === "silence") { + durations.push(it.seconds); + mutes.push(null); + continue; + } + const seg = path.join(segDir, `${it.id}.mp4`); + const d = await probeSeconds(seg); + durations.push(d); + const e = entries[it.index]; + if (e.type === "clip" && e.muteFrom != null) { + const m = muteSegmentSeconds({ entry: e, record: await readCutRecord(seg), render, seconds: d }); + if (m.note) emit("note", { id: e.id, message: m.note }); + mutes.push(m.at < d ? m.at : null); + } else { + mutes.push(null); + } + } + + const rate = render.audioRate ?? 48000; + const layout = render.audioChannels === 1 ? "mono" : "stereo"; + const work = path.join(dirs.dir, `.podcast.${process.pid}.work.wav`); + const m4a = path.join(dirs.dir, "podcast.m4a"); + const mp3 = settings.mp3 ? path.join(dirs.dir, "podcast.mp3") : null; + const notesPath = path.join(dirs.dir, "show-notes.md"); + const metaPath = path.join(dirs.dir, "podcast.ffmeta"); + try { + // 1. Joined, end to end, as PCM. + emit("podcast", { phase: "mix", inputs: items.length }); + const inputs = items.flatMap((it, i) => (it.kind === "silence" + ? ["-f", "lavfi", "-t", f3(durations[i]), "-i", `anullsrc=channel_layout=${layout}:sample_rate=${rate}`] + : ["-i", path.join(segDir, `${it.id}.mp4`)])); + await execFileP(FFMPEG(), [ + "-nostdin", "-v", "error", "-y", ...inputs, + "-filter_complex", podcastMixGraph(durations, { rate, layout, mutes }), + "-map", "[mix]", "-c:a", "pcm_s24le", work, + ], { maxBuffer: 1 << 26 }); + + // 2. Levelled to the podcast norm, in two passes (loudnorm linear). + emit("podcast", { phase: "loudness", target: settings.lufs }); + const pass1 = await execFileP(FFMPEG(), [ + "-nostdin", "-hide_banner", "-nostats", "-i", work, + "-af", `loudnorm=I=${settings.lufs}:TP=${settings.truePeak}:LRA=11:print_format=json`, "-f", "null", "-", + ], { maxBuffer: 1 << 26 }); + const measured = parseLoudnorm(pass1.stderr); + const level = loudnormPass2({ lufs: settings.lufs, truePeak: settings.truePeak, measured, rate }); + + // 3. The chapters (the video's titles, the podcast's offsets) and the files. + const titles = (await videoTitles(dirs.dir, entries)) ?? entries.map((e, i) => fallbackTitle(e, i, { deck: deckOn(render) })); + const chapters = podcastChapters(items, durations, titles); + // The editor's own disclosure lines, from the narrations the build kept. + const disclosure = await readCutDisclosure(narrationDir(outRoot), manifest, "\n"); + await writeFile(metaPath, podcastFfmeta(chapters, { title: manifest.title ?? null, disclosure: disclosure?.replace(/\n/g, " ") ?? null }), "utf8"); + emit("podcast", { phase: "encode", m4a: path.basename(m4a), mp3: mp3 ? path.basename(mp3) : null }); + const encode = async (file, codec) => { + const tmp = file.replace(/(\.[a-z0-9]+)$/, `.${process.pid}.tmp$1`); + try { + await execFileP(FFMPEG(), [ + "-nostdin", "-v", "error", "-y", "-i", work, "-i", metaPath, + "-map", "0:a", "-map_metadata", "1", "-map_chapters", "1", + "-af", level, "-ar", String(rate), "-ac", layout === "mono" ? "1" : "2", + ...codec, tmp, + ], { maxBuffer: 1 << 26 }); + await rename(tmp, file); + } finally { + await rm(tmp, { force: true }); + } + }; + await encode(m4a, ["-c:a", "aac", "-b:a", settings.bitrate, "-movflags", "+faststart"]); + if (mp3) await encode(mp3, ["-c:a", "libmp3lame", "-b:a", settings.mp3Bitrate, "-id3v2_version", "3", "-write_id3v1", "1"]); + + const duration = await probeSeconds(m4a); + const sources = citedSources(manifest, items, titles); + await writeFile(notesPath, showNotes({ manifest, chapters, sources, disclosure, duration }), "utf8"); + emit("podcast", { phase: "notes", file: path.basename(notesPath), sources: sources.length, chapters: chapters.length }); + await writeFile(path.join(dirs.dir, "podcast.json"), JSON.stringify({ + v: 1, variant, items: items.map((it, i) => ({ ...it, seconds: Number(durations[i].toFixed(3)), ...(mutes[i] != null ? { muteAt: mutes[i] } : {}) })), + left: entries.filter((e) => !items.some((it) => it.id === e.id)).map((e) => e.id), + lufs: settings.lufs, truePeak: settings.truePeak, measured, duration: Number(duration.toFixed(3)), + files: { m4a: path.basename(m4a), mp3: mp3 ? path.basename(mp3) : null, notes: path.basename(notesPath) }, + disclosure, madeAt: new Date().toISOString(), + }, null, 2) + "\n", "utf8"); + emit("done", { out: m4a, mp3, notes: notesPath, duration: Number(duration.toFixed(3)), chapters: chapters.length }); + return { m4a, mp3, notes: notesPath, duration, chapters }; + } finally { + await rm(work, { force: true }); + } +} + +// heavy-gate.mjs's withRenderSlot, loaded by a URL made at run time (as +// build-video.mjs's renderSlot): never through anything the app bundles. +async function renderSlot() { + const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href; + const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); + return withRenderSlot; +} + +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])); + const ndjson = flag("--progress") === "ndjson"; + const emit = ndjson + ? (ev, f = {}) => process.stdout.write(JSON.stringify({ ev, ...f }) + "\n") + : (ev, f = {}) => { + if (ev === "note") console.log(f.message); + else if (ev === "podcast") console.log(`podcast ${f.phase}${f.heard !== undefined ? `: ${f.heard} heard, ${f.silences} silence(s), ${f.left} left out` : ""}`); + else if (ev === "done") console.log(`${f.out}${f.mp3 ? `\n${f.mp3}` : ""}\n${f.notes}\nduration=${f.duration}`); + }; + if (!manifestPath) { + console.error("usage: build-podcast.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--progress ndjson]"); + process.exit(2); + } + const run = () => buildPodcast({ manifestPath, variant: flag("--variant") ?? "sourced", out: flag("--out") ?? null, emit }); + try { + await (await renderSlot())(["build-podcast", ...argv], run); + } catch (err) { + emit("error", { message: err?.message ?? String(err) }); + if (ndjson) process.stderr.write(`${err?.message ?? err}\n`); + else console.error(err?.message ?? err); + process.exit(1); + } +} + +if (import.meta.url === `file://${process.argv[1]}`) main(); diff --git a/umtool/report-to-video/build-podcast.test.mjs b/umtool/report-to-video/build-podcast.test.mjs @@ -0,0 +1,169 @@ +// build-podcast.mjs: the entry → audio plan, the chapters, the show notes, the +// settings' validator, and one render over segments made with ffmpeg tones +// (never a TTS engine): the files, their chapters, their loudness, the +// disclosure, and the two refusals. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + buildPodcast, citedSources, clock, ffmetaTitles, parseLoudnorm, podcastChapters, podcastFfmeta, podcastMixGraph, + podcastPlan, showNotes, validatePodcast, +} from "./build-podcast.mjs"; +import { narrationKey } from "./narration.mjs"; + +const haveFf = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const PROV = { siteOrigin: "https://archive.example", channelSlug: "chan" }; +const NARR = { text: "Then the county said yes." }; +const TIMELINE = [ + { id: "t0", type: "card", heading: "Title", seconds: 3 }, + { id: "k1", type: "card", heading: "Then", seconds: "auto", narration: NARR }, + { id: "c1", type: "clip", video: "v1", start: 10.4, end: 14 }, + { id: "i1", type: "image", src: "a.png", citeUrl: "https://example.test/post/1" }, + { id: "c2", type: "clip", video: "v2", channel: "other", start: 3, end: 5, citeUrl: "https://mirror.example/v2?t=3" }, + { id: "z1", type: "teaser", lines: ["Soon"], hits: false }, +]; +const M = (render = {}, extra = {}) => ({ slug: "pod", title: "The Pod", subtitle: "a test", provenance: PROV, render: { audioRate: 48000, audioChannels: 2, ...render }, timeline: TIMELINE, ...extra }); + +test("the plan: clips, narrated cards and teasers with hits are heard; the rest left out, or silence", () => { + const plan = podcastPlan(M()); + assert.deepEqual(plan.map((p) => `${p.id}:${p.kind}:${p.sound}`), ["k1:segment:narration", "c1:segment:clip", "c2:segment:clip"]); + const quiet = podcastPlan(M({ podcast: { skipSilentCards: false, silence: 0.5 } })); + assert.deepEqual(quiet.map((p) => `${p.id}:${p.kind}`), ["t0:silence", "k1:segment", "c1:segment", "i1:silence", "c2:segment", "z1:silence"]); + assert.equal(quiet[0].seconds, 0.5); + assert.deepEqual(podcastPlan({ render: {}, timeline: [{ id: "z", type: "teaser", lines: ["x"] }] }).map((p) => p.sound), ["teaser"]); +}); + +test("render.podcast is checked", () => { + assert.deepEqual(validatePodcast(M()), []); + assert.deepEqual(validatePodcast(M({ podcast: { lufs: -19, mp3: false, bitrate: "128k" } })), []); + const e = validatePodcast(M({ podcast: { lufs: -5, mp3: "yes", bitrate: "loud", volume: 2 } })); + assert.equal(e.length, 4, e.join("\n")); + assert.match(e.join("\n"), /render\.podcast\.volume is not a setting/); + assert.match(e.join("\n"), /lufs must be a number from -24 to -10/); + assert.match(e.join("\n"), /mp3 must be true or false/); + assert.match(e.join("\n"), /bitrate must be like "128k"/); +}); + +test("chapters at the podcast's own offsets, with the video's titles; ffmeta and show notes", () => { + const items = podcastPlan(M()); + const titles = ["Title", "Then", "Chan · 2024-01-01 — One", "Image", "Other · Two", "Soon"]; + const ch = podcastChapters(items, [4.1, 3.6, 2], titles); + assert.deepEqual(ch.map((c) => [c.title, c.start, c.end]), [["Then", 0, 4.1], ["Chan · 2024-01-01 — One", 4.1, 7.7], ["Other · Two", 7.7, 9.7]]); + const meta = podcastFfmeta(ch, { title: "The Pod", disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart)" }); + assert.match(meta, /^;FFMETADATA1\ntitle=The Pod\ncomment=Narration: synthetic voice \(Kokoro-82M · af_heart\)\n/); + assert.equal((meta.match(/\[CHAPTER\]/g) ?? []).length, 3); + assert.match(meta, /START=4100\nEND=7700\ntitle=Chan · 2024-01-01 — One/); + assert.deepEqual(ffmetaTitles(meta), ["Then", "Chan · 2024-01-01 — One", "Other · Two"]); + assert.deepEqual(ffmetaTitles("[CHAPTER]\ntitle=a \\= b\n[CHAPTER]\ntitle=c"), ["a = b", "c"]); + + const sources = citedSources(M({}, { posts: [{ id: "p1", author: "Someone", platform: "bluesky", date: "2026-08-13T19:05:26Z", url: "https://bsky.example/p/1" }, { id: "p2", hide: true, url: "https://x.example/2" }] }), items, titles); + assert.deepEqual(sources, [ + { label: "Chan · 2024-01-01 — One", url: "https://archive.example/?v=chan%2Fv1&t=10" }, + { label: "Image", url: "https://example.test/post/1" }, + { label: "Other · Two", url: "https://mirror.example/v2?t=3" }, + { label: "Someone (bluesky, 2026-08-13)", url: "https://bsky.example/p/1" }, + ]); + const notes = showNotes({ manifest: M(), chapters: ch, sources, disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart)", duration: 9.7 }); + assert.equal(notes, [ + "# The Pod", "", "a test", "", "Length: 0:09", "", "## Chapters", "", + "- 0:00 — Then", "- 0:04 — Chan · 2024-01-01 — One", "- 0:07 — Other · Two", "", + "## Sources", "", + "- Chan · 2024-01-01 — One — <https://archive.example/?v=chan%2Fv1&t=10>", + "- Image — <https://example.test/post/1>", + "- Other · Two — <https://mirror.example/v2?t=3>", + "- Someone (bluesky, 2026-08-13) — <https://bsky.example/p/1>", + "", "Narration: synthetic voice (Kokoro-82M · af_heart)", "", + ].join("\n")); + assert.equal(clock(3725), "1:02:05"); +}); + +test("the join's graph: rate and layout, a clip's mute, 10 ms edges, end to end", () => { + const g = podcastMixGraph([2, 1.5], { rate: 48000, layout: "stereo", mutes: [1.2, null] }); + assert.equal(g, + "[0:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,afade=t=out:st=1.16:d=0.04," + + "afade=t=in:d=0.01,afade=t=out:st=1.99:d=0.01,atrim=end=2,asetpts=PTS-STARTPTS[a0];" + + "[1:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,afade=t=in:d=0.01,afade=t=out:st=1.49:d=0.01," + + "atrim=end=1.5,asetpts=PTS-STARTPTS[a1];[a0][a1]concat=n=2:v=0:a=1[mix]"); + assert.match(podcastMixGraph([1], { rate: 44100, layout: "mono", mutes: [0] }), /channel_layouts=mono,volume=0,/); + assert.deepEqual( + parseLoudnorm('junk\n{\n\t"input_i" : "-23.10",\n\t"input_tp" : "-4.2",\n\t"input_lra" : "3.1",\n\t"input_thresh" : "-33.4",\n\t"target_offset" : "0.2"\n}\n'), + { i: -23.1, tp: -4.2, lra: 3.1, thresh: -33.4, offset: 0.2 }, + ); +}); + +const ff = (args) => { + const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args]); + assert.equal(r.status, 0, String(r.stderr)); +}; +/** A segment as the build makes them: a still picture and a sound (`src`: a lavfi audio source). */ +const segment = (file, seconds, src) => ff([ + "-f", "lavfi", "-i", `color=c=0x223344:size=160x90:rate=10:duration=${seconds}`, + "-f", "lavfi", "-i", src, "-t", String(seconds), + "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-ar", "48000", "-ac", "2", "-shortest", file, +]); +const json = (file, entries) => JSON.parse(spawnSync("ffprobe", ["-v", "error", ...entries, "-of", "json", file], { encoding: "utf8" }).stdout); +const lufsOf = (file) => { + const r = spawnSync("ffmpeg", ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], { encoding: "utf8" }); + return Number([...r.stderr.matchAll(/\bI:\s+(-?[\d.]+) LUFS/g)].at(-1)[1]); +}; + +test("a render: m4a and mp3 with chapters at −16 LUFS, the show notes, the disclosure; refusals name the entry", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-podcast-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const manifestPath = path.join(root, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify(M())); + const segs = path.join(root, "out", "sourced", "segments"); + mkdirSync(segs, { recursive: true }); + + // Not built yet: refused, naming the missing. + await assert.rejects(buildPodcast({ manifestPath }), /k1, c1, c2 are not built — build the cut first/); + + segment(path.join(segs, "t0.mp4"), 3, "anullsrc=channel_layout=stereo:sample_rate=48000"); + segment(path.join(segs, "k1.mp4"), 3.6, "sine=frequency=330:sample_rate=48000"); + segment(path.join(segs, "c1.mp4"), 2.5, "anoisesrc=color=pink:amplitude=0.05:sample_rate=48000"); + segment(path.join(segs, "c2.mp4"), 2, "sine=frequency=550:sample_rate=48000"); + // The narrated card's record, from OTHER words: refused as stale. + writeFileSync(path.join(segs, "k1.narration.json"), JSON.stringify({ key: "x", narration: narrationKey({ text: "Old words.", engine: "kokoro", voice: "af_heart", speed: 1 }) })); + await assert.rejects(buildPodcast({ manifestPath }), /k1: the narrated card's segment was made from other words/); + writeFileSync(path.join(segs, "k1.narration.json"), JSON.stringify({ key: "x", narration: narrationKey({ text: NARR.text, engine: "kokoro", voice: "af_heart", speed: 1 }) })); + // The video's chapters: their titles are the podcast's. + writeFileSync(path.join(root, "out", "sourced", "chapters.ffmeta"), [";FFMETADATA1", "", + ...["Title", "Then", "Chan · One", "Image", "Other · Two", "Soon"].flatMap((title, i) => ["[CHAPTER]", "TIMEBASE=1/1000", `START=${i * 1000}`, `END=${(i + 1) * 1000}`, `title=${title}`, ""])].join("\n")); + + const events = []; + const r = await buildPodcast({ manifestPath, emit: (ev, f) => events.push({ ev, ...f }) }); + const dir = path.join(root, "out", "sourced"); + assert.equal(r.m4a, path.join(dir, "podcast.m4a")); + assert.ok(Math.abs(r.duration - 8.1) < 0.1, `duration ${r.duration}`); + for (const file of [r.m4a, r.mp3]) { + const info = json(file, ["-show_chapters", "-show_entries", "format_tags=title,comment"]); + assert.deepEqual(info.chapters.map((c) => c.tags.title), ["Then", "Chan · One", "Other · Two"], file); + assert.ok(Math.abs(Number(info.chapters[1].start_time) - 3.6) < 0.05, `${file}: ${info.chapters[1].start_time}`); + const tags = Object.fromEntries(Object.entries(info.format.tags ?? {}).map(([k, v]) => [k.toLowerCase(), v])); + assert.equal(tags.title, "The Pod"); + assert.equal(tags.comment, "Narration: synthetic voice (Kokoro-82M · af_heart)"); + const l = lufsOf(file); + assert.ok(Math.abs(l + 16) < 1.5, `${file} at ${l} LUFS`); + } + const notes = readFileSync(r.notes, "utf8"); + assert.match(notes, /- 0:03 — Chan · One/); + assert.match(notes, /<https:\/\/archive\.example\/\?v=chan%2Fv1&t=10>/); + assert.match(notes, /Narration: synthetic voice \(Kokoro-82M · af_heart\)\n$/); + const rec = JSON.parse(readFileSync(path.join(dir, "podcast.json"), "utf8")); + assert.deepEqual(rec.left, ["t0", "i1", "z1"]); + assert.equal(rec.lufs, -16); + assert.deepEqual(events.filter((e) => e.ev === "podcast").map((e) => e.phase), ["plan", "mix", "loudness", "encode", "notes"]); + assert.ok(!existsSync(path.join(dir, `.podcast.${process.pid}.work.wav`)), "the work file is gone"); +}); + +test("the lint reports a bad render.podcast", async () => { + const { lintManifest } = await import("./lint.mjs"); + const lint = lintManifest(M({ podcast: { lufs: 0 } })); + assert.ok(lint.errors.some((e) => /render\.podcast\.lufs must be a number from -24 to -10/.test(e)), lint.errors.join("\n")); +}); 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, narrationGainDb, narrationsOf, + cardNarrationSeconds, resolveNarrationRender, validateNarration, +} from "./narration.mjs"; +import { narrationDir, narrationWavPath, readCutDisclosure, 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 (the editor's disclosure lines); 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: await readCutDisclosure(narrationStore, 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: await readCutDisclosure(narrationStore, 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: await readCutDisclosure(narrationStore, 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: await readCutDisclosure(narrationStore, 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), validatePodcast (build-podcast.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,8 @@ 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"; +import { validatePodcast } from "./build-podcast.mjs"; export const TEASER_HOUSE_CHARS = 34; export const MIN_QR_PX_PER_MODULE_720P = 1.5; @@ -193,7 +200,9 @@ 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), + // The podcast's settings: its render refuses them, and `--lint` says so first. + ...validatePodcast(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); @@ -202,18 +211,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 +298,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 +324,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,271 @@ +#!/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 ask's body keys are the editor's (`{text, engine, voice, speed}` of its +// `{text, file, voice, engine, speed, out}`); `out` is never sent -- the +// editor writes into its own cache and its result names the file. Its result +// line carries the disclosure ("Narration: synthetic voice (Kokoro-82M · +// af_heart)"), which is kept with the narration and used verbatim. +// +// 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; +// Re-reads of a done job's tail before its result line counts as missing. +const RESULT_RETRIES = 10; + +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); + let done = await poll(jobId, true); + // A cache hit can say `done` a few ms before its log line is on disk: + // read the tail again, briefly, before calling the result missing. + for (let i = 0; status === "done" && !ttsResultIn(done.tail) && i < RESULT_RETRIES; i += 1) { + await sleep(Math.max(pollMs, 100)); + 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,305 @@ +// 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, tails: 0, fail: /FAIL/.test(body.text), + result: { wav, seconds, engine: body.engine, voice: body.voice, cached: false, durationMs: 12, waitedMs: 3, sha: "s", sampleRate: 48000, speed: body.speed, disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice})` }, + }); + 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; + else j.tails += 1; + const status = j.polls <= 1 ? "queued" : j.polls === 2 ? "running" : j.fail ? "failed" : "done"; + // The editor's caveat, played: the first tail of a done job does not + // have the result line on disk yet. + const lineOnDisk = j.tails > 1; + 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", ...(lineOnDisk ? [`${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-82M · af_heart)", "the editor's line, verbatim"); + assert.equal(rec.editor.sha, "s"); + 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-82M · 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,145 @@ +// 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 { disclosureLine, narrationDisclosure, narrationsOf } 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) } : {}), + ...(typeof result.sha === "string" ? { sha: result.sha } : {}), + }, + // The editor's own line, verbatim (it may carry an engine's attribution). + disclosure: typeof result.disclosure === "string" && result.disclosure.trim() + ? result.disclosure.trim() + : disclosureLine(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; +} + +/** + * A cut's disclosure, from the narrations it keeps (`out/narration/`): the + * editor's lines, each once, joined by `sep`; null when nothing is narrated. + * A narration not kept yet says the line its engine and voice would. + */ +export async function readCutDisclosure(dir, manifest, sep = "\n") { + const records = await readNarrationRecords(dir, narrationsOf(manifest)); + return narrationDisclosure(manifest, records, sep); +} diff --git a/umtool/report-to-video/narration.mjs b/umtool/report-to-video/narration.mjs @@ -0,0 +1,343 @@ +// 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, lowercase and exact: Orpheus + * speaks them; Kokoro has none, and the editor strips them before it + * synthesizes. Any other `<…>` is refused, by name -- the editor's own list + * and rule (`TTS_EXPRESSIVE_TAGS`, common/lib/ttsText.ts; a test holds the + * two equal), mirrored here because this file runs in bare node and in + * umtool's client bundle. + */ +export const NARRATION_TAGS = Object.freeze(["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]); + +/** + * Each engine's name as the editor's disclosure line says it (ttsApps.ts + * `label`). Only for a narration whose record carries no line of the editor's + * own -- the editor's `disclosure` is used verbatim whenever there is one. + */ +export const NARRATION_ENGINE_LABELS = Object.freeze({ kokoro: "Kokoro-82M", "espeak-ng": "eSpeak NG", orpheus: "Orpheus" }); + +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)) { + if (NARRATION_TAGS.includes(m[1])) continue; + // Exact, as the editor reads them: `<Sigh>` and `< sigh >` are not tags. + const near = m[1].trim().toLowerCase(); + const hint = NARRATION_TAGS.includes(near) ? ` (did you mean <${near}>?)` : ""; + out.push(`the tag <${m[1]}>${hint} 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 line for one engine and voice, as the editor writes it (ttsApps.ts `ttsDisclosure`). */ +export const disclosureLine = (engine, voice) => + `Narration: synthetic voice (${NARRATION_ENGINE_LABELS[engine] ?? engine} · ${voice})`; + +/** + * The disclosure lines a narrated output carries -- in its description and + * chapters export, its show notes, its file's metadata -- each once, in cut + * order: every narration's record's own line (the editor's, verbatim: + * "Narration: synthetic voice (Kokoro-82M · af_heart)"), else one made the + * same way from the engine and voice asked for. `records` maps a card id to + * its record (narration-store). Empty when nothing in the cut is narrated. + */ +export function disclosureLines(manifest, records = new Map()) { + const lines = []; + for (const n of narrationsOf(manifest)) { + const line = records.get(n.id)?.disclosure || disclosureLine(n.engine, n.voice); + if (!lines.includes(line)) lines.push(line); + } + return lines; +} + +/** disclosureLines as one text (`sep` between lines), or null when nothing is narrated. */ +export function narrationDisclosure(manifest, records = new Map(), sep = "\n") { + const lines = disclosureLines(manifest, records); + return lines.length ? lines.join(sep) : null; +} diff --git a/umtool/report-to-video/narration.test.mjs b/umtool/report-to-video/narration.test.mjs @@ -0,0 +1,157 @@ +// 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, disclosureLines, 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>."), []); + // Exact, as the editor reads them. + assert.match(errs("Well <SIGH>.")[0], /the tag <SIGH> \(did you mean <sigh>\?\) is not one of/); + assert.match(errs("Well < laugh >.")[0], /the tag < laugh > \(did you mean <laugh>\?\)/); + 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: the record's own line, else the editor's form; each once; none without narration", () => { + assert.equal(narrationDisclosure(M([card()])), "Narration: synthetic voice (Kokoro-82M · af_heart)"); + assert.equal( + narrationDisclosure(M([card(), card({ id: "k2", narration: { text: "Two.", voice: "am_adam" } }), card({ id: "k3" })])), + "Narration: synthetic voice (Kokoro-82M · af_heart)\nNarration: synthetic voice (Kokoro-82M · am_adam)", + ); + assert.equal(narrationDisclosure(M([{ type: "card", id: "a", seconds: 3 }])), null); + // The editor's line wins, verbatim, attribution and all. + const recs = new Map([["k1", { disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart). Some attribution." }]]); + assert.equal(narrationDisclosure(M([card(), card({ id: "k2" })]), recs, " "), "Narration: synthetic voice (Kokoro-82M · af_heart). Some attribution. Narration: synthetic voice (Kokoro-82M · af_heart)"); + assert.deepEqual(disclosureLines(M([card({ narration: { text: "a", engine: "espeak-ng", voice: "en-us" } })])), ["Narration: synthetic voice (eSpeak NG · en-us)"]); +}); + +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")); +}); + +test("the tags are the editor's: TTS_EXPRESSIVE_TAGS (common/lib/ttsText.ts)", async () => { + const { TTS_EXPRESSIVE_TAGS } = await import("yt-dlp-transcript-common/lib/ttsText"); + assert.deepEqual([...NARRATION_TAGS], [...TTS_EXPRESSIVE_TAGS]); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -29,6 +29,8 @@ "./lint": "./lint.mjs", "./local-media": "./local-media.mjs", "./mute": "./mute.mjs", + "./narration": "./narration.mjs", + "./narration-store": "./narration-store.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) {