Archilyzer · Source

archilyzer

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

commit 81640cab55064ea64dba39b9a4a6803de4d5be8d
parent e0e9474ca872fb7e0b4c57c5bcf480c2338e1314
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 00:50:03 -0400

umtool: the cut as a podcast — build-podcast.mjs, and the export row's podcast button (release 25 T3)

build-podcast.mjs renders a cut's built segments as sound only: each clip's
sound as cut (muteFrom honoured), each narrated card's voice, each teaser's
hits; an entry with no sound of its own is left out (render.podcast.
skipSilentCards, default true) or is `silence` seconds of quiet. Joined end to
end with 10 ms edges, levelled in two loudnorm passes to −16 LUFS / −1.5 dBTP,
written to out/<variant>/podcast.m4a and podcast.mp3 with the video's chapter
titles at the podcast's own offsets, show-notes.md (chapters with times, every
cited source's link, the disclosure for a narrated cut) and podcast.json.
Refuses a missing segment, or a narrated card's segment made from other words.
The build route's `options.podcast` runs it alone; GET /api/report/podcast
serves the three files by name; the project page's export row gets a podcast
button per cut. validatePodcast runs in the render and the lint.

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

Diffstat:
Mumtool/app/api/report/build/route.ts | 15++++++++++-----
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 | 6++++++
Mumtool/e2e/report-narration.spec.ts | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/busy.mjs | 2+-
Mumtool/lib/report/deliverables.test.mjs | 1+
Mumtool/lib/report/driver.mjs | 14+++++++++++++-
Mumtool/lib/report/driver.test.mjs | 9+++++++++
Mumtool/lib/report/serve.mjs | 37+++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/README.md | 39+++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/build-podcast.mjs | 443+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/build-podcast.test.mjs | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/lint.mjs | 5++++-
15 files changed, 922 insertions(+), 8 deletions(-)

diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -83,6 +83,7 @@ export async function POST(request: Request) { chromeOnly?: boolean; preview?: { at: number; dur: number } | null; narrate?: boolean; + podcast?: boolean; } = {}; if (raw.variant !== undefined && raw.variant !== "") { const v = String(raw.variant); @@ -106,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 }, ); } @@ -123,7 +128,7 @@ export async function POST(request: Request) { const clipCount = clipsOf(manifest).length; // A card that carries narration puts the editor's tts step before the build. - if (manifest.timeline?.some((e: { type?: string; narration?: unknown }) => e?.type === "card" && e.narration)) { + 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 }); @@ -155,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), @@ -190,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 @@ -783,6 +783,12 @@ is YouTube's form and includes cards. Cite URLs follow the QR's rule. A cut with a narrated card (`narration`, below) ends its `description` and `chapters` with the disclosure line, `Narration: synthetic voice (kokoro · af_heart)`. +**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 diff --git a/umtool/e2e/report-narration.spec.ts b/umtool/e2e/report-narration.spec.ts @@ -99,3 +99,43 @@ test("a narrated card speaks, its length is the narration's, the plain card is s } 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|narrate-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 @@ -379,6 +379,7 @@ test("namesProject: a script names a project by path, or by --project id, name o 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 @@ -66,7 +66,12 @@ export const buildTimeoutMs = (clipCount, xfade) => * kept (narrate-via-editor.mjs). Not for the runs that build * no segment from the manifest's words. * - * @typedef {{ variant?: string, xfade?: boolean, chaptersOnly?: boolean, chromeOnly?: boolean, preview?: { at: number, dur: number } | null, narrate?: boolean }} BuildOptions + * 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. */ @@ -93,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 ? [] : [ diff --git a/umtool/lib/report/driver.test.mjs b/umtool/lib/report/driver.test.mjs @@ -66,3 +66,12 @@ test("narrate: the editor's tts step goes before the build, told the cut; never 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/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 @@ -1133,6 +1133,45 @@ 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 diff --git a/umtool/report-to-video/build-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -0,0 +1,443 @@ +#!/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, narrationDisclosure, narrationsOf } from "./narration.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"); + add(`${who}${p.platform ? ` (${p.platform}` : ""}${p.date ? `${p.platform ? ", " : " ("}${String(p.date).slice(0, 10)}` : ""}${p.platform || p.date ? ")" : ""}`, 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); + const disclosure = narrationDisclosure(manifest); + await writeFile(metaPath, podcastFfmeta(chapters, { title: manifest.title ?? null, disclosure }), "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 · af_heart)" }); + assert.match(meta, /^;FFMETADATA1\ntitle=The Pod\ncomment=Narration: synthetic voice \(kokoro · 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 · 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 · 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 · 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 · 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/lint.mjs b/umtool/report-to-video/lint.mjs @@ -21,7 +21,7 @@ // 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), validateNarration -// (narration.mjs), and the cut edits, teasers, claims and posts validators +// (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 @@ -67,6 +67,7 @@ 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; @@ -200,6 +201,8 @@ export function validatorErrors(whole) { const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(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}`));