// 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 — ", "- Image — ", "- Other · Two — ", "- Someone (bluesky, 2026-08-13) — ", "", "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, //); 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")); });