// 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" } } // // An Orpheus card may carry its own `tuning` ({temperature, top_p, top_k, min_p, // repeat_penalty, takes}, any of them) and `reading` (0 = the first; 1, 2, … // read the same words again differently) -- the editor's tts op's, checked // against the same ranges (yt-dlp-transcript-common/lib/ttsTuning.mjs). A card // without them is asked, and keyed, exactly as before. // // "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"; import { TTS_TUNING_FIELDS, normalizeTtsTuning, ttsReadingError, ttsTuningValueError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; /** 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", "tuning", "reading"]); // 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; /** * A narration's tuning as it is asked and keyed: the editor's normaliser * (lib/ttsTuning.mjs: quantised, a sampler value equal to Orpheus's default * dropped, in the registry's order), or null when nothing is left -- so a card * spelling a default asks and keys as one without it. `takes` is kept as * written: its default is the editor's settings, which a cut cannot see. */ export function narrationTuningOf(tuning) { const out = normalizeTtsTuning(tuning); return Object.keys(out).length ? out : null; } /** The problems with a tuning and a reading, as sentences, each naming where it is. */ export function tuningProblems(tuning, reading, where) { const out = []; if (tuning !== undefined && tuning !== null) { if (!isObj(tuning)) { out.push(`${where}.tuning must be an object of ${TTS_TUNING_FIELDS.join(", ")}`); } else { for (const [k, v] of Object.entries(tuning)) { if (!TTS_TUNING_FIELDS.includes(k)) out.push(`${where}.tuning.${k} is not a tuning field (${TTS_TUNING_FIELDS.join(", ")})`); else if (v !== null) { const p = ttsTuningValueError(k, v, `${where}.tuning.${k}`); if (p) out.push(p); } } } } if (reading !== undefined && reading !== null) { const p = ttsReadingError(reading, `${where}.reading`); if (p) out.push(p); } return out; } /** 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; const tuning = narrationTuningOf(n.tuning); return { text: String(n.text ?? "").trim(), engine: n.engine ?? r.engine, voice: n.voice ?? r.voice, speed: r.speed, // Only when asked: a card without them resolves -- and keys -- as it always did. ...(tuning ? { tuning } : {}), ...(Number.isInteger(n.reading) && n.reading > 0 ? { reading: n.reading } : {}), }; } /** * 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. A * tuning or a reading is in it only when the card asks for one. */ export function narrationKey({ text, engine, voice, speed, tuning = null, reading = 0 }) { const t = narrationTuningOf(tuning); return createHash("sha256") .update(JSON.stringify({ v: 1, text: String(text), engine, voice, speed: Number(speed), ...(t ? { tuning: t } : {}), ...(reading > 0 ? { reading } : {}) })) .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: `` 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 ?? "?"}`; // A post item's narration is post-narration.mjs's (its own shape and validator). if (e.narration !== undefined && e.narration !== null && e.type !== "post") { if (e.type !== "card") { errors.push(`${where}: narration is on cards and post items only (this is a ${e.type ?? "typeless"} entry)`); continue; } if (!isObj(e.narration)) { errors.push(`${where}.narration must be an object { text, voice?, engine?, tuning?, reading? }`); 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}`); } errors.push(...tuningProblems(e.narration.tuning, e.narration.reading, `${where}.narration`)); } 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; }