decklight 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +57 -24
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +1 -1
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +17 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/tools/video.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // decklight video deck.html -o deck.mp4
8
8
  // [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
9
- // [--build-hold <s>] [--theme <name>] [--slides a-b] [--voiceover]
9
+ // [--build-hold <s>] [--theme <name> | --gen <b64url>] [--slides a-b] [--voiceover]
10
10
  //
11
11
  // A still per FRAME — a narrated slide is one still, fully built, held for its
12
12
  // audio; a silent slide builds as it goes, one still per step — muxed with the
@@ -22,7 +22,7 @@
22
22
  // Capture is the tools/shot.mjs mechanism: one one-shot headless Chrome per
23
23
  // frame against the deck served over http://127.0.0.1 at #/n/999 (an oversized
24
24
  // step clamps to the last build, so every slide renders fully built). The deck
25
- // is served under the `present` CSP, NOT opened over file:// with
25
+ // is served under the `--no-trust` CSP, NOT opened over file:// with
26
26
  // --allow-file-access-from-files (#229): that flag let a deck's own JS read any
27
27
  // local file and exfiltrate it, and video renders decks you may not have
28
28
  // vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
@@ -40,9 +40,17 @@ import { promisify } from 'node:util';
40
40
  import { fileURLToPath } from 'node:url';
41
41
  import { chromeBin, chromeArgs } from './chrome.mjs';
42
42
  import { argReader, isMain } from './args.mjs';
43
- import { injectBeforeBodyEnd, sectionBodies, isHiddenSection } from './deck-html.mjs';
44
- import { serveForRender } from '../cli/present.mjs';
43
+ import { renderThemeParams } from './render-theme.mjs';
44
+ import { injectBeforeBodyEnd, sectionBodies, isHiddenSection, NOTES_ASIDE, cleanNotes, notesSegments } from './deck-html.mjs';
45
+ import { VIDEO_FORMATS, VIDEO_QUALITIES, VIDEO_SUBTITLES, valuesOf } from './video-options.mjs';
46
+ import { splitSentences, speechRuns, stripAudioTags, PAUSE_MARK, CLICK_MARK, canonMarks } from './sentences.mjs';
47
+ import { serveForRender } from '../cli/serve.mjs';
45
48
  import { run as runBounded, PROBE_MS } from './exec.mjs';
49
+ import { staleSlides, slideTexts, priorSlideTexts, slideNotes, markerPauses } from './narration-manifest.mjs';
50
+ import { synthesizeSlides, readTrack, trackFormat } from './narration-synth.mjs';
51
+ import { createEngine, engineStatus, engineBlocker, ENGINES, piperModelDir } from './tts-engines.mjs';
52
+ import { loadTtsConfig } from './tts-setup.mjs';
53
+ import { createTtsCache } from './tts-cache.mjs';
46
54
 
47
55
  const run = promisify(execFile);
48
56
 
@@ -51,9 +59,25 @@ export const TAIL_SECONDS = 0.4;
51
59
 
52
60
  const HELP = `decklight video <deck.html> [options] — render the deck to a narrated mp4
53
61
 
54
- -o, --out <file> output mp4 (default: <deck>.mp4 next to the deck)
62
+ -o, --out <file> output file (default: <deck>.mp4 next to the deck, or
63
+ <deck>.slides-a-b.mp4 for a --slides range; .mov/.webm
64
+ with --format)
55
65
  --narration <dir> narration dir (default: <deckdir>/voiceover if it has a
56
66
  manifest.json; otherwise the deck renders silent)
67
+ --no-narration render silent, even with a voiceover/ beside the deck
68
+ --allow-stale render although the narration was recorded from other
69
+ notes than the deck has now (the slides are still named)
70
+ — for what cannot be re-voiced; a machine-voiced track's
71
+ stale slides are re-voiced first (below)
72
+ --no-revoice leave a machine-voiced track's stale slides as they are:
73
+ refuse them, or render them old with --allow-stale
74
+ --format <f> mp4 (H.264/AAC, the default) · mov (H.264/AAC) · webm
75
+ (VP9/Opus); read off -o's extension when that names one
76
+ --quality <q> draft (quick, small) · standard (the default) · high
77
+ (slower to render, sharper, larger)
78
+ --subtitles <how> none (the default) · embed (a track the player can turn
79
+ on) · file (a .srt beside the video, .vtt for webm) —
80
+ what the narration says, timed against its audio
57
81
  --size <WxH> frame size (default 1280x720; both must be even)
58
82
  --fps <n> video frame rate (default 30)
59
83
  --hold <s> seconds a slide without narration holds (default 5;
@@ -64,12 +88,17 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
64
88
  --build-hold <s> seconds each build-up frame holds on a silent slide
65
89
  (default: the slide's own hold, so builds move at the
66
90
  pace the deck does)
67
- --theme <name> render with themes/<name>.css instead of the deck's theme
91
+ --theme <name> render in another theme — one of the deck's own, an added
92
+ one, or a themes/<name>.css file (rides ?theme=)
93
+ --gen <b64url> render in a theme that has no name the deck knows — a
94
+ custom or generated one, as {name, tokens} base64url JSON
95
+ (rides ?gen=; the export row sends it for you)
68
96
  --slides <a-b> only this slide range (1-based, inclusive)
69
- --voiceover run the voiceover batch (tools/voiceover.mjs) first
97
+ --voiceover run the voiceover batch (tools/voiceover.mjs) first —
98
+ over the --slides range only, when one is given
70
99
 
71
100
  Every slide BUILDS, one frame per step. A narrated slide takes its timing from
72
- its own audio: ⟨CLICK⟩ in the speaker notes splits the narration, and segment k
101
+ its own audio: [click] in the speaker notes splits the narration, and segment k
73
102
  is spoken over build step k — the same rule the live player follows. Without
74
103
  markers it holds fully built for the audio's real duration. A silent slide holds
75
104
  --hold seconds, --build-hold per step. Either way the audio track is continuous
@@ -100,6 +129,86 @@ export function parseSlideRange(s, total) {
100
129
  return { from, to };
101
130
  }
102
131
 
132
+ /**
133
+ * Where a render lands: `talk.mp4`, or `talk.slides-5-9.mp4` for a range — so
134
+ * five slides rendered to check a fix never overwrite the whole talk. The deck's
135
+ * export row writes the same name, because what a row writes is what this
136
+ * command writes.
137
+ */
138
+ export function videoOut(deck, slides = null, format = 'mp4') {
139
+ return `${deck.replace(/\.html?$/i, '')}${slides ? `.slides-${slides}` : ''}.${ENCODINGS[format]?.ext ?? 'mp4'}`;
140
+ }
141
+
142
+ /** The sidecar subtitles of a render: the video's name, with the container's own subtitle extension. */
143
+ export function subtitlesOut(out, format = 'mp4') {
144
+ return `${out.replace(/\.[^./\\]+$/, '')}.${ENCODINGS[format].subtitleExt}`;
145
+ }
146
+
147
+ /**
148
+ * --format, --quality and --subtitles, checked. The format is read off `-o`
149
+ * when only the file name says it, and a name and a flag that disagree are
150
+ * refused rather than settled: `-o talk.mp4 --format webm` would otherwise write
151
+ * a WebM that every player then refuses by its extension.
152
+ */
153
+ export function videoOptions({ out = null, format = null, quality = null, subtitles = null } = {}) {
154
+ const formats = valuesOf(VIDEO_FORMATS);
155
+ if (format != null && !formats.includes(format)) throw new Error(`--format must be ${formats.join(', ')} (got "${format}")`);
156
+ const named = out ? /\.([a-z0-9]+)$/i.exec(basename(out))?.[1]?.toLowerCase() ?? null : null;
157
+ if (format && named && named !== ENCODINGS[format].ext) {
158
+ throw new Error(`-o ${basename(out)} is not a .${ENCODINGS[format].ext} — drop --format, or name the file .${ENCODINGS[format].ext}`);
159
+ }
160
+ if (!format && named && !formats.includes(named)) {
161
+ throw new Error(`-o ${basename(out)}: .${named} is not a format this writes — use ${formats.map((f) => `.${f}`).join(', ')}`);
162
+ }
163
+ const qualities = valuesOf(VIDEO_QUALITIES);
164
+ if (quality != null && !qualities.includes(quality)) throw new Error(`--quality must be ${qualities.join(', ')} (got "${quality}")`);
165
+ const modes = valuesOf(VIDEO_SUBTITLES);
166
+ if (subtitles != null && !modes.includes(subtitles)) throw new Error(`--subtitles must be ${modes.join(', ')} (got "${subtitles}")`);
167
+ return { format: format ?? named ?? 'mp4', quality: quality ?? 'standard', subtitles: subtitles ?? 'none' };
168
+ }
169
+
170
+ /**
171
+ * Read this command's own output as progress: the plan line names how many
172
+ * slides the render covers, and each frame line names its slide. `onSlide(n, of)`
173
+ * fires once per slide, when its first frame is done — the edit server
174
+ * relays it to the deck's export row, which is how a render that takes minutes
175
+ * keeps saying where it is.
176
+ */
177
+ export function videoProgress(onSlide) {
178
+ let of = 0;
179
+ const seen = new Set();
180
+ return (line) => {
181
+ const head = /^\S.*: (\d+) slides?, \d+ narrated/.exec(line);
182
+ if (head) { of = Number(head[1]); return; }
183
+ const frame = /^\s+slide (\d+)[:\s·]/.exec(line);
184
+ if (frame && of && !seen.has(frame[1])) { seen.add(frame[1]); onSlide(seen.size, of); }
185
+ };
186
+ }
187
+
188
+ /**
189
+ * The same, for `tools/voiceover.mjs` when an export voices its slides first:
190
+ * its plan line ends `· N to voice`, and each slide line after it — synthesized,
191
+ * or kept from an earlier run — is one of those N done.
192
+ */
193
+ export function voiceoverProgress(onSlide) {
194
+ let of = 0;
195
+ let n = 0;
196
+ return (line) => {
197
+ const head = / · (\d+) to voice$/.exec(line);
198
+ if (head) { of = Number(head[1]); return; }
199
+ if (of && /^\s+slide \d+: /.test(line)) onSlide(++n, of);
200
+ };
201
+ }
202
+
203
+ /**
204
+ * argv for the `--voiceover` batch. The range rides along: rendering slides 5-9
205
+ * should not synthesise the other thirty, and on a paid engine that is a bill.
206
+ */
207
+ export function voiceoverArgs(deck, { narration, slides } = {}) {
208
+ return [fileURLToPath(new URL('./voiceover.mjs', import.meta.url)), deck,
209
+ ...(narration ? ['-o', resolve(narration)] : []), ...(slides ? ['--slides', slides] : [])];
210
+ }
211
+
103
212
  /** Per-slide hold seconds: data-video-hold="8" on the section, else the default. */
104
213
  export function extractHolds(html, defaultHold) {
105
214
  return sectionBodies(html).map((sec) => {
@@ -118,6 +227,26 @@ export function extractHolds(html, defaultHold) {
118
227
  */
119
228
  export const SLIDE_PAUSE_DEFAULT = 1;
120
229
 
230
+ /**
231
+ * Seconds of ⟨PAUSE⟩ hold each build step of each slide asks for (#560): the
232
+ * markers in the ⟨CLICK⟩ segments that step narrates, each two beat pauses
233
+ * (`markerPauses`). `steps[i]` is slide i+1's build count; the array for a
234
+ * slide has one entry per frame, the finished slide last. Segments fold the
235
+ * way the runtime's `stepAudio` folds them — empty ones kept, so segment k is
236
+ * step k, and every surplus segment on the last step.
237
+ *
238
+ * A render with narration has the holds IN its audio — the deck's recorder and
239
+ * the synthesis core both bake them — so only a SILENT frame reads this.
240
+ */
241
+ export function pauseMarks(html, steps = null) {
242
+ const holds = markerPauses(html);
243
+ return slideNotes(html).map((notes, i) => {
244
+ const segs = notes.split(CLICK_MARK).map((t) => t.split(PAUSE_MARK).length - 1);
245
+ const builds = steps?.[i] ?? 0;
246
+ return Array.from({ length: builds + 1 }, (_, k) => (k < builds ? segs[k] ?? 0 : segs.slice(k).reduce((a, b) => a + b, 0)) * holds[i]);
247
+ });
248
+ }
249
+
121
250
  /**
122
251
  * Per-slide narration beat: data-narration-pause="2" on the section, else
123
252
  * the built-in default above.
@@ -182,11 +311,13 @@ const round = (s) => Math.round(s * 1000) / 1000;
182
311
  * frame per slide); buildHold: seconds per
183
312
  * build-up frame (null ⇒ the slide's own hold);
184
313
  * pauses: per-slide data-narration-pause seconds
185
- * added to a NARRATED slide's finished frame
314
+ * added to a NARRATED slide's finished frame;
315
+ * marks: pauseMarks — ⟨PAUSE⟩ seconds per frame
316
+ * added to a SILENT one (narrated audio has them)
186
317
  * @returns {Array<{slide, step, audio, duration, pad}>} audio null ⇒ silent hold;
187
318
  * `pad` is the silence ffmpeg appends to the audio
188
319
  */
189
- export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, pauses = null, onWarn = null } = {}) {
320
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, pauses = null, marks = null, onWarn = null } = {}) {
190
321
  const from = range?.from ?? 1;
191
322
  const to = range?.to ?? holds.length;
192
323
  const plan = [];
@@ -237,15 +368,48 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
237
368
  plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + tail), pad: tail });
238
369
  continue;
239
370
  }
371
+ // No audio to carry them, so a silent frame holds its ⟨PAUSE⟩ markers
372
+ // itself — the same seconds a narrated one has baked into its file.
240
373
  const hold = holds[n - 1];
241
- if (!builds) { plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold }); continue; }
374
+ const mark = (k) => marks?.[n - 1]?.[k] ?? 0;
375
+ if (!builds) { plan.push({ slide: n, step: LAST_STEP, audio: null, duration: round(hold + mark(0)) }); continue; }
242
376
  const each = buildHold ?? hold;
243
- for (let k = 0; k < builds; k++) plan.push({ slide: n, step: k, audio: null, duration: each });
244
- plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold });
377
+ for (let k = 0; k < builds; k++) plan.push({ slide: n, step: k, audio: null, duration: round(each + mark(k)) });
378
+ plan.push({ slide: n, step: LAST_STEP, audio: null, duration: round(hold + mark(builds)) });
245
379
  }
246
380
  return plan;
247
381
  }
248
382
 
383
+ /**
384
+ * How each container is encoded, at each quality.
385
+ *
386
+ * `standard` for mp4 is what this command always wrote (x264's own defaults,
387
+ * AAC at 128k), so a render that asks for nothing comes out as it did. WebM is
388
+ * VP9 in constant-quality mode (`-b:v 0` is what makes `-crf` mean that) with
389
+ * Opus, which takes 48 kHz and nothing else — so its silent segments are
390
+ * synthesized at 48 kHz too, or the concat's `-c copy` audio would change rate
391
+ * mid-file. Draft trades VP9's quality search for speed (`realtime`), because a
392
+ * draft is for checking the timing, not the picture.
393
+ */
394
+ const X264 = { draft: { preset: 'veryfast', crf: '28' }, standard: { preset: 'medium', crf: '23' }, high: { preset: 'slow', crf: '18' } };
395
+ const VP9 = { draft: { crf: '40', deadline: 'realtime', cpu: '8' }, standard: { crf: '32', deadline: 'good', cpu: '4' }, high: { crf: '24', deadline: 'good', cpu: '2' } };
396
+ const AUDIO_KBPS = { draft: '96k', standard: '128k', high: '192k' };
397
+ const H264 = {
398
+ faststart: true, subtitleCodec: 'mov_text', subtitleExt: 'srt', sampleRate: 44100,
399
+ video: (q) => ['-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p', '-preset', X264[q].preset, '-crf', X264[q].crf],
400
+ audio: (q) => ['-c:a', 'aac', '-b:a', AUDIO_KBPS[q], '-ar', '44100', '-ac', '2'],
401
+ };
402
+ export const ENCODINGS = {
403
+ mp4: { ext: 'mp4', ...H264 },
404
+ mov: { ext: 'mov', ...H264 },
405
+ webm: {
406
+ ext: 'webm', faststart: false, subtitleCodec: 'webvtt', subtitleExt: 'vtt', sampleRate: 48000,
407
+ video: (q) => ['-c:v', 'libvpx-vp9', '-pix_fmt', 'yuv420p', '-b:v', '0', '-crf', VP9[q].crf,
408
+ '-deadline', VP9[q].deadline, '-cpu-used', VP9[q].cpu, '-row-mt', '1'],
409
+ audio: (q) => ['-c:a', 'libopus', '-b:a', AUDIO_KBPS[q], '-ar', '48000', '-ac', '2'],
410
+ },
411
+ };
412
+
249
413
  /**
250
414
  * ffmpeg argv for one slide's segment: the still looped at --fps under its
251
415
  * audio. Narrated slides pad the audio with `pad` — the tail, plus whatever
@@ -255,15 +419,15 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
255
419
  * goes discontinuous. -t bounds both the infinite loop and the infinite
256
420
  * anullsrc (-shortest can't end a segment whose streams are both endless).
257
421
  */
258
- export function segmentArgs({ frame, audio, duration, fps, out, pad = TAIL_SECONDS }) {
422
+ export function segmentArgs({ frame, audio, duration, fps, out, pad = TAIL_SECONDS, format = 'mp4', quality = 'standard' }) {
423
+ const enc = ENCODINGS[format];
259
424
  return [
260
425
  '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
261
426
  ...(audio
262
427
  ? ['-i', audio, '-af', `apad=pad_dur=${pad}`]
263
- : ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
264
- '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
265
- '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
266
- '-t', Number(duration).toFixed(3), '-movflags', '+faststart', out,
428
+ : ['-f', 'lavfi', '-i', `anullsrc=channel_layout=stereo:sample_rate=${enc.sampleRate}`]),
429
+ ...enc.video(quality), ...enc.audio(quality),
430
+ '-t', Number(duration).toFixed(3), ...(enc.faststart ? ['-movflags', '+faststart'] : []), out,
267
431
  ];
268
432
  }
269
433
 
@@ -272,10 +436,110 @@ export function concatList(segments) {
272
436
  return segments.map((s) => `file '${s.replaceAll("'", "'\\''")}'`).join('\n') + '\n';
273
437
  }
274
438
 
275
- /** ffmpeg argv joining the segments into the output without re-encoding. */
276
- export function concatArgs(listFile, out) {
277
- return ['-y', '-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy',
278
- '-movflags', '+faststart', out];
439
+ /**
440
+ * ffmpeg argv joining the segments into the output without re-encoding — and,
441
+ * when there are subtitles to embed, mapping them in as a track of the
442
+ * container's own kind (the only step that encodes anything, and it is text).
443
+ */
444
+ export function concatArgs(listFile, out, { format = 'mp4', subtitles = null } = {}) {
445
+ const enc = ENCODINGS[format];
446
+ return ['-y', '-f', 'concat', '-safe', '0', '-i', listFile,
447
+ ...(subtitles ? ['-i', subtitles, '-map', '0', '-map', '1'] : []),
448
+ '-c', 'copy', ...(subtitles ? ['-c:s', enc.subtitleCodec] : []),
449
+ ...(enc.faststart ? ['-movflags', '+faststart'] : []), out];
450
+ }
451
+
452
+ /** A subtitle longer than this is split into cues of its own; two lines of about half each is what a player shows. */
453
+ export const CUE_MAX_CHARS = 84;
454
+
455
+ /** Words into runs of at most `max` characters, never mid-word. */
456
+ function chunkCue(text, max) {
457
+ if (text.length <= max) return [text];
458
+ const out = [];
459
+ let line = '';
460
+ for (const word of text.split(' ')) {
461
+ if (line && line.length + 1 + word.length > max) { out.push(line); line = word; } else line = line ? `${line} ${word}` : word;
462
+ }
463
+ if (line) out.push(line);
464
+ return out;
465
+ }
466
+
467
+ /** One cue's text on at most two lines, broken at the space nearest the middle. */
468
+ function wrapCue(text, line = CUE_MAX_CHARS / 2) {
469
+ if (text.length <= line) return text;
470
+ const mid = text.length / 2;
471
+ let at = -1;
472
+ for (let i = text.indexOf(' '); i >= 0; i = text.indexOf(' ', i + 1)) if (at < 0 || Math.abs(i - mid) < Math.abs(at - mid)) at = i;
473
+ return at < 0 ? text : `${text.slice(0, at)}\n${text.slice(at + 1)}`;
474
+ }
475
+
476
+ /**
477
+ * The subtitles of a render: what each narrated frame SAYS, timed against the
478
+ * frame's real audio.
479
+ *
480
+ * The unit is the sentence, split by the very function the live captions use
481
+ * (`splitSentences`, tools/sentences.mjs), so a video's subtitles break
482
+ * where the deck's captions do. Within one beat the audio is ONE file, so
483
+ * where a sentence starts inside it is not known — it is shared out by length,
484
+ * which lands close for speech and is exact at every beat boundary. The breath
485
+ * after a slide (`pad`) carries no caption, and a silent frame none at all.
486
+ * Nor does a ⟨PAUSE⟩ (#560): the script beside a clip keeps its markers, and
487
+ * each one is `holdOf(frame)` seconds of the clip's silence — taken out of the
488
+ * time shared among the words, and left uncaptioned where it falls.
489
+ *
490
+ * @param plan planTimeline's frames, in order
491
+ * @param textOf frame → the words its audio speaks, ⟨PAUSE⟩ markers and all
492
+ * @param holdOf frame → seconds one ⟨PAUSE⟩ holds on its slide
493
+ * @returns {Array<{start, end, text}>} seconds from the start of the video
494
+ */
495
+ export function subtitleCues(plan, textOf, holdOf = () => 0) {
496
+ const cues = [];
497
+ let t = 0;
498
+ for (const p of plan) {
499
+ const speech = p.audio ? Math.max(0, p.duration - (p.pad ?? 0)) : 0;
500
+ const { lead, runs } = speechRuns(speech ? String(textOf(p) ?? '') : '');
501
+ const hold = runs.length ? holdOf(p) : 0;
502
+ const held = hold * (lead + runs.reduce((n, r) => n + r.pause, 0));
503
+ const spoken = Math.max(0, speech - held);
504
+ // pieces of { text, weight }, each run's then its hold
505
+ const cut = runs.map((r) => ({
506
+ // an audio tag is direction for the voice, never a subtitle
507
+ pieces: splitSentences(r.text).map(stripAudioTags).filter(Boolean).flatMap((s) => chunkCue(s, CUE_MAX_CHARS))
508
+ .map((text) => ({ text, weight: text.length })),
509
+ pause: r.pause,
510
+ }));
511
+ const total = cut.reduce((n, c) => n + c.pieces.reduce((m, x) => m + x.weight, 0), 0);
512
+ let at = t + lead * hold;
513
+ for (const c of cut) {
514
+ for (const piece of c.pieces) {
515
+ const len = spoken * (piece.weight / total);
516
+ cues.push({ start: round(at), end: round(at + len), text: wrapCue(piece.text) });
517
+ at += len;
518
+ }
519
+ at += c.pause * hold;
520
+ }
521
+ t += p.duration;
522
+ }
523
+ return cues;
524
+ }
525
+
526
+ const stamp = (s, mark) => {
527
+ const ms = Math.round(s * 1000);
528
+ const two = (n) => String(n).padStart(2, '0');
529
+ return `${two(Math.floor(ms / 3600000))}:${two(Math.floor(ms / 60000) % 60)}:${two(Math.floor(ms / 1000) % 60)}${mark}${String(ms % 1000).padStart(3, '0')}`;
530
+ };
531
+ // An arrow inside a line would read as a timing line to a strict parser.
532
+ const safeCue = (text) => text.replaceAll('-->', '→');
533
+
534
+ /** SubRip: numbered cues, comma before the milliseconds. */
535
+ export function toSrt(cues) {
536
+ return cues.map((c, i) => `${i + 1}\n${stamp(c.start, ',')} --> ${stamp(c.end, ',')}\n${safeCue(c.text).replaceAll('<', '‹')}\n`).join('\n');
537
+ }
538
+
539
+ /** WebVTT: a header, a dot before the milliseconds, and `<` / `&` escaped — cue text is markup there. */
540
+ export function toVtt(cues) {
541
+ const esc = (t) => safeCue(t).replaceAll('&', '&amp;').replaceAll('<', '&lt;');
542
+ return `WEBVTT\n\n${cues.map((c) => `${stamp(c.start, '.')} --> ${stamp(c.end, '.')}\n${esc(c.text)}\n`).join('\n')}`;
279
543
  }
280
544
 
281
545
  /** ffprobe argv for a file's real duration in seconds (prints one number). */
@@ -303,12 +567,86 @@ export function resolveNarration(deckPath, narrationDir) {
303
567
  if (!Array.isArray(m?.slides)) {
304
568
  throw new Error(`${path}: not a voiceover manifest (no slides array) — regenerate it with tools/voiceover.mjs`);
305
569
  }
306
- return { dir, slides: m.slides };
570
+ // the header rides along: the freshness check hashes the deck's notes under it
571
+ return { dir, slides: m.slides, engine: m.engine, model: m.model, voice: m.voice, style: m.style };
307
572
  };
308
573
  if (narrationDir) return load(resolve(narrationDir), true);
309
574
  return load(join(resolve(deckPath, '..'), 'voiceover'), false);
310
575
  }
311
576
 
577
+ /**
578
+ * Re-voice a machine-voiced track's stale slides, before a render (#553).
579
+ *
580
+ * A slide whose notes changed since it was voiced would speak against its own
581
+ * captions, so the render refuses it (#536). When the track was voiced by an
582
+ * ENGINE — its manifest header names one — and that engine is available here,
583
+ * the refusal has an obvious fix the render can make itself: voice just those
584
+ * slides again, in the track's own engine, model, voice and style, into its
585
+ * own format and file names. That is a range-scoped call into the one
586
+ * synthesis core every producer of a track shares (tools/narration-synth.mjs,
587
+ * #555), so the refreshed slide is exactly what `voiceover` or the deck's
588
+ * recorder would have written, and the freshness check it then passes is the
589
+ * same hash.
590
+ *
591
+ * Returns `{ ok: true }` once every stale slide is voiced, or `{ ok: false,
592
+ * why }` for a track that cannot be re-voiced — a human take (no engine), or an
593
+ * engine this machine cannot run (no key, no model) — naming what is missing.
594
+ * Before any synthesis it says how many clips it will ask for, from which
595
+ * engine: on a cloud engine that is money, and the clip cache makes any
596
+ * sentence already paid for free.
597
+ */
598
+ export async function revoiceStale({
599
+ html, narration, stale, log = console.log, env = process.env,
600
+ create = createEngine, status = engineStatus, cache = createTtsCache(),
601
+ }) {
602
+ const { dir, engine } = narration;
603
+ if (!engine || !ENGINES.includes(engine)) {
604
+ return { ok: false, why: `${basename(dir)}/ names no engine it was voiced with — a take in somebody's own voice is re-recorded, not re-voiced` };
605
+ }
606
+ // the engine's settings as the edit server passes them to voiceover: the
607
+ // environment, then tts.json for THIS engine
608
+ const saved = loadTtsConfig(env);
609
+ const savedFor = saved?.engine === engine ? saved : null;
610
+ const project = env.GOOGLE_CLOUD_PROJECT ?? saved?.project ?? null;
611
+ const dataDir = savedFor?.dataDir ?? (engine === 'piper' ? piperModelDir(env) : null);
612
+ const voice = narration.voice ?? undefined;
613
+ const st = status(engine, { env, project, dataDir, voice: engine === 'piper' ? (voice ?? narration.model) : voice });
614
+ if (!st.ready) {
615
+ const b = engineBlocker(st, { env });
616
+ return { ok: false, why: `it was voiced by ${engine}, which ${b ? `${b.why} — ${b.fix}` : `is not available here (${st.reason})`}` };
617
+ }
618
+ let tts;
619
+ try {
620
+ tts = create({
621
+ engine, voice, project, dataDir, env,
622
+ // the model is identity only where an engine has more than one per voice
623
+ model: engine === 'elevenlabs' || engine === 'gemini' ? (narration.model ?? undefined) : undefined,
624
+ format: savedFor?.format,
625
+ });
626
+ } catch (e) {
627
+ return { ok: false, why: `it was voiced by ${engine}, which cannot start here — ${e.message}` };
628
+ }
629
+ try {
630
+ const raw = slideNotes(html);
631
+ const clips = stale.reduce((sum, n) => sum + (notesSegments(raw[n - 1] ?? '')?.length ?? 1), 0);
632
+ log(` re-voicing ${stale.length === 1 ? `slide ${stale[0]}` : `slides ${stale.join(', ')}`} in the track's own voice — `
633
+ + `${clips} clip${clips === 1 ? '' : 's'} from ${engine}${voice ? ` (${voice})` : ''}`
634
+ + `${typeof tts.cost === 'string' ? `, ${tts.cost}` : ''}; any sentence already voiced comes from the clip cache`);
635
+ for (const n of stale) {
636
+ const prev = readTrack(dir);
637
+ await synthesizeSlides({
638
+ html, dir, tts, voice, style: narration.style ?? undefined,
639
+ format: trackFormat(prev) ?? 'wav', range: { from: n, to: n }, prev, cache, log,
640
+ });
641
+ }
642
+ return { ok: true };
643
+ } catch (e) {
644
+ return { ok: false, why: e.message };
645
+ } finally {
646
+ tts.synth.close?.();
647
+ }
648
+ }
649
+
312
650
  const have = (bin) => {
313
651
  try { runBounded(bin, ['-version'], { stdio: 'ignore', timeout: PROBE_MS }); return true; }
314
652
  catch (e) { return e?.code !== 'ENOENT'; }
@@ -343,8 +681,17 @@ const STEP_PROBE = `<script>
343
681
  })();
344
682
  </script>`;
345
683
 
346
- /** Make the deck's instance reachable, the way test/import-render.mjs does. */
347
- const exposeInstance = (html) => html.replace(/\bDecklight\s*\.\s*init\s*\(/, 'window.__decklightProbe = Decklight.init(');
684
+ /**
685
+ * Make the deck's instance reachable, the way test/import-render.mjs does: a
686
+ * deck that boots itself from its `init` call has the call's result exposed; a
687
+ * deck as data (#520) boots itself, so the probe reads the instance off the
688
+ * stage — lazily, since the engine is served into the page after this runs.
689
+ */
690
+ const PROBE_GETTER = '<script>Object.defineProperty(window, "__decklightProbe", { get: () => document.querySelector(".decklight")?.__decklight });</script>\n';
691
+ const exposeInstance = (html) => {
692
+ const out = html.replace(/\bDecklight\s*\.\s*init\s*\(/, 'window.__decklightProbe = Decklight.init(');
693
+ return out !== html ? out : (injectBeforeBodyEnd(html, PROBE_GETTER) ?? html);
694
+ };
348
695
 
349
696
  /** Parse the probe's answer out of a dumped DOM; null when it did not report. */
350
697
  export function parseBuildSteps(dom, slides) {
@@ -373,7 +720,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
373
720
 
374
721
  // The served root is the directory you run from — the deck must sit inside it
375
722
  // so its relative assets (`../dist/decklight.js`, `themes/…`) resolve as URLs
376
- // off the loopback origin the frames are captured against. This is `present`'s
723
+ // off the loopback origin the frames are captured against. This is the no-trust mode's
377
724
  // rule, for the same reason (#229): the deck runs under the CSP, and a read
378
725
  // cannot escape the served tree. `cd` to a directory containing the deck.
379
726
  const root = process.cwd();
@@ -392,7 +739,11 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
392
739
 
393
740
  let out; let plan; let narration;
394
741
  try {
395
- out = resolve(opt('-o', opt('--out', deck.replace(/\.html?$/i, '.mp4'))));
742
+ const named = opt('-o', opt('--out'));
743
+ const { format, quality, subtitles } = videoOptions({
744
+ out: named, format: opt('--format'), quality: opt('--quality'), subtitles: opt('--subtitles'),
745
+ });
746
+ out = resolve(named ?? videoOut(deck, opt('--slides'), format));
396
747
  const { w, h } = parseSize(opt('--size', '1280x720'));
397
748
  const fps = Number(opt('--fps', '30'));
398
749
  const hold = Number(opt('--hold', '5'));
@@ -404,6 +755,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
404
755
  throw new Error(`--build-hold must be positive seconds`);
405
756
  }
406
757
  const theme = opt('--theme');
758
+ const themeParams = renderThemeParams({ theme, gen: opt('--gen') }); // throws on a bad value, before any work
407
759
 
408
760
  const html = readFileSync(deck, 'utf8');
409
761
  const holds = extractHolds(html, hold);
@@ -412,14 +764,45 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
412
764
  const range = parseSlideRange(opt('--slides'), holds.length);
413
765
 
414
766
  if (argv.includes('--voiceover')) {
415
- const vo = [fileURLToPath(new URL('./voiceover.mjs', import.meta.url)), deck];
416
- const nd = opt('--narration');
417
- if (nd) vo.push('-o', resolve(nd));
767
+ const vo = voiceoverArgs(deck, { narration: opt('--narration'), slides: opt('--slides') });
418
768
  const r = spawnSync(process.execPath, vo, { stdio: 'inherit' });
419
769
  if (r.status !== 0) throw new Error('voiceover batch failed — see its output above');
420
770
  }
421
771
 
422
- narration = resolveNarration(deck, opt('--narration'));
772
+ // --no-narration is silence asked for by name: without it, a voiceover/
773
+ // beside the deck narrates whether or not that was the voice wanted
774
+ narration = argv.includes('--no-narration') ? null : resolveNarration(deck, opt('--narration'));
775
+ // Is the track still THIS deck's notes? Each manifest slide carries the
776
+ // hash of the notes it was voiced from; a slide whose notes moved since
777
+ // would speak against its own captions, so it is named and, unless asked
778
+ // for by name, refused (#536). Only the slides being rendered are checked.
779
+ if (narration) {
780
+ let { stale, hashless } = staleSlides(narration, slideTexts(html), range, priorSlideTexts(html));
781
+ if (hashless) log(` narration: ${hashless} slide${hashless === 1 ? '' : 's'} in ${basename(narration.dir)}/ carr${hashless === 1 ? 'ies' : 'y'} no notes hash (recorded by hand) — not checked`);
782
+ for (const n of stale) console.warn(` slide ${n}: narration was recorded from different notes`);
783
+ // A machine-voiced track fixes itself: its stale slides are voiced again
784
+ // in its own voice, and the check runs again on what that wrote (#553).
785
+ let unrevoiced = null;
786
+ if (stale.length && !argv.includes('--no-revoice')) {
787
+ const r = await revoiceStale({ html, narration, stale, log });
788
+ if (r.ok) {
789
+ narration = resolveNarration(deck, narration.dir);
790
+ ({ stale } = staleSlides(narration, slideTexts(html), range, priorSlideTexts(html)));
791
+ } else {
792
+ unrevoiced = r.why;
793
+ console.warn(` not re-voiced: ${r.why}`);
794
+ }
795
+ }
796
+ if (stale.length) {
797
+ const which = stale.length === 1 ? `slide ${stale[0]}` : `slides ${stale.join(', ')}`;
798
+ if (!argv.includes('--allow-stale')) {
799
+ throw new Error(`the narration in ${narration.dir} was recorded from older notes on ${which}`
800
+ + `${unrevoiced ? ` and cannot be re-voiced here: ${unrevoiced}` : ''} — `
801
+ + `re-record those slides (V → Record this deck… → slides ${stale[0]}-${stale[stale.length - 1]}) or pass --allow-stale`);
802
+ }
803
+ console.warn(` --allow-stale: rendering ${which} with the older narration`);
804
+ }
805
+ }
423
806
 
424
807
  // real durations, not the manifest's word count: ffprobe each audio file
425
808
  const durations = {};
@@ -444,18 +827,19 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
444
827
  }
445
828
 
446
829
 
447
- // --theme rides on the deck's response in memory (no temp file): only the
448
- // deck itself gets the injected link; every other html asset under the root
449
- // is served untouched. Over the loopback origin `themes/…` resolves exactly
450
- // as the sibling-copy path used to, so a themed render is unchanged.
830
+ // --theme rides the deck URL as `?theme=` — the runtime's own startup
831
+ // override, as `decklight pdf` has always used it — so it reaches every
832
+ // kind of theme a deck can hold: one of its inline blocks, an added one, or
833
+ // a themes/<name>.css file. It used to inject a <link> to that file, which
834
+ // on a deck whose themes are inline blocks (every `upgrade --link` deck)
835
+ // pointed at nothing, and the render came out in the first block (#547).
836
+ // …and every load is declared a render (`?capture`, #548). --gen rides
837
+ // `?gen=` the same way, for a theme that lives only in a browser.
838
+ const renderQuery = `?${['capture', ...themeParams].join('&')}`;
451
839
  let probing = false;
452
840
  const inject = (text, file) => {
453
- if (resolve(file) !== deck) return text;
454
- let out = theme
455
- ? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`)
456
- : text;
457
- if (probing) out = injectBeforeBodyEnd(exposeInstance(out), STEP_PROBE) ?? out;
458
- return out;
841
+ if (resolve(file) !== deck || !probing) return text;
842
+ return injectBeforeBodyEnd(exposeInstance(text), STEP_PROBE) ?? text;
459
843
  };
460
844
  const deckPath = '/' + relative(root, deck).split(sep).join('/');
461
845
 
@@ -473,7 +857,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
473
857
  try {
474
858
  const dom = await exec(chrome, chromeArgs(
475
859
  '--hide-scrollbars', `--window-size=${w},${h}`,
476
- '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}`,
860
+ '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}${renderQuery}`,
477
861
  ), { maxBuffer: 64 * 1024 * 1024 });
478
862
  steps = parseBuildSteps(dom.stdout, holds.length);
479
863
  } catch { /* fall through to one frame per slide */ }
@@ -481,7 +865,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
481
865
  if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
482
866
 
483
867
  plan = planTimeline(narration?.slides ?? null, durations, holds, range,
484
- { steps, buildHold, pauses, onWarn: (w) => console.warn(` ${w}`) });
868
+ { steps, buildHold, pauses, marks: pauseMarks(html, steps), onWarn: (w) => console.warn(` ${w}`) });
485
869
  const slideCount = new Set(plan.map((p) => p.slide)).size;
486
870
  log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
487
871
  + `${plan.filter((p) => p.audio).length} narrated`
@@ -494,19 +878,21 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
494
878
  const nn = String(p.slide).padStart(2, '0');
495
879
  const id = `${nn}-${String(f++).padStart(3, '0')}`;
496
880
  const frame = join(work, `frame-${id}.png`);
497
- // one one-shot Chrome per frame; LAST_STEP clamps to the last build
881
+ // one one-shot Chrome per frame; LAST_STEP clamps to the last build.
882
+ // `?capture` says it is a render: every frame is a fresh load, and
883
+ // without it each one greeted the viewer with the voice-over hint (#548)
498
884
  await exec(chrome, chromeArgs(
499
885
  '--hide-scrollbars',
500
886
  '--autoplay-policy=no-user-gesture-required',
501
887
  `--window-size=${w},${h}`,
502
888
  '--virtual-time-budget=1500',
503
889
  `--screenshot=${frame}`,
504
- `${server.origin}${deckPath}#/${p.slide}/${p.step}`,
890
+ `${server.origin}${deckPath}${renderQuery}#/${p.slide}/${p.step}`,
505
891
  ));
506
892
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
507
- const seg = join(work, `seg-${id}.mp4`);
893
+ const seg = join(work, `seg-${id}.${ENCODINGS[format].ext}`);
508
894
  await exec('ffmpeg', segmentArgs({
509
- frame, duration: p.duration, pad: p.pad, fps, out: seg,
895
+ frame, duration: p.duration, pad: p.pad, fps, out: seg, format, quality,
510
896
  audio: p.audio ? join(narration.dir, p.audio) : null,
511
897
  }));
512
898
  segments.push(seg);
@@ -514,9 +900,36 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
514
900
  log(` slide ${nn}${where}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
515
901
  }
516
902
 
903
+ // Subtitles are the words the audio speaks: the script voiceover wrote
904
+ // beside each clip when there is one (it may have been edited to change
905
+ // what is said), the deck's own notes for that beat when there is not.
906
+ let embedded = null;
907
+ if (subtitles !== 'none') {
908
+ const sections = sectionBodies(html);
909
+ const textOf = (p) => {
910
+ const script = join(narration.dir, p.audio.replace(/\.[^.]+$/, '.txt'));
911
+ // an edited script may spell its markers the way a person does — `[pause]`
912
+ if (existsSync(script)) return canonMarks(readFileSync(script, 'utf8'));
913
+ const notes = sections[p.slide - 1]?.match(NOTES_ASIDE)?.[1] ?? '';
914
+ const k = narration.slides?.[p.slide - 1]?.segments?.findIndex((sg) => sg.file === p.audio) ?? -1;
915
+ return k >= 0 ? (notesSegments(notes, { marks: true })?.[k] ?? '') : cleanNotes(notes, { marks: true });
916
+ };
917
+ const markHolds = markerPauses(html);
918
+ const cues = narration ? subtitleCues(plan, textOf, (p) => markHolds[p.slide - 1] ?? 0) : [];
919
+ const enc = ENCODINGS[format];
920
+ if (!cues.length) {
921
+ console.warn(' subtitles: nothing is spoken in this render — none written');
922
+ } else {
923
+ const file = subtitles === 'embed' ? join(work, `subtitles.${enc.subtitleExt}`) : subtitlesOut(out, format);
924
+ writeFileSync(file, enc.subtitleExt === 'vtt' ? toVtt(cues) : toSrt(cues));
925
+ if (subtitles === 'embed') embedded = file;
926
+ log(` subtitles: ${cues.length} cue${cues.length === 1 ? '' : 's'} ${subtitles === 'embed' ? 'embedded' : `→ ${file}`}`);
927
+ }
928
+ }
929
+
517
930
  const list = join(work, 'concat.txt');
518
931
  writeFileSync(list, concatList(segments));
519
- await exec('ffmpeg', concatArgs(list, out));
932
+ await exec('ffmpeg', concatArgs(list, out, { format, subtitles: embedded }));
520
933
  } finally {
521
934
  await server.close();
522
935
  rmSync(work, { recursive: true, force: true });