decklight 0.8.1 → 0.10.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 (138) hide show
  1. package/PLATFORM.md +707 -0
  2. package/README.md +226 -150
  3. package/SPEC.md +803 -888
  4. package/cli/agent-review.mjs +246 -0
  5. package/cli/agents.mjs +35 -9
  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 +190 -0
  10. package/cli/bundle-module.mjs +95 -0
  11. package/cli/bundle.mjs +439 -35
  12. package/cli/cast.mjs +48 -12
  13. package/cli/check-fixes.mjs +186 -0
  14. package/cli/check.mjs +988 -0
  15. package/cli/clone-deck.mjs +179 -0
  16. package/cli/commands.mjs +345 -0
  17. package/cli/comments.mjs +64 -18
  18. package/cli/commit-flow.mjs +51 -22
  19. package/cli/commit-message.mjs +51 -74
  20. package/cli/commit-split.mjs +601 -0
  21. package/cli/deck-refs.mjs +64 -0
  22. package/cli/deck-routes.mjs +67 -0
  23. package/cli/deckfile.mjs +3 -5
  24. package/cli/decklight.mjs +68 -289
  25. package/cli/design-system-deps.mjs +209 -0
  26. package/cli/design-system-edit.mjs +194 -0
  27. package/cli/design-system-refs.mjs +666 -0
  28. package/cli/design-system.mjs +497 -0
  29. package/cli/doctor.mjs +115 -0
  30. package/cli/edit-git.mjs +353 -0
  31. package/cli/edit-handover.mjs +551 -0
  32. package/cli/edit-look.mjs +631 -0
  33. package/cli/edit-slides.mjs +683 -0
  34. package/cli/edit.mjs +2585 -855
  35. package/cli/enhance.mjs +485 -0
  36. package/cli/extension.mjs +10 -10
  37. package/cli/font-refs.mjs +273 -0
  38. package/cli/font.mjs +246 -0
  39. package/cli/git-tree.mjs +1 -1
  40. package/cli/git.mjs +78 -11
  41. package/cli/import.mjs +56 -10
  42. package/cli/init.mjs +407 -236
  43. package/cli/library.mjs +127 -0
  44. package/cli/loader.mjs +3 -1
  45. package/cli/marketplace-autocheck.mjs +200 -0
  46. package/cli/marketplace.mjs +460 -29
  47. package/cli/narrate.mjs +251 -0
  48. package/cli/open-browser.mjs +63 -0
  49. package/cli/open.mjs +961 -0
  50. package/cli/pdf.mjs +64 -17
  51. package/cli/pkg.mjs +44 -2
  52. package/cli/plugin.mjs +43 -41
  53. package/cli/port-conflict.mjs +53 -23
  54. package/cli/pptx-export.mjs +63 -27
  55. package/cli/publish.mjs +8 -4
  56. package/cli/qr.mjs +1 -1
  57. package/cli/record.mjs +85 -23
  58. package/cli/remote.mjs +43 -17
  59. package/cli/restore.mjs +11 -4
  60. package/cli/review-ref.mjs +125 -0
  61. package/cli/review-remote.mjs +92 -48
  62. package/cli/review-routes.mjs +254 -0
  63. package/cli/review-store.mjs +47 -7
  64. package/cli/review-submit.mjs +47 -57
  65. package/cli/runtime-link.mjs +560 -0
  66. package/cli/serve.mjs +236 -45
  67. package/cli/setup.mjs +112 -0
  68. package/cli/sign.mjs +1 -1
  69. package/cli/skill-content.mjs +229 -35
  70. package/cli/skills.mjs +353 -26
  71. package/cli/start.mjs +110 -0
  72. package/cli/supervise.mjs +6 -6
  73. package/cli/theme-refs.mjs +527 -0
  74. package/cli/theme.mjs +181 -137
  75. package/cli/trust.mjs +83 -0
  76. package/cli/units.mjs +112 -47
  77. package/cli/update-check.mjs +1 -5
  78. package/cli/upgrade.mjs +194 -28
  79. package/cli/upstream.mjs +4 -3
  80. package/cli/util.mjs +4 -4
  81. package/cli/wizard.mjs +6 -6
  82. package/dist/build-info.json +1 -1
  83. package/dist/decklight.css +1533 -59
  84. package/dist/decklight.js +258 -115
  85. package/dist/decklight.js.map +4 -4
  86. package/docs/GLOSSARY.md +141 -0
  87. package/docs/architecture.svg +17 -17
  88. package/package.json +4 -2
  89. package/themes/README.md +9 -8
  90. package/themes/reveal-solarized.css +10 -0
  91. package/tools/args.mjs +20 -0
  92. package/tools/atomic-write.mjs +48 -0
  93. package/tools/brand-palette.mjs +717 -0
  94. package/tools/bridge.mjs +1 -1
  95. package/tools/build-groups.mjs +42 -0
  96. package/tools/color.mjs +48 -0
  97. package/tools/deck-html.mjs +396 -11
  98. package/tools/design-system-format.mjs +778 -0
  99. package/tools/design-system-migrations.mjs +207 -0
  100. package/tools/elevenlabs-tts.mjs +110 -17
  101. package/tools/exec.mjs +11 -3
  102. package/tools/extension-check.mjs +31 -7
  103. package/tools/font-format.mjs +190 -0
  104. package/tools/font-stacks.mjs +24 -0
  105. package/tools/gemini-tts.mjs +3 -0
  106. package/tools/lipsync-config.mjs +103 -0
  107. package/tools/lipsync-engines.mjs +205 -2
  108. package/tools/lipsync-server.mjs +264 -41
  109. package/tools/lipsync.mjs +37 -18
  110. package/tools/local-voice.mjs +32 -42
  111. package/tools/narration-manifest.mjs +270 -0
  112. package/tools/narration-synth.mjs +416 -0
  113. package/tools/pptx.mjs +776 -19
  114. package/tools/publish-targets.mjs +1 -1
  115. package/tools/publish-voices.mjs +3 -3
  116. package/tools/recording-impact.mjs +7 -3
  117. package/tools/render-theme.mjs +33 -0
  118. package/tools/review-anchor.mjs +28 -12
  119. package/tools/semver.mjs +40 -0
  120. package/tools/sentences.mjs +180 -0
  121. package/tools/shot.mjs +14 -7
  122. package/tools/site-clip.mjs +114 -0
  123. package/tools/site-voices.mjs +232 -0
  124. package/tools/template-theme.mjs +1 -1
  125. package/tools/test-impact.mjs +17 -10
  126. package/tools/theme-check.mjs +30 -3
  127. package/tools/tts-cache.mjs +4 -3
  128. package/tools/tts-engines.mjs +38 -20
  129. package/tools/tts-setup.mjs +7 -7
  130. package/tools/video-options.mjs +34 -0
  131. package/tools/video.mjs +530 -54
  132. package/tools/voiceover-server.mjs +185 -104
  133. package/tools/voiceover.mjs +119 -261
  134. package/tools/zip.mjs +1 -1
  135. package/cli/dev.mjs +0 -623
  136. package/cli/present.mjs +0 -853
  137. package/cli/review.mjs +0 -361
  138. 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:
@@ -33,16 +33,24 @@
33
33
  // written here would be a copy that drifts.
34
34
 
35
35
  import { execFile, spawnSync } from 'node:child_process';
36
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
36
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
37
  import { tmpdir } from 'node:os';
38
38
  import { basename, join, relative, resolve, sep } from 'node:path';
39
39
  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). */
@@ -285,8 +549,48 @@ export function ffprobeArgs(file) {
285
549
  }
286
550
 
287
551
  /**
288
- * Where the narration lives: --narration <dir> (its manifest is then required)
289
- * → <deckdir>/voiceover/manifest.json → null (a silent deck).
552
+ * A folder recorded by hand, read off the disk: what a manifest would say
553
+ * about its files, and nothing it would say about the notes. Your own voice
554
+ * (`narrate --mic`) wrote no manifest, and a folder of `slide-NN.wav` with its
555
+ * `slide-NN-KK.wav` beats is everything a render plays; with no hash per
556
+ * slide, the freshness check counts it as hand-recorded and says so.
557
+ * Null when the folder holds no whole-slide audio at all.
558
+ */
559
+ export function folderNarration(dir) {
560
+ let names;
561
+ try { names = readdirSync(dir); } catch { return null; }
562
+ const EXT = ['wav', 'm4a', 'mp3']; // a folder holding two, the recorder's first
563
+ const whole = new Map();
564
+ const beats = new Map();
565
+ for (const f of names) {
566
+ const m = /^slide-(\d+)(?:-(\d+))?\.(wav|m4a|mp3)$/.exec(f);
567
+ if (!m) continue;
568
+ const n = Number(m[1]);
569
+ if (m[2] == null) {
570
+ const had = whole.get(n);
571
+ if (!had || EXT.indexOf(m[3]) < EXT.indexOf(had.split('.').pop())) whole.set(n, f);
572
+ } else {
573
+ if (!beats.has(n)) beats.set(n, new Map());
574
+ const k = Number(m[2]);
575
+ const had = beats.get(n).get(k);
576
+ if (!had || EXT.indexOf(m[3]) < EXT.indexOf(had.split('.').pop())) beats.get(n).set(k, f);
577
+ }
578
+ }
579
+ if (!whole.size) return null;
580
+ const slides = [];
581
+ for (let n = 1; n <= Math.max(...whole.keys()); n++) {
582
+ const file = whole.get(n);
583
+ if (!file) { slides.push(null); continue; }
584
+ const segs = [...(beats.get(n) ?? new Map()).entries()].sort((a, b) => a[0] - b[0]).map(([, f]) => ({ file: f }));
585
+ slides.push(segs.length ? { file, segments: segs } : { file });
586
+ }
587
+ return { dir, slides, engine: undefined, model: undefined, voice: undefined, style: undefined };
588
+ }
589
+
590
+ /**
591
+ * Where the narration lives: --narration <dir> (its manifest, else the audio
592
+ * files in it, recorded by hand) → <deckdir>/voiceover/manifest.json → null
593
+ * (a silent deck).
290
594
  * @returns {{ dir, slides }|null}
291
595
  */
292
596
  export function resolveNarration(deckPath, narrationDir) {
@@ -294,8 +598,10 @@ export function resolveNarration(deckPath, narrationDir) {
294
598
  const path = join(dir, 'manifest.json');
295
599
  if (!existsSync(path)) {
296
600
  if (required) {
297
- throw new Error(`--narration: no manifest.json in ${dir} — `
298
- + 'run tools/voiceover.mjs (or decklight video --voiceover) first');
601
+ const byHand = folderNarration(dir);
602
+ if (byHand) return byHand;
603
+ throw new Error(`--narration: no manifest.json and no slide-NN audio in ${dir} — `
604
+ + 'record it first (decklight narrate, or decklight video --voiceover)');
299
605
  }
300
606
  return null;
301
607
  }
@@ -303,12 +609,86 @@ export function resolveNarration(deckPath, narrationDir) {
303
609
  if (!Array.isArray(m?.slides)) {
304
610
  throw new Error(`${path}: not a voiceover manifest (no slides array) — regenerate it with tools/voiceover.mjs`);
305
611
  }
306
- return { dir, slides: m.slides };
612
+ // the header rides along: the freshness check hashes the deck's notes under it
613
+ return { dir, slides: m.slides, engine: m.engine, model: m.model, voice: m.voice, style: m.style };
307
614
  };
308
615
  if (narrationDir) return load(resolve(narrationDir), true);
309
616
  return load(join(resolve(deckPath, '..'), 'voiceover'), false);
310
617
  }
311
618
 
619
+ /**
620
+ * Re-voice a machine-voiced track's stale slides, before a render (#553).
621
+ *
622
+ * A slide whose notes changed since it was voiced would speak against its own
623
+ * captions, so the render refuses it (#536). When the track was voiced by an
624
+ * ENGINE — its manifest header names one — and that engine is available here,
625
+ * the refusal has an obvious fix the render can make itself: voice just those
626
+ * slides again, in the track's own engine, model, voice and style, into its
627
+ * own format and file names. That is a range-scoped call into the one
628
+ * synthesis core every producer of a track shares (tools/narration-synth.mjs,
629
+ * #555), so the refreshed slide is exactly what `voiceover` or the deck's
630
+ * recorder would have written, and the freshness check it then passes is the
631
+ * same hash.
632
+ *
633
+ * Returns `{ ok: true }` once every stale slide is voiced, or `{ ok: false,
634
+ * why }` for a track that cannot be re-voiced — a human take (no engine), or an
635
+ * engine this machine cannot run (no key, no model) — naming what is missing.
636
+ * Before any synthesis it says how many clips it will ask for, from which
637
+ * engine: on a cloud engine that is money, and the clip cache makes any
638
+ * sentence already paid for free.
639
+ */
640
+ export async function revoiceStale({
641
+ html, narration, stale, log = console.log, env = process.env,
642
+ create = createEngine, status = engineStatus, cache = createTtsCache(),
643
+ }) {
644
+ const { dir, engine } = narration;
645
+ if (!engine || !ENGINES.includes(engine)) {
646
+ 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` };
647
+ }
648
+ // the engine's settings as the edit server passes them to voiceover: the
649
+ // environment, then tts.json for THIS engine
650
+ const saved = loadTtsConfig(env);
651
+ const savedFor = saved?.engine === engine ? saved : null;
652
+ const project = env.GOOGLE_CLOUD_PROJECT ?? saved?.project ?? null;
653
+ const dataDir = savedFor?.dataDir ?? (engine === 'piper' ? piperModelDir(env) : null);
654
+ const voice = narration.voice ?? undefined;
655
+ const st = status(engine, { env, project, dataDir, voice: engine === 'piper' ? (voice ?? narration.model) : voice });
656
+ if (!st.ready) {
657
+ const b = engineBlocker(st, { env });
658
+ return { ok: false, why: `it was voiced by ${engine}, which ${b ? `${b.why} — ${b.fix}` : `is not available here (${st.reason})`}` };
659
+ }
660
+ let tts;
661
+ try {
662
+ tts = create({
663
+ engine, voice, project, dataDir, env,
664
+ // the model is identity only where an engine has more than one per voice
665
+ model: engine === 'elevenlabs' || engine === 'gemini' ? (narration.model ?? undefined) : undefined,
666
+ format: savedFor?.format,
667
+ });
668
+ } catch (e) {
669
+ return { ok: false, why: `it was voiced by ${engine}, which cannot start here — ${e.message}` };
670
+ }
671
+ try {
672
+ const raw = slideNotes(html);
673
+ const clips = stale.reduce((sum, n) => sum + (notesSegments(raw[n - 1] ?? '')?.length ?? 1), 0);
674
+ log(` re-voicing ${stale.length === 1 ? `slide ${stale[0]}` : `slides ${stale.join(', ')}`} in the track's own voice — `
675
+ + `${clips} clip${clips === 1 ? '' : 's'} from ${engine}${voice ? ` (${voice})` : ''}`
676
+ + `${typeof tts.cost === 'string' ? `, ${tts.cost}` : ''}; any sentence already voiced comes from the clip cache`);
677
+ for (const n of stale) {
678
+ const prev = readTrack(dir);
679
+ await synthesizeSlides({
680
+ html, dir, tts, voice, style: narration.style ?? undefined,
681
+ format: trackFormat(prev) ?? 'wav', range: { from: n, to: n }, prev, cache, log,
682
+ });
683
+ }
684
+ return { ok: true };
685
+ } catch (e) {
686
+ return { ok: false, why: e.message };
687
+ } finally {
688
+ tts.synth.close?.();
689
+ }
690
+ }
691
+
312
692
  const have = (bin) => {
313
693
  try { runBounded(bin, ['-version'], { stdio: 'ignore', timeout: PROBE_MS }); return true; }
314
694
  catch (e) { return e?.code !== 'ENOENT'; }
@@ -343,8 +723,17 @@ const STEP_PROBE = `<script>
343
723
  })();
344
724
  </script>`;
345
725
 
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(');
726
+ /**
727
+ * Make the deck's instance reachable, the way test/import-render.mjs does: a
728
+ * deck that boots itself from its `init` call has the call's result exposed; a
729
+ * deck as data (#520) boots itself, so the probe reads the instance off the
730
+ * stage — lazily, since the engine is served into the page after this runs.
731
+ */
732
+ const PROBE_GETTER = '<script>Object.defineProperty(window, "__decklightProbe", { get: () => document.querySelector(".decklight")?.__decklight });</script>\n';
733
+ const exposeInstance = (html) => {
734
+ const out = html.replace(/\bDecklight\s*\.\s*init\s*\(/, 'window.__decklightProbe = Decklight.init(');
735
+ return out !== html ? out : (injectBeforeBodyEnd(html, PROBE_GETTER) ?? html);
736
+ };
348
737
 
349
738
  /** Parse the probe's answer out of a dumped DOM; null when it did not report. */
350
739
  export function parseBuildSteps(dom, slides) {
@@ -356,7 +745,7 @@ export function parseBuildSteps(dom, slides) {
356
745
  return counts.length === slides ? counts : null;
357
746
  }
358
747
 
359
- export async function videoMain(argv, { exec = run, log = console.log } = {}) {
748
+ export async function videoMain(argv, { exec: execRaw = run, log = console.log } = {}) {
360
749
  const { opt } = argReader(argv);
361
750
  const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
362
751
  // Two different situations, and the stream and the exit code follow WHICH
@@ -373,7 +762,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
373
762
 
374
763
  // The served root is the directory you run from — the deck must sit inside it
375
764
  // 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
765
+ // off the loopback origin the frames are captured against. This is the no-trust mode's
377
766
  // rule, for the same reason (#229): the deck runs under the CSP, and a read
378
767
  // cannot escape the served tree. `cd` to a directory containing the deck.
379
768
  const root = process.cwd();
@@ -390,9 +779,27 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
390
779
  process.exit(1);
391
780
  }
392
781
 
782
+ // Stopped part-way — the edit server's stop route sends SIGTERM. Every Chrome
783
+ // and ffmpeg in flight is killed through this signal and the next one never
784
+ // starts; the `finally` below takes the scratch frames, and the catch takes a
785
+ // file ffmpeg had begun writing, because a half-written video looks exactly
786
+ // like a finished one in a file browser. Anything not waiting on a child
787
+ // (re-voicing over the network) gets a moment, then the process goes anyway.
788
+ const stopping = new AbortController();
789
+ process.once('SIGTERM', () => {
790
+ stopping.abort();
791
+ setTimeout(() => process.exit(143), 3000).unref();
792
+ });
793
+ const exec = (bin, args, opts = {}) => execRaw(bin, args, { ...opts, signal: stopping.signal });
794
+ let writing = false;
795
+
393
796
  let out; let plan; let narration;
394
797
  try {
395
- out = resolve(opt('-o', opt('--out', deck.replace(/\.html?$/i, '.mp4'))));
798
+ const named = opt('-o', opt('--out'));
799
+ const { format, quality, subtitles } = videoOptions({
800
+ out: named, format: opt('--format'), quality: opt('--quality'), subtitles: opt('--subtitles'),
801
+ });
802
+ out = resolve(named ?? videoOut(deck, opt('--slides'), format));
396
803
  const { w, h } = parseSize(opt('--size', '1280x720'));
397
804
  const fps = Number(opt('--fps', '30'));
398
805
  const hold = Number(opt('--hold', '5'));
@@ -404,6 +811,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
404
811
  throw new Error(`--build-hold must be positive seconds`);
405
812
  }
406
813
  const theme = opt('--theme');
814
+ const themeParams = renderThemeParams({ theme, gen: opt('--gen') }); // throws on a bad value, before any work
407
815
 
408
816
  const html = readFileSync(deck, 'utf8');
409
817
  const holds = extractHolds(html, hold);
@@ -412,14 +820,45 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
412
820
  const range = parseSlideRange(opt('--slides'), holds.length);
413
821
 
414
822
  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));
823
+ const vo = voiceoverArgs(deck, { narration: opt('--narration'), slides: opt('--slides') });
418
824
  const r = spawnSync(process.execPath, vo, { stdio: 'inherit' });
419
825
  if (r.status !== 0) throw new Error('voiceover batch failed — see its output above');
420
826
  }
421
827
 
422
- narration = resolveNarration(deck, opt('--narration'));
828
+ // --no-narration is silence asked for by name: without it, a voiceover/
829
+ // beside the deck narrates whether or not that was the voice wanted
830
+ narration = argv.includes('--no-narration') ? null : resolveNarration(deck, opt('--narration'));
831
+ // Is the track still THIS deck's notes? Each manifest slide carries the
832
+ // hash of the notes it was voiced from; a slide whose notes moved since
833
+ // would speak against its own captions, so it is named and, unless asked
834
+ // for by name, refused (#536). Only the slides being rendered are checked.
835
+ if (narration) {
836
+ let { stale, hashless } = staleSlides(narration, slideTexts(html), range, priorSlideTexts(html));
837
+ 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`);
838
+ for (const n of stale) console.warn(` slide ${n}: narration was recorded from different notes`);
839
+ // A machine-voiced track fixes itself: its stale slides are voiced again
840
+ // in its own voice, and the check runs again on what that wrote (#553).
841
+ let unrevoiced = null;
842
+ if (stale.length && !argv.includes('--no-revoice')) {
843
+ const r = await revoiceStale({ html, narration, stale, log });
844
+ if (r.ok) {
845
+ narration = resolveNarration(deck, narration.dir);
846
+ ({ stale } = staleSlides(narration, slideTexts(html), range, priorSlideTexts(html)));
847
+ } else {
848
+ unrevoiced = r.why;
849
+ console.warn(` not re-voiced: ${r.why}`);
850
+ }
851
+ }
852
+ if (stale.length) {
853
+ const which = stale.length === 1 ? `slide ${stale[0]}` : `slides ${stale.join(', ')}`;
854
+ if (!argv.includes('--allow-stale')) {
855
+ throw new Error(`the narration in ${narration.dir} was recorded from older notes on ${which}`
856
+ + `${unrevoiced ? ` and cannot be re-voiced here: ${unrevoiced}` : ''} — `
857
+ + `re-record those slides (V → Record this deck… → slides ${stale[0]}-${stale[stale.length - 1]}) or pass --allow-stale`);
858
+ }
859
+ console.warn(` --allow-stale: rendering ${which} with the older narration`);
860
+ }
861
+ }
423
862
 
424
863
  // real durations, not the manifest's word count: ffprobe each audio file
425
864
  const durations = {};
@@ -444,18 +883,19 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
444
883
  }
445
884
 
446
885
 
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.
886
+ // --theme rides the deck URL as `?theme=` — the runtime's own startup
887
+ // override, as `decklight pdf` has always used it — so it reaches every
888
+ // kind of theme a deck can hold: one of its inline blocks, an added one, or
889
+ // a themes/<name>.css file. It used to inject a <link> to that file, which
890
+ // on a deck whose themes are inline blocks (every `upgrade --link` deck)
891
+ // pointed at nothing, and the render came out in the first block (#547).
892
+ // …and every load is declared a render (`?capture`, #548). --gen rides
893
+ // `?gen=` the same way, for a theme that lives only in a browser.
894
+ const renderQuery = `?${['capture', ...themeParams].join('&')}`;
451
895
  let probing = false;
452
896
  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;
897
+ if (resolve(file) !== deck || !probing) return text;
898
+ return injectBeforeBodyEnd(exposeInstance(text), STEP_PROBE) ?? text;
459
899
  };
460
900
  const deckPath = '/' + relative(root, deck).split(sep).join('/');
461
901
 
@@ -473,7 +913,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
473
913
  try {
474
914
  const dom = await exec(chrome, chromeArgs(
475
915
  '--hide-scrollbars', `--window-size=${w},${h}`,
476
- '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}`,
916
+ '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}${renderQuery}`,
477
917
  ), { maxBuffer: 64 * 1024 * 1024 });
478
918
  steps = parseBuildSteps(dom.stdout, holds.length);
479
919
  } catch { /* fall through to one frame per slide */ }
@@ -481,7 +921,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
481
921
  if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
482
922
 
483
923
  plan = planTimeline(narration?.slides ?? null, durations, holds, range,
484
- { steps, buildHold, pauses, onWarn: (w) => console.warn(` ${w}`) });
924
+ { steps, buildHold, pauses, marks: pauseMarks(html, steps), onWarn: (w) => console.warn(` ${w}`) });
485
925
  const slideCount = new Set(plan.map((p) => p.slide)).size;
486
926
  log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
487
927
  + `${plan.filter((p) => p.audio).length} narrated`
@@ -494,19 +934,21 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
494
934
  const nn = String(p.slide).padStart(2, '0');
495
935
  const id = `${nn}-${String(f++).padStart(3, '0')}`;
496
936
  const frame = join(work, `frame-${id}.png`);
497
- // one one-shot Chrome per frame; LAST_STEP clamps to the last build
937
+ // one one-shot Chrome per frame; LAST_STEP clamps to the last build.
938
+ // `?capture` says it is a render: every frame is a fresh load, and
939
+ // without it each one greeted the viewer with the voice-over hint (#548)
498
940
  await exec(chrome, chromeArgs(
499
941
  '--hide-scrollbars',
500
942
  '--autoplay-policy=no-user-gesture-required',
501
943
  `--window-size=${w},${h}`,
502
944
  '--virtual-time-budget=1500',
503
945
  `--screenshot=${frame}`,
504
- `${server.origin}${deckPath}#/${p.slide}/${p.step}`,
946
+ `${server.origin}${deckPath}${renderQuery}#/${p.slide}/${p.step}`,
505
947
  ));
506
948
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
507
- const seg = join(work, `seg-${id}.mp4`);
949
+ const seg = join(work, `seg-${id}.${ENCODINGS[format].ext}`);
508
950
  await exec('ffmpeg', segmentArgs({
509
- frame, duration: p.duration, pad: p.pad, fps, out: seg,
951
+ frame, duration: p.duration, pad: p.pad, fps, out: seg, format, quality,
510
952
  audio: p.audio ? join(narration.dir, p.audio) : null,
511
953
  }));
512
954
  segments.push(seg);
@@ -514,9 +956,38 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
514
956
  log(` slide ${nn}${where}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
515
957
  }
516
958
 
959
+ // Subtitles are the words the audio speaks: the script voiceover wrote
960
+ // beside each clip when there is one (it may have been edited to change
961
+ // what is said), the deck's own notes for that beat when there is not.
962
+ let embedded = null;
963
+ if (subtitles !== 'none') {
964
+ const sections = sectionBodies(html);
965
+ const textOf = (p) => {
966
+ const script = join(narration.dir, p.audio.replace(/\.[^.]+$/, '.txt'));
967
+ // an edited script may spell its markers the way a person does — `[pause]`
968
+ if (existsSync(script)) return canonMarks(readFileSync(script, 'utf8'));
969
+ const notes = sections[p.slide - 1]?.match(NOTES_ASIDE)?.[1] ?? '';
970
+ const k = narration.slides?.[p.slide - 1]?.segments?.findIndex((sg) => sg.file === p.audio) ?? -1;
971
+ return k >= 0 ? (notesSegments(notes, { marks: true })?.[k] ?? '') : cleanNotes(notes, { marks: true });
972
+ };
973
+ const markHolds = markerPauses(html);
974
+ const cues = narration ? subtitleCues(plan, textOf, (p) => markHolds[p.slide - 1] ?? 0) : [];
975
+ const enc = ENCODINGS[format];
976
+ if (!cues.length) {
977
+ console.warn(' subtitles: nothing is spoken in this render — none written');
978
+ } else {
979
+ const file = subtitles === 'embed' ? join(work, `subtitles.${enc.subtitleExt}`) : subtitlesOut(out, format);
980
+ writeFileSync(file, enc.subtitleExt === 'vtt' ? toVtt(cues) : toSrt(cues));
981
+ if (subtitles === 'embed') embedded = file;
982
+ log(` subtitles: ${cues.length} cue${cues.length === 1 ? '' : 's'} ${subtitles === 'embed' ? 'embedded' : `→ ${file}`}`);
983
+ }
984
+ }
985
+
517
986
  const list = join(work, 'concat.txt');
518
987
  writeFileSync(list, concatList(segments));
519
- await exec('ffmpeg', concatArgs(list, out));
988
+ writing = true;
989
+ await exec('ffmpeg', concatArgs(list, out, { format, subtitles: embedded }));
990
+ writing = false;
520
991
  } finally {
521
992
  await server.close();
522
993
  rmSync(work, { recursive: true, force: true });
@@ -525,6 +996,11 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
525
996
  const total = Number((await exec('ffprobe', ffprobeArgs(out))).stdout.trim());
526
997
  log(`done → ${out} (${total.toFixed(1)}s)`);
527
998
  } catch (e) {
999
+ if (stopping.signal.aborted) {
1000
+ if (writing) rmSync(out, { force: true });
1001
+ console.error('decklight video: stopped — no video written');
1002
+ process.exit(143);
1003
+ }
528
1004
  console.error(`decklight video: ${e.message}`);
529
1005
  process.exit(1);
530
1006
  }