#!/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 // [--out ] [--variant sourced|full] [--progress ndjson] // // Made from the cut's BUILT segments (`out//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//podcast.m4a AAC, with the chapters // out//podcast.mp3 MP3 (ID3 chapters), unless render.podcast.mp3 is false // out//show-notes.md the chapters with their times, every cited // source's link, and the disclosure line for // a narrated cut // out//podcast.json what was made from what: the plan, the // lengths, the measured loudness // // The chapters are the video's (`out//chapters.ffmeta`'s titles, the // same names), at the podcast's own offsets. A narrated cut's files carry // "Narration: synthetic 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, segmentSoundEdits, soundEdges, teaserTitle } from "./deck.mjs"; import { hasNarration, narrationsOf } from "./narration.mjs"; import { narrationDir, readCutDisclosure } from "./narration-store.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.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 -- an anonymous author's post (post-anon.mjs: `noQr`) * by its shown name and with NO link. */ 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 }); }; const named = new Set(); (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(", "); const label = about ? who + " (" + about + ")" : who; if (p.noQr === true || p.anonymous === true) { if (!named.has(label)) out.push({ label, url: null }); named.add(label); continue; } add(label, 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.url ? `- ${s.label} — <${s.url}>` : `- ${s.label}`))); 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("; ")}`); // ON-SCREEN ANONYMISING's set (post-anon.mjs), the project's: an anonymous author's post is cited by its shown // name and with no link (citedSources); refused as the build is. const { projectAnonymousSet } = await import("./project-characters-file.mjs"); const { anonymiseManifest } = await import("./post-anon.mjs"); const anonymity = await projectAnonymousSet(path.dirname(path.resolve(manifestPath)), whole); const manifest = anonymiseManifest(selectVariant(whole, variant), anonymity.doc, { set: anonymity.set }); 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]; // The one rule (mute.mjs soundEdges): its own muteFrom, or its locked end. const se = soundEdges(e, render); if (e.type === "clip" && se.muteFrom != null) { const ed = segmentSoundEdits({ entry: e, record: await readCutRecord(seg), render, seconds: d }); for (const message of ed.notes) emit("note", { id: e.id, message }); mutes.push(ed.mute != null && ed.mute < d ? ed.mute : 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 = tmpPathFor(file.replace(/\.[a-z0-9]+$/, ""), { ext: /\.[a-z0-9]+$/.exec(file)?.[0] ?? "" }); 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 [--out ] [--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();