decklight 0.10.0 → 0.11.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 (117) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +17 -0
  3. package/README.md +53 -25
  4. package/SPEC.md +1239 -67
  5. package/cli/agents.mjs +139 -15
  6. package/cli/bundle.mjs +68 -2
  7. package/cli/cast.mjs +45 -14
  8. package/cli/check-fixes.mjs +12 -4
  9. package/cli/check-watch.mjs +151 -0
  10. package/cli/check.mjs +460 -71
  11. package/cli/code-editor.mjs +287 -0
  12. package/cli/commands.mjs +13 -2
  13. package/cli/commit-message.mjs +34 -7
  14. package/cli/commit-split.mjs +123 -23
  15. package/cli/decklight.mjs +11 -1
  16. package/cli/design-system-edit.mjs +37 -1
  17. package/cli/edit-address.mjs +184 -0
  18. package/cli/edit-git.mjs +21 -4
  19. package/cli/edit-handover.mjs +136 -25
  20. package/cli/edit-look.mjs +45 -1
  21. package/cli/edit-open.mjs +143 -0
  22. package/cli/edit-slides.mjs +1043 -67
  23. package/cli/edit-translate.mjs +243 -0
  24. package/cli/edit.mjs +3182 -267
  25. package/cli/editor-support.mjs +286 -0
  26. package/cli/enhance.mjs +148 -20
  27. package/cli/find-replace.mjs +142 -0
  28. package/cli/fix-review.mjs +368 -0
  29. package/cli/init.mjs +93 -19
  30. package/cli/keep-awake.mjs +68 -0
  31. package/cli/migrate-writing.mjs +214 -0
  32. package/cli/narrate.mjs +51 -10
  33. package/cli/open.mjs +29 -9
  34. package/cli/outside-edit.mjs +257 -0
  35. package/cli/paste.mjs +92 -0
  36. package/cli/pdf.mjs +61 -2
  37. package/cli/pptx-export.mjs +3 -1
  38. package/cli/publish.mjs +24 -3
  39. package/cli/record.mjs +19 -8
  40. package/cli/rewrite.mjs +265 -0
  41. package/cli/runtime-link.mjs +218 -17
  42. package/cli/serve.mjs +7 -4
  43. package/cli/setup.mjs +2 -2
  44. package/cli/skill-content.mjs +212 -8
  45. package/cli/skills/slide-writing.md +333 -0
  46. package/cli/skills/voiceover.md +423 -0
  47. package/cli/skills.mjs +36 -13
  48. package/cli/starter-full.mjs +353 -0
  49. package/cli/supervise.mjs +14 -0
  50. package/cli/theme.mjs +3 -2
  51. package/cli/translate-core.mjs +466 -0
  52. package/cli/translate-files.mjs +149 -0
  53. package/cli/translate.mjs +458 -0
  54. package/cli/util.mjs +25 -0
  55. package/cli/vocabulary-docs.mjs +138 -0
  56. package/dist/decklight.css +2087 -91
  57. package/dist/decklight.js +367 -203
  58. package/dist/decklight.js.map +4 -4
  59. package/docs/GLOSSARY.md +9 -2
  60. package/docs/WRITING_RESEARCH.md +327 -0
  61. package/package.json +5 -3
  62. package/themes/coastal.css +3 -0
  63. package/themes/metropolis.css +2 -0
  64. package/themes/reveal-blood.css +3 -0
  65. package/themes/reveal-league.css +2 -0
  66. package/themes/reveal-moon.css +2 -0
  67. package/themes/reveal-serif.css +1 -0
  68. package/themes/reveal-sky.css +1 -0
  69. package/themes/reveal-solarized.css +4 -0
  70. package/tools/brand-palette.mjs +6 -1
  71. package/tools/build-groups.mjs +28 -8
  72. package/tools/cdp.mjs +176 -0
  73. package/tools/chart-spec.mjs +242 -0
  74. package/tools/click-match.mjs +70 -0
  75. package/tools/code-options.mjs +174 -0
  76. package/tools/conversation.mjs +49 -0
  77. package/tools/deck-family.mjs +101 -0
  78. package/tools/deck-html.mjs +212 -15
  79. package/tools/design-system-format.mjs +15 -1
  80. package/tools/diagram-shapes.mjs +221 -0
  81. package/tools/elevenlabs-tts.mjs +62 -53
  82. package/tools/face-clip.mjs +96 -0
  83. package/tools/face-layout.mjs +94 -0
  84. package/tools/gemini-tts.mjs +1 -1
  85. package/tools/invisible-in-print.mjs +27 -0
  86. package/tools/lipsync-auto.mjs +197 -0
  87. package/tools/lipsync-config.mjs +16 -0
  88. package/tools/lipsync-engines.mjs +22 -4
  89. package/tools/lipsync-server.mjs +8 -5
  90. package/tools/lipsync.mjs +122 -30
  91. package/tools/local-voice.mjs +1 -1
  92. package/tools/mouth-file.mjs +26 -0
  93. package/tools/mouth.mjs +320 -0
  94. package/tools/narration-manifest.mjs +24 -4
  95. package/tools/narration-synth.mjs +96 -76
  96. package/tools/recording-impact.mjs +16 -1
  97. package/tools/sentences.mjs +7 -1
  98. package/tools/starters.mjs +402 -0
  99. package/tools/steps.mjs +118 -0
  100. package/tools/take-check.mjs +146 -0
  101. package/tools/template-theme.mjs +3 -1
  102. package/tools/test-impact.mjs +36 -12
  103. package/tools/theme-check.mjs +196 -1
  104. package/tools/tone-cue.mjs +108 -0
  105. package/tools/tts-cache.mjs +9 -3
  106. package/tools/tts-engines.mjs +100 -11
  107. package/tools/video-cache.mjs +93 -0
  108. package/tools/video-live.mjs +349 -0
  109. package/tools/video-options.mjs +11 -0
  110. package/tools/video.mjs +772 -127
  111. package/tools/viseme-fit.mjs +27 -0
  112. package/tools/viseme-match.mjs +77 -0
  113. package/tools/vocabulary.mjs +397 -0
  114. package/tools/voice-renumber.mjs +605 -0
  115. package/tools/voiceover-server.mjs +42 -11
  116. package/tools/voiceover.mjs +48 -20
  117. package/dist/build-info.json +0 -1
package/tools/video.mjs CHANGED
@@ -8,49 +8,43 @@
8
8
  // [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
9
9
  // [--build-hold <s>] [--theme <name> | --gen <b64url>] [--slides a-b] [--voiceover]
10
10
  //
11
- // A still per FRAME — a narrated slide is one still, fully built, held for its
12
- // audio; a silent slide builds as it goes, one still per step — muxed with the
13
- // audio into one mp4, so a deck becomes a watchable, shareable video in one
14
- // command. Every frame of a silent slide holds --hold, builds included, so a
15
- // build lands at the pace the deck moves at; --build-hold paces the build-up
16
- // frames alone. Narration resolves --narration <dir> → <deckdir>/voiceover/
17
- // (the manifest tools/voiceover.mjs writes) → a fully silent deck where every
18
- // slide holds --hold seconds (per-slide override: data-video-hold="8" on the
19
- // section). Silent slides still carry a silent audio segment (anullsrc) so the
20
- // concatenated audio track stays continuous.
11
+ // The timeline is shared by both render modes. Exact renders slides in a
12
+ // bounded pool, prepares one document per beat, and seeks its animation and
13
+ // mouth pose on the output frame clock. It encodes the beat with its whole
14
+ // audio clip and caches completed slides. Live plays that timeline once
15
+ // against the browser's audio clock and records its viewport in real time.
21
16
  //
22
- // Capture is the tools/shot.mjs mechanism: one one-shot headless Chrome per
23
- // frame against the deck served over http://127.0.0.1 at #/n/999 (an oversized
24
- // step clamps to the last build, so every slide renders fully built). The deck
25
- // is served under the `--no-trust` CSP, NOT opened over file:// with
26
- // --allow-file-access-from-files (#229): that flag let a deck's own JS read any
27
- // local file and exfiltrate it, and video renders decks you may not have
28
- // vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
29
- // frames are stills, so the character overlay appears but frozen and a build
30
- // CUTS rather than animating (animated capture needs a CDP screencast — a
31
- // Node ≥22 follow-up). How far each slide builds is asked of the deck itself,
32
- // in one extra load, because the grouping is the runtime's and a second counter
33
- // written here would be a copy that drifts.
17
+ // Both render modes use the loopback render server's CSP. The capture process
18
+ // never grants a deck file:// access to the rest of the machine.
34
19
 
35
20
  import { execFile, spawnSync } from 'node:child_process';
36
- import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
- import { tmpdir } from 'node:os';
38
- import { basename, join, relative, resolve, sep } from 'node:path';
21
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
22
+ import { writeFile } from 'node:fs/promises';
23
+ import { availableParallelism, tmpdir } from 'node:os';
24
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
39
25
  import { promisify } from 'node:util';
40
26
  import { fileURLToPath } from 'node:url';
41
27
  import { chromeBin, chromeArgs } from './chrome.mjs';
28
+ import { openPage } from './cdp.mjs';
42
29
  import { argReader, isMain } from './args.mjs';
43
30
  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';
31
+ import { injectBeforeBodyEnd, sectionBodies, isHiddenSection, NOTES_ASIDE, cleanNotes, notesSegments, deckLang } from './deck-html.mjs';
32
+ import { VIDEO_FORMATS, VIDEO_QUALITIES, VIDEO_SUBTITLES, VIDEO_RENDER_MODES, valuesOf } from './video-options.mjs';
33
+ import { splitSentences, speechRuns, stripAudioTags, PAUSE_MARK, CLICK_MARK, canonMarks, hasWords } from './sentences.mjs';
47
34
  import { serveForRender } from '../cli/serve.mjs';
48
35
  import { run as runBounded, PROBE_MS } from './exec.mjs';
49
- import { staleSlides, slideTexts, priorSlideTexts, slideNotes, markerPauses } from './narration-manifest.mjs';
36
+ import { staleSlides, slideTexts, priorSlideTexts, slideNotes, slideBeats, scriptDrift, markerPauses } from './narration-manifest.mjs';
37
+ import { defaultTrackDir } from './deck-family.mjs';
50
38
  import { synthesizeSlides, readTrack, trackFormat } from './narration-synth.mjs';
39
+ import { characterMode, lipsyncAfterVoicing, haveRhubarb } from './lipsync-auto.mjs';
51
40
  import { createEngine, engineStatus, engineBlocker, ENGINES, piperModelDir } from './tts-engines.mjs';
52
41
  import { loadTtsConfig } from './tts-setup.mjs';
53
42
  import { createTtsCache } from './tts-cache.mjs';
43
+ import { faceLayout } from './face-layout.mjs';
44
+ import { videoCache, videoDigest, videoMarkup } from './video-cache.mjs';
45
+ import { captureLive } from './video-live.mjs';
46
+ import { visemeMismatch, wavDuration } from './viseme-match.mjs';
47
+ import { mouthFromFile } from './mouth-file.mjs';
54
48
 
55
49
  const run = promisify(execFile);
56
50
 
@@ -71,13 +65,24 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
71
65
  stale slides are re-voiced first (below)
72
66
  --no-revoice leave a machine-voiced track's stale slides as they are:
73
67
  refuse them, or render them old with --allow-stale
68
+ --no-remake-visemes leave missing or mismatched lip-sync unused
74
69
  --format <f> mp4 (H.264/AAC, the default) · mov (H.264/AAC) · webm
75
70
  (VP9/Opus); read off -o's extension when that names one
76
71
  --quality <q> draft (quick, small) · standard (the default) · high
77
72
  (slower to render, sharper, larger)
78
73
  --subtitles <how> none (the default) · embed (a track the player can turn
79
74
  on) · file (a .srt beside the video, .vtt for webm) —
80
- what the narration says, timed against its audio
75
+ what the narration says, timed against its audio, cut
76
+ to the lengths the deck's language reads at
77
+ --disclose a video voiced by an AI voice says so in its metadata
78
+ by default; this also shows it, a line on the first
79
+ slide in the deck's language
80
+ --no-disclose write neither
81
+ --render <mode> exact (default, repeatable) or live (real-time capture,
82
+ may drop frames and cannot resume)
83
+ --parallel <n> maximum Chrome pages for exact render (default: up to 6,
84
+ bounded by available cores); 1 renders serially
85
+ --no-cache render every slide again in exact mode
81
86
  --size <WxH> frame size (default 1280x720; both must be even)
82
87
  --fps <n> video frame rate (default 30)
83
88
  --hold <s> seconds a slide without narration holds (default 5;
@@ -96,10 +101,22 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
96
101
  --slides <a-b> only this slide range (1-based, inclusive)
97
102
  --voiceover run the voiceover batch (tools/voiceover.mjs) first —
98
103
  over the --slides range only, when one is given
104
+ --character <how> viseme draws the animated character in every narrated
105
+ frame, off leaves it out; by default the deck's own
106
+ narration.character.mode decides
107
+ --no-face leave out the face you filmed while recording the
108
+ narration and the animated character. By default they
109
+ show the way each slide says
110
+ (data-face: the corner medallion, hidden, or full
111
+ screen at a zoom), in time with your voice
99
112
 
100
- Every slide BUILDS, one frame per step. A narrated slide takes its timing from
101
- its own audio: [click] in the speaker notes splits the narration, and segment k
102
- is spoken over build step k — the same rule the live player follows. Without
113
+ Every slide BUILDS, one frame per step, and each build fades or slides in as it
114
+ does in the deck. A slide that animates (an SVG <animate>, a looping CSS
115
+ animation) plays at --fps for its whole hold, from the start of its loop; a
116
+ slide with no motion stays a cheap still. Moving capture needs Node 22+.
117
+ A narrated slide takes its timing from its own audio: [click] in the speaker
118
+ notes splits the narration, and segment k is spoken over build step k — the
119
+ same rule the live player follows. Without
103
120
  markers it holds fully built for the audio's real duration. A silent slide holds
104
121
  --hold seconds, --build-hold per step. Either way the audio track is continuous
105
122
  and the finished slide gets a ${TAIL_SECONDS}s breath before the cut — plus
@@ -187,16 +204,15 @@ export function videoProgress(onSlide) {
187
204
 
188
205
  /**
189
206
  * 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.
207
+ * count completed synthesis against the work left after checking the track.
192
208
  */
193
209
  export function voiceoverProgress(onSlide) {
194
210
  let of = 0;
195
211
  let n = 0;
196
212
  return (line) => {
197
- const head = / · (\d+) to voice$/.exec(line);
213
+ const head = /^\s+voice work: (\d+) slides to synthesize$/.exec(line);
198
214
  if (head) { of = Number(head[1]); return; }
199
- if (of && /^\s+slide \d+: /.test(line)) onSlide(++n, of);
215
+ if (of && /^\s+slide \d+: \d+ chars → /.test(line)) onSlide(++n, of);
200
216
  };
201
217
  }
202
218
 
@@ -209,6 +225,38 @@ export function voiceoverArgs(deck, { narration, slides } = {}) {
209
225
  ...(narration ? ['-o', resolve(narration)] : []), ...(slides ? ['--slides', slides] : [])];
210
226
  }
211
227
 
228
+ /** Per-slide `data-face` (FACE_LAYOUT), read off the open tag like extractHolds; null where there is none. */
229
+ export function extractFaces(html) {
230
+ return sectionBodies(html).map((sec) => {
231
+ const tag = sec.slice(0, sec.indexOf('>'));
232
+ const match = /\sdata-face\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(tag);
233
+ return match?.[1] ?? match?.[2] ?? null;
234
+ });
235
+ }
236
+
237
+ /** The medallion in the frame: the deck's own size and corner margin (CSS px, and a frame is a window of them). */
238
+ export const FACE_CORNER_PX = { size: 220, margin: 28 };
239
+
240
+ /**
241
+ * The filmed face for one planned frame, or null: the clip beside its audio
242
+ * (slide-NN-KK.mp4 beside slide-NN-KK.wav), on a slide whose manifest entry
243
+ * says it was filmed, placed as the slide's `data-face` says for that beat.
244
+ */
245
+ export function faceFor(p, { narration, faces, defaultCorner, exists = existsSync }) {
246
+ if (!p.audio || !narration?.slides?.[p.slide - 1]?.face) return null;
247
+ const clip = join(narration.dir, p.audio.replace(/\.[^.]+$/, '.mp4'));
248
+ if (!exists(clip)) return null;
249
+ const at = exportFaceLayout(p, faces);
250
+ if (at.kind === 'hide') return null;
251
+ if (at.kind === 'corner' && !at.at && defaultCorner) return { clip, ...at, at: defaultCorner };
252
+ return { clip, ...at };
253
+ }
254
+
255
+ export function exportFaceLayout(p, faces) {
256
+ const beat = Number(/^slide-\d+-(\d+)\./.exec(basename(p.audio ?? ''))?.[1] ?? 1);
257
+ return faceLayout(faces?.[p.slide - 1], beat);
258
+ }
259
+
212
260
  /** Per-slide hold seconds: data-video-hold="8" on the section, else the default. */
213
261
  export function extractHolds(html, defaultHold) {
214
262
  return sectionBodies(html).map((sec) => {
@@ -267,6 +315,123 @@ export function extractPauses(html) {
267
315
  });
268
316
  }
269
317
 
318
+ /** Read and validate one recorded viseme sidecar. */
319
+ export function readVisemes(file) {
320
+ if (!existsSync(file)) return null;
321
+ try {
322
+ const tl = JSON.parse(readFileSync(file, 'utf8'));
323
+ if (!Array.isArray(tl?.cues)) return null;
324
+ return { ...tl, cues: tl.cues.filter((c) => Number.isFinite(c?.t) && typeof c?.v === 'string').sort((a, b) => a.t - b.t) };
325
+ } catch { return null; }
326
+ }
327
+
328
+ const LIPSYNC = fileURLToPath(new URL('./lipsync.mjs', import.meta.url));
329
+
330
+ // whether Rhubarb runs here, asked once per process: a sidecar read from the
331
+ // voice stands in for Rhubarb's only while it does not (tools/viseme-match.mjs)
332
+ let rhubarbKnown;
333
+ const rhubarbHere = () => (rhubarbKnown ??= haveRhubarb());
334
+
335
+ function visemeCheck(dir, rhubarb = rhubarbHere()) {
336
+ let state = {};
337
+ try { state = JSON.parse(readFileSync(join(dir, 'lipsync.json'), 'utf8')); } catch { /* none kept */ }
338
+ return (it) => {
339
+ const tl = readVisemes(it.file);
340
+ if (!tl) return { tl: null, why: existsSync(it.file) ? 'it is not a viseme timeline' : 'it is missing' };
341
+ const stem = basename(it.file, '.visemes.json');
342
+ const txt = join(dirname(it.file), `${stem}.txt`);
343
+ const audioBytes = existsSync(it.audio) ? readFileSync(it.audio) : null;
344
+ const why = visemeMismatch(tl, {
345
+ audioBytes,
346
+ stateHash: state[stem]?.visemes ?? null,
347
+ text: existsSync(txt) ? readFileSync(txt, 'utf8').trim() : '',
348
+ duration: it.duration ?? wavDuration(audioBytes),
349
+ rhubarb,
350
+ });
351
+ return { tl, why };
352
+ };
353
+ }
354
+
355
+ /**
356
+ * The viseme timeline for each `{ audio, file, duration }`, checked against
357
+ * that audio. The CLI remakes bad sidecars by default (tools/lipsync.mjs);
358
+ * when that cannot run (no Rhubarb), the mouth is read from the voice itself
359
+ * (tools/mouth.mjs), less exact than Rhubarb and nothing written to disk,
360
+ * rather than stopping. Only audio that cannot even be read stops the export.
361
+ * `skipBad` (exporting as-is) neither remakes nor reads.
362
+ * Returns file → timeline.
363
+ */
364
+ export async function visemesFor(items, { dir, deck, log = console.log, remakeWith = remakeVisemes, readMouth = mouthFromFile, skipBad = false, rhubarb } = {}) {
365
+ if (!items.length) return new Map();
366
+ const unique = [...new Map(items.map((it) => [it.file, it])).values()];
367
+ const check = visemeCheck(dir, rhubarb);
368
+ const out = new Map();
369
+ const bad = [];
370
+ for (const it of unique) {
371
+ const r = check(it);
372
+ if (r.why) bad.push({ ...it, why: r.why }); else out.set(it.file, r.tl);
373
+ }
374
+ if (!bad.length) return out;
375
+ const n = bad.length;
376
+ const files = (list) => list.map((b) => basename(b.file)).join(', ');
377
+ for (const b of bad) log(` lip-sync: ${basename(b.file)} does not match its audio — ${b.why}`);
378
+ if (skipBad) return out;
379
+ log(` lip-sync: remaking ${n} file${n === 1 ? '' : 's'} with Rhubarb…`);
380
+ const failed = await remakeWith(dir, bad.map((b) => basename(b.file, '.visemes.json')));
381
+ const left = [];
382
+ for (const b of bad) {
383
+ const r = check(b);
384
+ if (r.why) left.push(b); else out.set(b.file, r.tl);
385
+ }
386
+ const unread = [];
387
+ for (const b of left) {
388
+ try { out.set(b.file, readMouth(b.audio)); } catch { unread.push(b); }
389
+ }
390
+ if (unread.length) {
391
+ throw new Error(`the animated character's lip-sync does not match its audio in ${files(unread)}`
392
+ + `${failed ? ` and could not be remade here: ${failed}` : ''}`
393
+ + ` — run decklight narrate ${basename(deck)} --face, or pass --no-face`);
394
+ }
395
+ const read = left.length;
396
+ if (n > read) log(` lip-sync: remade ${n - read} file${n - read === 1 ? '' : 's'} to match ${n - read === 1 ? 'its' : 'their'} audio`);
397
+ if (read) {
398
+ log(` lip-sync: ${failed ? `Rhubarb could not run (${failed}), so ` : ''}`
399
+ + `${read} file${read === 1 ? ' is' : 's are'} read from the voice instead · install Rhubarb for a more exact mouth`);
400
+ }
401
+ return out;
402
+ }
403
+
404
+
405
+ /** tools/lipsync.mjs on just these stems; the reason it failed, or null. */
406
+ function remakeVisemes(dir, stems) {
407
+ const r = spawnSync(process.execPath, [LIPSYNC, dir, '--visemes', '--remake', stems.join(',')],
408
+ { stdio: ['ignore', 'inherit', 'pipe'], encoding: 'utf8' });
409
+ if (r.status === 0) return null;
410
+ return String(r.stderr ?? r.error?.message ?? '').trim().split('\n').pop() || `lipsync exited ${r.status}`;
411
+ }
412
+
413
+ /**
414
+ * Split one planned narration beat into deterministic character poses. Audio
415
+ * offsets keep the original recording continuous; the final interval retains
416
+ * the beat/slide padding. Duplicate adjacent shapes do not create extra work.
417
+ */
418
+ export function characterFrames(p, timeline) {
419
+ if (!timeline?.cues?.length || !p.audio) return [{ ...p, character: null, audioOffset: 0 }];
420
+ const changes = [];
421
+ for (const cue of timeline.cues) {
422
+ const t = Math.max(0, Number(cue.t));
423
+ if (t >= p.duration) break;
424
+ if (changes.at(-1)?.v === cue.v) continue;
425
+ changes.push({ t, v: cue.v });
426
+ }
427
+ if (!changes.length || changes[0].t > 0) changes.unshift({ t: 0, v: 'X' });
428
+ return changes.map((cue, i) => {
429
+ const end = changes[i + 1]?.t ?? p.duration;
430
+ return { ...p, duration: round(end - cue.t), pad: i === changes.length - 1 ? p.pad : 0,
431
+ character: cue.v, audioOffset: round(cue.t) };
432
+ }).filter((x) => x.duration > 0);
433
+ }
434
+
270
435
  /**
271
436
  * An oversized step: the engine clamps it to the slide's last build, so this
272
437
  * always renders a slide fully built however many steps it turns out to have.
@@ -275,6 +440,9 @@ export function extractPauses(html) {
275
440
  */
276
441
  export const LAST_STEP = 999;
277
442
 
443
+ /** A build's own transition plays in this long; the rest of its frame is its last picture, held. */
444
+ export const MOTION_WINDOW_S = 1;
445
+
278
446
  const round = (s) => Math.round(s * 1000) / 1000;
279
447
 
280
448
  /**
@@ -396,7 +564,7 @@ const VP9 = { draft: { crf: '40', deadline: 'realtime', cpu: '8' }, standard: {
396
564
  const AUDIO_KBPS = { draft: '96k', standard: '128k', high: '192k' };
397
565
  const H264 = {
398
566
  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],
567
+ video: (q, moving = false) => ['-c:v', 'libx264', ...(moving ? [] : ['-tune', 'stillimage']), '-pix_fmt', 'yuv420p', '-preset', X264[q].preset, '-crf', X264[q].crf],
400
568
  audio: (q) => ['-c:a', 'aac', '-b:a', AUDIO_KBPS[q], '-ar', '44100', '-ac', '2'],
401
569
  };
402
570
  export const ENCODINGS = {
@@ -412,21 +580,69 @@ export const ENCODINGS = {
412
580
 
413
581
  /**
414
582
  * ffmpeg argv for one slide's segment: the still looped at --fps under its
415
- * audio. Narrated slides pad the audio with `pad` — the tail, plus whatever
583
+ * audio, or a moving frame's sequence (`frames`) with its last picture held. Narrated slides pad the audio with `pad` — the tail, plus whatever
416
584
  * beat the slide asked for (`data-narration-pause`) — and stop there; silent
417
585
  * slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
418
586
  * carries an audio stream and the concat-demuxer's `-c copy` audio track never
419
587
  * goes discontinuous. -t bounds both the infinite loop and the infinite
420
588
  * anullsrc (-shortest can't end a segment whose streams are both endless).
421
589
  */
422
- export function segmentArgs({ frame, audio, duration, fps, out, pad = TAIL_SECONDS, format = 'mp4', quality = 'standard' }) {
590
+ export function segmentArgs({ frame, frames = null, audio, audioOffset = 0, duration, fps, out, pad = TAIL_SECONDS, format = 'mp4', quality = 'standard', face = null, size = null }) {
423
591
  const enc = ENCODINGS[format];
592
+ // A moving segment reads a numbered sequence (`frames: { pattern, count }`)
593
+ // and holds its last picture for whatever the sequence does not cover, so
594
+ // the segment is as long as the still would have been.
595
+ const rest = frames ? Math.max(0, duration - frames.count / fps) : 0;
596
+ if (face && audio && size) return faceSegmentArgs({ frame, frames, rest, audio, audioOffset, duration, fps, out, pad, enc, quality, face, size });
424
597
  return [
425
- '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
598
+ '-y', ...(frames
599
+ ? ['-framerate', String(fps), '-i', frames.pattern]
600
+ : ['-loop', '1', '-framerate', String(fps), '-i', frame]),
426
601
  ...(audio
427
- ? ['-i', audio, '-af', `apad=pad_dur=${pad}`]
602
+ ? [...(audioOffset ? ['-ss', Number(audioOffset).toFixed(3)] : []), '-i', audio, '-af', `apad=pad_dur=${pad}`]
428
603
  : ['-f', 'lavfi', '-i', `anullsrc=channel_layout=stereo:sample_rate=${enc.sampleRate}`]),
429
- ...enc.video(quality), ...enc.audio(quality),
604
+ ...(rest > 0 ? ['-vf', `tpad=stop_mode=clone:stop_duration=${rest.toFixed(3)}`] : []),
605
+ ...enc.video(quality, !!frames), ...enc.audio(quality),
606
+ '-t', Number(duration).toFixed(3), ...(enc.faststart ? ['-movflags', '+faststart'] : []), out,
607
+ ];
608
+ }
609
+
610
+ /**
611
+ * segmentArgs with your face in it: the medallion over the still, cut round
612
+ * in the corner (`corner`), or the face alone over the whole frame, cropped
613
+ * to fill it and zoomed on itself the way the deck's `transform-origin: 50%
614
+ * 40%` zooms it (`full`). The clip is exactly as long as the audio (the
615
+ * recorder made it so); it holds its last frame through the slide's breath,
616
+ * as the deck holds it between beats. Same encoder, frame rate and size as
617
+ * every other segment, so the concat's `-c copy` still joins them.
618
+ */
619
+ function faceSegmentArgs({ frame, frames, rest, audio, audioOffset = 0, duration, fps, out, pad, enc, quality, face, size }) {
620
+ const { w, h } = size;
621
+ const hold = `tpad=stop_mode=clone:stop_duration=${Number(pad + 1).toFixed(3)}`;
622
+ let graph;
623
+ if (face.kind === 'full') {
624
+ const zw = Math.ceil((w * face.zoom) / 2) * 2;
625
+ const zh = Math.ceil((h * face.zoom) / 2) * 2;
626
+ graph = `[2:v]fps=${fps},scale=${zw}:${zh}:force_original_aspect_ratio=increase,`
627
+ + `crop=${w}:${h}:(iw-${w})/2:(ih-${h})*0.4,setsar=1,${hold},format=yuv420p`
628
+ + (face.keep ? '[f];[f][0:v]overlay=eof_action=repeat,format=yuv420p[v]' : '[v]');
629
+ } else {
630
+ const d = FACE_CORNER_PX.size;
631
+ const m = FACE_CORNER_PX.margin;
632
+ graph = `[2:v]fps=${fps},scale=${d}:${d}:force_original_aspect_ratio=increase,crop=${d}:${d},setsar=1,${hold},format=yuva420p,`
633
+ + `geq=lum='lum(X,Y)':cb='cb(X,Y)':cr='cr(X,Y)':a='if(lte(hypot(X-${d / 2},Y-${d / 2}),${d / 2}),255,0)'[f];`
634
+ // the corner the slide names (data-face="top-left"), else the deck's bottom right
635
+ + `[0:v]${rest > 0 ? `tpad=stop_mode=clone:stop_duration=${rest.toFixed(3)},` : ''}setsar=1[s];[s][f]overlay=`
636
+ + `${/l$/.test(face.at ?? '') ? m : w - d - m}:${/^t/.test(face.at ?? '') ? m : h - d - m}:eof_action=repeat,format=yuv420p[v]`;
637
+ }
638
+ return [
639
+ '-y', ...(frames
640
+ ? ['-framerate', String(fps), '-i', frames.pattern]
641
+ : ['-loop', '1', '-framerate', String(fps), '-i', frame]),
642
+ ...(audioOffset ? ['-ss', Number(audioOffset).toFixed(3)] : []), '-i', audio, '-i', face.clip,
643
+ '-filter_complex', `${graph};[1:a]apad=pad_dur=${pad}[a]`,
644
+ '-map', '[v]', '-map', '[a]', '-r', String(fps),
645
+ ...enc.video(quality, true), ...enc.audio(quality),
430
646
  '-t', Number(duration).toFixed(3), ...(enc.faststart ? ['-movflags', '+faststart'] : []), out,
431
647
  ];
432
648
  }
@@ -441,20 +657,40 @@ export function concatList(segments) {
441
657
  * when there are subtitles to embed, mapping them in as a track of the
442
658
  * container's own kind (the only step that encodes anything, and it is text).
443
659
  */
444
- export function concatArgs(listFile, out, { format = 'mp4', subtitles = null } = {}) {
660
+ export function concatArgs(input, out, { format = 'mp4', subtitles = null, concat = true, lang = null, audio = false, comment = null } = {}) {
445
661
  const enc = ENCODINGS[format];
446
- return ['-y', '-f', 'concat', '-safe', '0', '-i', listFile,
662
+ const code = iso639b(lang);
663
+ return ['-y', ...(concat ? ['-f', 'concat', '-safe', '0'] : []), '-i', input,
447
664
  ...(subtitles ? ['-i', subtitles, '-map', '0', '-map', '1'] : []),
448
665
  '-c', 'copy', ...(subtitles ? ['-c:s', enc.subtitleCodec] : []),
666
+ ...(code && audio ? ['-metadata:s:a:0', `language=${code}`] : []),
667
+ ...(code && subtitles ? ['-metadata:s:s:0', `language=${code}`] : []),
668
+ ...(comment ? ['-metadata', `comment=${comment}`] : []),
449
669
  ...(enc.faststart ? ['-movflags', '+faststart'] : []), out];
450
670
  }
451
671
 
452
672
  /** A subtitle longer than this is split into cues of its own; two lines of about half each is what a player shows. */
453
673
  export const CUE_MAX_CHARS = 84;
454
674
 
675
+ /**
676
+ * The longest cue for a language (SPEC TRANSLATION_VOICE): two lines of 42 for
677
+ * a language written in words, and of what a reader takes in at a glance for
678
+ * one written without spaces (Japanese 13 a line, Chinese and Korean 16,
679
+ * the lengths broadcasters set).
680
+ */
681
+ export function cueMaxChars(lang) {
682
+ let script = null;
683
+ try { script = lang ? new Intl.Locale(lang).maximize().script : null; } catch { script = null; }
684
+ if (script === 'Jpan') return 26;
685
+ if (script === 'Hans' || script === 'Hant' || script === 'Kore') return 32;
686
+ return CUE_MAX_CHARS;
687
+ }
688
+
455
689
  /** Words into runs of at most `max` characters, never mid-word. */
456
690
  function chunkCue(text, max) {
457
691
  if (text.length <= max) return [text];
692
+ // a language written without spaces is cut by characters
693
+ if (!/\s/.test(text)) return text.match(new RegExp(`[\\s\\S]{1,${max}}`, 'gu')) ?? [text];
458
694
  const out = [];
459
695
  let line = '';
460
696
  for (const word of text.split(' ')) {
@@ -468,6 +704,7 @@ function chunkCue(text, max) {
468
704
  function wrapCue(text, line = CUE_MAX_CHARS / 2) {
469
705
  if (text.length <= line) return text;
470
706
  const mid = text.length / 2;
707
+ if (!/\s/.test(text)) return `${text.slice(0, Math.ceil(mid))}\n${text.slice(Math.ceil(mid))}`;
471
708
  let at = -1;
472
709
  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
710
  return at < 0 ? text : `${text.slice(0, at)}\n${text.slice(at + 1)}`;
@@ -492,7 +729,7 @@ function wrapCue(text, line = CUE_MAX_CHARS / 2) {
492
729
  * @param holdOf frame → seconds one ⟨PAUSE⟩ holds on its slide
493
730
  * @returns {Array<{start, end, text}>} seconds from the start of the video
494
731
  */
495
- export function subtitleCues(plan, textOf, holdOf = () => 0) {
732
+ export function subtitleCues(plan, textOf, holdOf = () => 0, { max = CUE_MAX_CHARS } = {}) {
496
733
  const cues = [];
497
734
  let t = 0;
498
735
  for (const p of plan) {
@@ -504,7 +741,7 @@ export function subtitleCues(plan, textOf, holdOf = () => 0) {
504
741
  // pieces of { text, weight }, each run's then its hold
505
742
  const cut = runs.map((r) => ({
506
743
  // 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))
744
+ pieces: splitSentences(r.text).map(stripAudioTags).filter(Boolean).flatMap((s) => chunkCue(s, max))
508
745
  .map((text) => ({ text, weight: text.length })),
509
746
  pause: r.pause,
510
747
  }));
@@ -513,7 +750,7 @@ export function subtitleCues(plan, textOf, holdOf = () => 0) {
513
750
  for (const c of cut) {
514
751
  for (const piece of c.pieces) {
515
752
  const len = spoken * (piece.weight / total);
516
- cues.push({ start: round(at), end: round(at + len), text: wrapCue(piece.text) });
753
+ cues.push({ start: round(at), end: round(at + len), text: wrapCue(piece.text, max / 2) });
517
754
  at += len;
518
755
  }
519
756
  at += c.pause * hold;
@@ -537,9 +774,43 @@ export function toSrt(cues) {
537
774
  }
538
775
 
539
776
  /** WebVTT: a header, a dot before the milliseconds, and `<` / `&` escaped — cue text is markup there. */
540
- export function toVtt(cues) {
777
+ export function toVtt(cues, { lang = null } = {}) {
541
778
  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')}`;
779
+ return `WEBVTT\n${lang ? `Language: ${lang}\n` : ''}\n${cues.map((c) => `${stamp(c.start, '.')} --> ${stamp(c.end, '.')}\n${esc(c.text)}\n`).join('\n')}`;
780
+ }
781
+
782
+ /**
783
+ * The ISO 639-2 code a container tags a stream's language with (`fre` for
784
+ * `fr`), or null for a language not listed: an untagged stream rather than a
785
+ * wrong tag.
786
+ */
787
+ export function iso639b(lang) {
788
+ const p = String(lang ?? '').trim().split(/[-_]/)[0].toLowerCase();
789
+ return ({
790
+ en: 'eng', fr: 'fre', de: 'ger', es: 'spa', it: 'ita', pt: 'por', nl: 'dut', ja: 'jpn', zh: 'chi', ko: 'kor',
791
+ ru: 'rus', pl: 'pol', sv: 'swe', da: 'dan', fi: 'fin', no: 'nor', nb: 'nob', tr: 'tur', ar: 'ara', he: 'heb',
792
+ hi: 'hin', cs: 'cze', el: 'gre', hu: 'hun', ro: 'rum', uk: 'ukr', vi: 'vie', th: 'tha', id: 'ind', ca: 'cat',
793
+ })[p] ?? null;
794
+ }
795
+
796
+ /** "Narrated by an AI voice (ElevenLabs)" in the deck's language, English where it has no line of its own. */
797
+ export function disclosureLine(engine, lang) {
798
+ const by = engine ? ` (${ENGINE_NAMES[engine] ?? engine})` : '';
799
+ const p = String(lang ?? '').split(/[-_]/)[0].toLowerCase();
800
+ const line = ({
801
+ fr: 'Narration par une voix de synthèse', de: 'Gesprochen von einer KI-Stimme', es: 'Narrado por una voz sintética',
802
+ it: 'Narrazione con una voce sintetica', pt: 'Narrado por uma voz sintética', nl: 'Ingesproken door een AI-stem',
803
+ ja: 'AI音声によるナレーション', zh: '由AI合成语音讲解', ko: 'AI 음성 내레이션',
804
+ })[p] ?? 'Narrated by an AI voice';
805
+ return `${line}${by}`;
806
+ }
807
+ const ENGINE_NAMES = { elevenlabs: 'ElevenLabs', gemini: 'Gemini', chirp: 'Google Chirp', piper: 'Piper', say: 'macOS', sapi: 'Windows' };
808
+
809
+ /** The deck with the disclosure line on its first slide, for the frames of a render. */
810
+ export function withDisclosure(html, line) {
811
+ const esc = String(line).replace(/&/g, '&amp;').replace(/</g, '&lt;');
812
+ let done = false;
813
+ return String(html).replace(/<\/section>/i, (m) => { done = true; return `<p class="decklight-disclose" data-decklight-disclose>${esc}</p>${m}`; }) + (done ? '' : '');
543
814
  }
544
815
 
545
816
  /** ffprobe argv for a file's real duration in seconds (prints one number). */
@@ -593,13 +864,14 @@ export function folderNarration(dir) {
593
864
  * (a silent deck).
594
865
  * @returns {{ dir, slides }|null}
595
866
  */
596
- export function resolveNarration(deckPath, narrationDir) {
867
+ export function resolveNarration(deckPath, narrationDir, { allowEmpty = false } = {}) {
597
868
  const load = (dir, required) => {
598
869
  const path = join(dir, 'manifest.json');
599
870
  if (!existsSync(path)) {
600
871
  if (required) {
601
872
  const byHand = folderNarration(dir);
602
873
  if (byHand) return byHand;
874
+ if (allowEmpty) return { dir, slides: [] };
603
875
  throw new Error(`--narration: no manifest.json and no slide-NN audio in ${dir} — `
604
876
  + 'record it first (decklight narrate, or decklight video --voiceover)');
605
877
  }
@@ -610,10 +882,57 @@ export function resolveNarration(deckPath, narrationDir) {
610
882
  throw new Error(`${path}: not a voiceover manifest (no slides array) — regenerate it with tools/voiceover.mjs`);
611
883
  }
612
884
  // 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 };
885
+ return { dir, slides: m.slides, engine: m.engine, model: m.model, voice: m.voice, voiceId: m.voiceId, style: m.style, format: m.format, recorder: m.recorder };
614
886
  };
615
887
  if (narrationDir) return load(resolve(narrationDir), true);
616
- return load(join(resolve(deckPath, '..'), 'voiceover'), false);
888
+ return load(join(resolve(deckPath, '..'), defaultTrackDir(resolve(deckPath))), false);
889
+ }
890
+
891
+ /** Check the chosen track without writing audio, sidecars, or video. */
892
+ export async function checkVideoTrack(html, narration, range, { face = true, character, rhubarb } = {}) {
893
+ const report = { missing: [], stale: [], lipsync: [] };
894
+ if (!narration) return report;
895
+ const texts = slideTexts(html);
896
+ const hidden = sectionBodies(html).map(isHiddenSection);
897
+ const faces = extractFaces(html);
898
+ const { on } = characterPlan(character, characterMode(html), !face);
899
+ const checkVisemes = on ? visemeCheck(narration.dir, rhubarb) : null;
900
+ const { stale } = staleSlides(narration, texts, range, priorSlideTexts(html));
901
+ const oldNotes = new Set(stale);
902
+ const manualBeats = narration.engine ? null : slideBeats(html);
903
+ const checked = new Set();
904
+ for (let n = range.from; n <= range.to; n++) {
905
+ if (hidden[n - 1]) continue;
906
+ const entry = narration.slides[n - 1];
907
+ if (oldNotes.has(n) || (manualBeats && scriptDrift(entry, manualBeats[n - 1]))) report.stale.push(n);
908
+ const files = [entry?.file, ...(entry?.segments ?? []).map((segment) => segment.file)];
909
+ const recordedBeats = entry?.segments?.length ?? 0;
910
+ const missingBeat = recordedBeats > 0 && recordedBeats < (entry.beats?.length
911
+ ?? (entry.hash ? 0 : manualBeats?.[n - 1]?.length ?? 0));
912
+ if (missingBeat || ((hasWords(texts[n - 1] ?? '') || entry)
913
+ && files.some((file) => !file || !existsSync(join(narration.dir, file))))) {
914
+ report.missing.push(n);
915
+ }
916
+ if (!checkVisemes) continue;
917
+ for (const audioName of files) {
918
+ if (!audioName || checked.has(audioName)) continue;
919
+ const p = { slide: n, audio: audioName };
920
+ const audio = join(narration.dir, audioName);
921
+ if (!existsSync(audio) || exportFaceLayout(p, faces).kind === 'hide' || faceFor(p, { narration, faces })) continue;
922
+ checked.add(audioName);
923
+ const file = audio.replace(/\.[^.]+$/, '.visemes.json');
924
+ const { why, tl } = checkVisemes({ audio, file });
925
+ let mismatch = why;
926
+ // Older sidecars may only have a duration to compare.
927
+ if (!mismatch && typeof tl.audio !== 'string' && !audio.endsWith('.wav')) {
928
+ let duration;
929
+ try { duration = Number((await run('ffprobe', ffprobeArgs(audio), { timeout: PROBE_MS })).stdout.trim()); } catch { /* unavailable */ }
930
+ mismatch = visemeMismatch(tl, { duration });
931
+ }
932
+ if (mismatch) report.lipsync.push({ slide: n, audio: audioName, why: mismatch });
933
+ }
934
+ }
935
+ return report;
617
936
  }
618
937
 
619
938
  /**
@@ -640,6 +959,7 @@ export function resolveNarration(deckPath, narrationDir) {
640
959
  export async function revoiceStale({
641
960
  html, narration, stale, log = console.log, env = process.env,
642
961
  create = createEngine, status = engineStatus, cache = createTtsCache(),
962
+ lipsync = lipsyncAfterVoicing, missing = [], onSlide = null, signal = null,
643
963
  }) {
644
964
  const { dir, engine } = narration;
645
965
  if (!engine || !ENGINES.includes(engine)) {
@@ -652,6 +972,9 @@ export async function revoiceStale({
652
972
  const project = env.GOOGLE_CLOUD_PROJECT ?? saved?.project ?? null;
653
973
  const dataDir = savedFor?.dataDir ?? (engine === 'piper' ? piperModelDir(env) : null);
654
974
  const voice = narration.voice ?? undefined;
975
+ if (!voice && !narration.voiceId) {
976
+ return { ok: false, why: `${basename(dir)}/ has no recorded voice — set it in the voice panel before regenerating` };
977
+ }
655
978
  const st = status(engine, { env, project, dataDir, voice: engine === 'piper' ? (voice ?? narration.model) : voice });
656
979
  if (!st.ready) {
657
980
  const b = engineBlocker(st, { env });
@@ -674,13 +997,19 @@ export async function revoiceStale({
674
997
  log(` re-voicing ${stale.length === 1 ? `slide ${stale[0]}` : `slides ${stale.join(', ')}`} in the track's own voice — `
675
998
  + `${clips} clip${clips === 1 ? '' : 's'} from ${engine}${voice ? ` (${voice})` : ''}`
676
999
  + `${typeof tts.cost === 'string' ? `, ${tts.cost}` : ''}; any sentence already voiced comes from the clip cache`);
677
- for (const n of stale) {
1000
+ for (const [i, n] of stale.entries()) {
1001
+ signal?.throwIfAborted();
678
1002
  const prev = readTrack(dir);
679
1003
  await synthesizeSlides({
680
- html, dir, tts, voice, style: narration.style ?? undefined,
1004
+ html, dir, tts, voice, voiceId: narration.voiceId, style: narration.style ?? undefined,
681
1005
  format: trackFormat(prev) ?? 'wav', range: { from: n, to: n }, prev, cache, log,
1006
+ force: missing.includes(n),
682
1007
  });
1008
+ onSlide?.(i + 1, stale.length);
683
1009
  }
1010
+ // the re-voiced slides' lip-sync, cut from their new audio in one parallel
1011
+ // run (#1244) — before the export checks every sidecar it will play
1012
+ if (lipsync) await lipsync({ html, dir, log });
684
1013
  return { ok: true };
685
1014
  } catch (e) {
686
1015
  return { ok: false, why: e.message };
@@ -709,14 +1038,35 @@ const have = (bin) => {
709
1038
  */
710
1039
  const STEP_PROBE = `<script>
711
1040
  (function () {
1041
+ // 0 still · 1 only its builds move · 2 it animates (SMIL, or a CSS animation
1042
+ // that loops or outlasts a build's window). The slide's own entry animation
1043
+ // is on the section itself and does not count: a cut between slides stays a cut.
1044
+ function motion(d, i) {
1045
+ var sec = d._sections[i - 1];
1046
+ if (d._hasWrittenText?.(i)) return 2;
1047
+ var inside = function (a) { var t = a.effect && a.effect.target; return t && t !== sec && sec.contains(t); };
1048
+ var long = function (a) { return !(a instanceof CSSTransition) && a.effect.getComputedTiming().endTime > ${MOTION_WINDOW_S * 1000}; };
1049
+ if (sec.querySelector('animate, animateMotion, animateTransform, set') || document.getAnimations().filter(inside).some(long)) return 2;
1050
+ d.goto(i, 0);
1051
+ document.getAnimations().forEach(function (a) { try { a.finish(); } catch (e) {} });
1052
+ d.goto(i, 1);
1053
+ return d.state.step > 0 && document.getAnimations().some(inside) ? 1 : 0;
1054
+ }
712
1055
  function report() {
713
- var d = window.__decklightProbe, out = [];
1056
+ var d = window.__decklightProbe, out = [], moves = [];
714
1057
  try {
715
1058
  for (var i = 1; i <= d.state.totalSlides; i++) { d.goto(i, ${LAST_STEP}); out.push(d.state.step); }
716
1059
  } catch (e) { out = ['err', String(e && e.message)]; }
1060
+ try {
1061
+ for (var j = 1; j <= d.state.totalSlides; j++) { d.goto(j, ${LAST_STEP}); moves.push(motion(d, j)); }
1062
+ } catch (e) { moves = []; }
717
1063
  var pre = document.createElement('pre');
718
- pre.textContent = 'DECKLIGHT-BUILD-STEPS ' + JSON.stringify(out);
1064
+ pre.textContent = 'DECKLIGHT-BUILD-STEPS ' + JSON.stringify(out) + '\\nDECKLIGHT-MOTION ' + JSON.stringify(moves);
719
1065
  document.body.appendChild(pre);
1066
+ var ch = document.createElement('pre');
1067
+ ch.textContent = 'DECKLIGHT-CHARACTER ' + JSON.stringify({ mode: d?.config?.narration?.character?.mode,
1068
+ keep: d?._sections?.map(s => !s.matches('[data-face-keep="none"]') && !!s.querySelector('[data-face-keep]')) });
1069
+ document.body.appendChild(ch);
720
1070
  }
721
1071
  if (document.readyState === 'complete') setTimeout(report, 30);
722
1072
  else window.addEventListener('load', function () { setTimeout(report, 30); });
@@ -745,6 +1095,241 @@ export function parseBuildSteps(dom, slides) {
745
1095
  return counts.length === slides ? counts : null;
746
1096
  }
747
1097
 
1098
+ /**
1099
+ * Parse the probe's per-slide motion out of a dumped DOM: 0 still, 1 only its
1100
+ * builds move, 2 it animates. Null when the deck did not report — every slide
1101
+ * then keeps the still path it had before animated capture.
1102
+ */
1103
+ export function parseMotion(dom, slides) {
1104
+ const m = /DECKLIGHT-MOTION (\[[^\]]*\])/.exec(dom);
1105
+ if (!m) return null;
1106
+ let kinds;
1107
+ try { kinds = JSON.parse(m[1]); } catch { return null; }
1108
+ if (!Array.isArray(kinds) || kinds.some((k) => ![0, 1, 2].includes(k))) return null;
1109
+ return kinds.length === slides ? kinds : null;
1110
+ }
1111
+
1112
+ /**
1113
+ * How many frames of a plan entry are captured moving (0 ⇒ the cheap still).
1114
+ * An animating slide (2) moves for the whole hold; a slide that only builds (1)
1115
+ * moves just in the first MOTION_WINDOW_S of a frame that a build led into —
1116
+ * `entered` — and every other frame of it is a still.
1117
+ */
1118
+ export function motionFrames(kind, { duration, fps, entered }) {
1119
+ if (kind === 2) return Math.ceil(duration * fps);
1120
+ if (kind === 1 && entered) return Math.min(Math.ceil(duration * fps), Math.ceil(MOTION_WINDOW_S * fps));
1121
+ return 0;
1122
+ }
1123
+
1124
+ /**
1125
+ * The motion of every plan entry: how many frames to capture moving (`count`,
1126
+ * 0 ⇒ a still), the step the page shows first when a build leads into it
1127
+ * (`from`), and how long the slide has been on screen when it starts
1128
+ * (`offset`). `kinds` is parseMotion's answer, or null for an all-still render.
1129
+ */
1130
+ export function motionPlan(plan, kinds, fps) {
1131
+ let offset = 0;
1132
+ return plan.map((p, i) => {
1133
+ const prev = plan[i - 1];
1134
+ const same = prev?.slide === p.slide;
1135
+ offset = same ? offset + prev.duration : 0;
1136
+ const entered = same && prev.step !== p.step;
1137
+ const from = entered ? prev.step : null;
1138
+ const kind = p.character || p.face?.keep ? 2 : (kinds?.[p.slide - 1] ?? 0);
1139
+ return { count: motionFrames(kind, { duration: p.duration, fps, entered }), from, offset: round(offset) };
1140
+ });
1141
+ }
1142
+
1143
+ async function loadBeat(page, url, slide, step) {
1144
+ // A hash-only navigation doesn't fire load. Start each beat fresh.
1145
+ await page.navigate('about:blank');
1146
+ await page.navigate(`${url}#/${slide}/${step}`);
1147
+ await page.evaluate('(document.fonts ? document.fonts.ready : Promise.resolve()).then(() => new Promise((r) => setTimeout(r, 400)))');
1148
+ }
1149
+
1150
+ /**
1151
+ * Photograph a moving frame: one page, every animation paused, the clock set by
1152
+ * hand to 0, 1/fps, 2/fps… — so frames are exactly a tick apart whatever the
1153
+ * machine's speed, and a loop starts from its beginning. SMIL has its own clock
1154
+ * (`setCurrentTime` on the svg); CSS animations and transitions share the
1155
+ * document's (`getAnimations`). `from` is the build step shown first: the page
1156
+ * then moves to `to`, and that transition is what the frames show — from its
1157
+ * own start, while whatever was already moving carries on from `offset`, the
1158
+ * seconds the slide has been on screen, so a loop does not restart at a build.
1159
+ * A slide's own entry animation (on the section) is finished, never played: a
1160
+ * still cuts between slides, and so does this.
1161
+ */
1162
+ export async function captureMotion(page, { url, slide, from = null, to, offset = 0, count, fps, frameAt, poses = [] }) {
1163
+ const movie = new URL(url);
1164
+ movie.searchParams.set('motion', '');
1165
+ await loadBeat(page, movie, slide, from ?? to);
1166
+ if (poses.length) await page.evaluate(characterPose(poses[0]));
1167
+ await page.evaluate(`window.__dlBefore = new Set(document.getAnimations()); window.__dlSeek = (t, offset) => {
1168
+ const own = (el) => el && el.tagName === 'SECTION' && !el.parentElement.closest('section');
1169
+ for (const s of document.querySelectorAll('svg')) { try { s.pauseAnimations(); s.setCurrentTime(t + offset); } catch {} }
1170
+ for (const a of document.getAnimations()) {
1171
+ try {
1172
+ if (own(a.effect && a.effect.target)) { a.finish(); continue; }
1173
+ a.pause();
1174
+ a.currentTime = (window.__dlBefore.has(a) ? t + offset : t) * 1000;
1175
+ } catch {}
1176
+ }
1177
+ }`);
1178
+ // The build steps through the deck itself, the way a presenter's click does:
1179
+ // a hash change is a jump, and a jump applies its builds without animating.
1180
+ if (from != null) {
1181
+ await page.evaluate(`new Promise((r) => { document.querySelector('.decklight').__decklight.goto(${slide}, ${to}); requestAnimationFrame(() => setTimeout(r, 0)); })`);
1182
+ }
1183
+ let poseIndex = 0;
1184
+ for (let i = 0; i < count; i++) {
1185
+ const time = i / fps;
1186
+ const prior = poseIndex;
1187
+ while (poses[poseIndex + 1]?.audioOffset <= time) poseIndex++;
1188
+ const pose = poseIndex !== prior ? poses[poseIndex] : null;
1189
+ await page.evaluate(`${pose ? characterPose(pose) + '; ' : ''}window.__dlSeek(${time}, ${offset})`);
1190
+ await frameAt(i, await page.screenshot());
1191
+ }
1192
+ }
1193
+
1194
+ function characterPose({ character, placement, force = false }) {
1195
+ return `document.querySelector('.decklight').__decklight.character.capture(${JSON.stringify(character)}, ${JSON.stringify(placement)}, ${force})`;
1196
+ }
1197
+ async function renderExact({ plan, kinds, chrome, url, settings, work, exec, signal, log, parallel, cache, markup, refresh }) {
1198
+ const { w, h, fps, format, quality } = settings;
1199
+ const slides = new Map();
1200
+ const motion = motionPlan(plan, kinds, fps);
1201
+ for (const [i, beat] of plan.entries()) {
1202
+ if (!slides.has(beat.slide)) slides.set(beat.slide, []);
1203
+ slides.get(beat.slide).push({ beat, motion: motion[i] });
1204
+ }
1205
+ const jobs = [...slides];
1206
+ const outputs = [];
1207
+ const failed = new AbortController();
1208
+ const captureSignal = AbortSignal.any([signal, failed.signal]);
1209
+ const run = (bin, args) => exec(bin, args, { signal: captureSignal });
1210
+ let next = 0;
1211
+ let reused = 0;
1212
+ let firstError;
1213
+ let pages = 0;
1214
+ const shared = videoDigest(JSON.stringify([markup.shared, url.slice(url.indexOf('?')), settings, 3]));
1215
+ const files = new Map();
1216
+ const digestFile = (file) => {
1217
+ if (!files.has(file)) files.set(file, videoDigest(readFileSync(file)));
1218
+ return files.get(file);
1219
+ };
1220
+ async function worker() {
1221
+ let page;
1222
+ try {
1223
+ while (next < jobs.length) {
1224
+ captureSignal.throwIfAborted();
1225
+ const index = next++;
1226
+ const [slide, beats] = jobs[index];
1227
+ const nn = String(slide).padStart(2, '0');
1228
+ const key = videoDigest(JSON.stringify([shared, markup.slides[slide - 1], beats.map(({ beat, motion }) => [
1229
+ beat, motion, beat.audio && digestFile(beat.audio), beat.face && digestFile(beat.face.clip),
1230
+ // a mouth read from the voice has no file (its poses, in `beat`, are the key)
1231
+ beat.visemeFile && existsSync(beat.visemeFile) && digestFile(beat.visemeFile),
1232
+ ])]));
1233
+ const cached = !refresh && await cache.load(slide, key, work);
1234
+ if (cached) {
1235
+ reused++;
1236
+ outputs[index] = cached;
1237
+ log(` slide ${nn}: reused`);
1238
+ continue;
1239
+ }
1240
+ if (!page && typeof WebSocket !== 'undefined') {
1241
+ page = await openPage(chrome, { w, h, signal: captureSignal });
1242
+ await page.send('Page.addScriptToEvaluateOnNewDocument', { source: 'performance.setResourceTimingBufferSize(4096)' });
1243
+ pages++;
1244
+ }
1245
+ const resources = new Set();
1246
+ const segments = [];
1247
+ for (const [i, { beat, motion: m }] of beats.entries()) {
1248
+ const id = `${nn}-${i}`;
1249
+ const dir = join(work, 'frames-' + id);
1250
+ const frame = join(dir, '00000.png');
1251
+ mkdirSync(dir);
1252
+ const count = beat.poses.length ? Math.ceil(beat.duration * fps) : m.count;
1253
+ const layer = beat.face?.keep;
1254
+ const beatUrl = new URL(url);
1255
+ if (layer) beatUrl.searchParams.set('capture', 'face-layer');
1256
+ if (page) await page.send('Emulation.setDefaultBackgroundColorOverride', layer ? { color: { r: 0, g: 0, b: 0, a: 0 } } : {});
1257
+ if (page && count) {
1258
+ await captureMotion(page, {
1259
+ url: beatUrl, slide, from: m.from, to: beat.step, offset: m.offset, count, fps, poses: beat.poses,
1260
+ frameAt: (f, png) => writeFile(join(dir, String(f).padStart(5, '0') + '.png'), png, { signal: captureSignal }),
1261
+ });
1262
+ } else if (page) {
1263
+ await loadBeat(page, beatUrl, slide, beat.step);
1264
+ writeFileSync(frame, await page.screenshot());
1265
+ } else {
1266
+ if (beat.poses.length) throw new Error('animated character export needs Node 22 or later');
1267
+ await run(chrome, chromeArgs(
1268
+ '--hide-scrollbars', '--autoplay-policy=no-user-gesture-required', `--window-size=${w},${h}`,
1269
+ ...(layer ? ['--default-background-color=00000000'] : []),
1270
+ '--virtual-time-budget=1500', `--screenshot=${frame}`, `${beatUrl}#/${slide}/${beat.step}`,
1271
+ ));
1272
+ }
1273
+ if (page) {
1274
+ for (const resource of await page.evaluate("performance.getEntriesByType('resource').map((entry) => entry.name)")) {
1275
+ resources.add(resource);
1276
+ }
1277
+ }
1278
+ const out = join(work, `seg-${id}.${format}`);
1279
+ const args = segmentArgs({
1280
+ ...beat, frame, frames: count && page ? { pattern: join(dir, '%05d.png'), count } : null,
1281
+ fps, out, format, quality, size: { w, h },
1282
+ });
1283
+ // Each worker can encode at the same time. Use the same encoder
1284
+ // thread count in serial and parallel exports.
1285
+ await run('ffmpeg', ['-filter_threads', '1', '-filter_complex_threads', '1',
1286
+ ...args.slice(0, -1), '-threads:v', '2', out]);
1287
+ rmSync(dir, { recursive: true, force: true });
1288
+ segments.push(out);
1289
+ const where = beat.step === LAST_STEP ? '' : ` · build ${beat.step}`;
1290
+ const moving = count && page ? ` · moving ${(count / fps).toFixed(1)}s` : '';
1291
+ log(` slide ${nn}${where}: ${beat.duration.toFixed(1)}s ${beat.audio ? basename(beat.audio) : '(silence)'}${moving}`);
1292
+ }
1293
+ outputs[index] = segments;
1294
+ if (page && markup.slides.length >= slide) {
1295
+ await cache.save(slide, key, segments, resources).catch((error) => console.warn(` video cache: ${error.message}`));
1296
+ }
1297
+ }
1298
+ } catch (error) {
1299
+ firstError ??= error;
1300
+ failed.abort();
1301
+ } finally {
1302
+ await page?.close();
1303
+ }
1304
+ }
1305
+ log(` exact: up to ${parallel} Chrome pages in parallel`);
1306
+ const results = await Promise.allSettled(Array.from({ length: parallel }, worker));
1307
+ firstError ??= results.find((result) => result.status === 'rejected')?.reason;
1308
+ if (firstError) throw firstError;
1309
+ log(` exact: ${pages} Chrome pages ran in parallel; reused ${reused} of ${jobs.length} slides`);
1310
+ return outputs.flat();
1311
+ }
1312
+
1313
+ export function parseCharacterConfig(dom) {
1314
+ const m = /DECKLIGHT-CHARACTER (\{[^\n<]*\})/.exec(dom);
1315
+ if (!m) return {};
1316
+ try { return JSON.parse(m[1]); } catch { return {}; }
1317
+ }
1318
+
1319
+ /**
1320
+ * Is the animated character in this render, and must the page be told to draw
1321
+ * it? `--character` says it outright (the export card sends who is on screen
1322
+ * in the deck, which a fresh browser cannot see); without it the deck's own
1323
+ * `narration.character.mode` decides. `--no-face` leaves it out either way.
1324
+ * Forced only when asked for by name: a deck whose config already turns the
1325
+ * character on draws it unprompted.
1326
+ */
1327
+ export function characterPlan(ask, configMode, noFace = false) {
1328
+ if (ask !== undefined && !['viseme', 'off'].includes(ask)) throw new Error('--character must be viseme or off');
1329
+ const on = (ask ?? configMode) === 'viseme' && !noFace;
1330
+ return { on, force: on && ask === 'viseme' };
1331
+ }
1332
+
748
1333
  export async function videoMain(argv, { exec: execRaw = run, log = console.log } = {}) {
749
1334
  const { opt } = argReader(argv);
750
1335
  const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
@@ -779,27 +1364,29 @@ export async function videoMain(argv, { exec: execRaw = run, log = console.log }
779
1364
  process.exit(1);
780
1365
  }
781
1366
 
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.
1367
+ // The editor and Ctrl-C share cancellation. Abort the renderer's child
1368
+ // processes and clean up the work directory before reporting completion.
788
1369
  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;
1370
+ const stop = () => stopping.abort();
1371
+ const onMessage = (message) => { if (message === 'stop-video') stop(); };
1372
+ process.once('SIGTERM', stop);
1373
+ process.once('SIGINT', stop);
1374
+ if (process.channel) {
1375
+ process.on('message', onMessage);
1376
+ process.channel.unref();
1377
+ }
1378
+ const exec = (bin, args, opts = {}) => execRaw(bin, args, { signal: stopping.signal, ...opts });
795
1379
 
796
- let out; let plan; let narration;
797
1380
  try {
798
1381
  const named = opt('-o', opt('--out'));
799
1382
  const { format, quality, subtitles } = videoOptions({
800
1383
  out: named, format: opt('--format'), quality: opt('--quality'), subtitles: opt('--subtitles'),
801
1384
  });
802
- out = resolve(named ?? videoOut(deck, opt('--slides'), format));
1385
+ const render = opt('--render', 'exact');
1386
+ if (!valuesOf(VIDEO_RENDER_MODES).includes(render)) throw new Error('--render must be exact or live');
1387
+ const parallel = Number(opt('--parallel', String(Math.min(availableParallelism(), 6))));
1388
+ if (!Number.isSafeInteger(parallel) || parallel < 1) throw new Error('--parallel must be a positive integer');
1389
+ const out = resolve(named ?? videoOut(deck, opt('--slides'), format));
803
1390
  const { w, h } = parseSize(opt('--size', '1280x720'));
804
1391
  const fps = Number(opt('--fps', '30'));
805
1392
  const hold = Number(opt('--hold', '5'));
@@ -827,23 +1414,26 @@ export async function videoMain(argv, { exec: execRaw = run, log = console.log }
827
1414
 
828
1415
  // --no-narration is silence asked for by name: without it, a voiceover/
829
1416
  // beside the deck narrates whether or not that was the voice wanted
830
- narration = argv.includes('--no-narration') ? null : resolveNarration(deck, opt('--narration'));
1417
+ let narration = argv.includes('--no-narration') ? null : resolveNarration(deck, opt('--narration'));
831
1418
  // Is the track still THIS deck's notes? Each manifest slide carries the
832
1419
  // hash of the notes it was voiced from; a slide whose notes moved since
833
1420
  // would speak against its own captions, so it is named and, unless asked
834
1421
  // for by name, refused (#536). Only the slides being rendered are checked.
835
1422
  if (narration) {
1423
+ const visible = argv.includes('--no-remake-visemes') ? sectionBodies(html).map((sec) => !isHiddenSection(sec)) : null;
836
1424
  let { stale, hashless } = staleSlides(narration, slideTexts(html), range, priorSlideTexts(html));
1425
+ if (visible) stale = stale.filter((n) => visible[n - 1]);
837
1426
  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
1427
  for (const n of stale) console.warn(` slide ${n}: narration was recorded from different notes`);
839
1428
  // A machine-voiced track fixes itself: its stale slides are voiced again
840
1429
  // in its own voice, and the check runs again on what that wrote (#553).
841
1430
  let unrevoiced = null;
842
1431
  if (stale.length && !argv.includes('--no-revoice')) {
843
- const r = await revoiceStale({ html, narration, stale, log });
1432
+ const r = await revoiceStale({ html, narration, stale, log, ...(argv.includes('--no-face') ? { lipsync: null } : {}) });
844
1433
  if (r.ok) {
845
1434
  narration = resolveNarration(deck, narration.dir);
846
1435
  ({ stale } = staleSlides(narration, slideTexts(html), range, priorSlideTexts(html)));
1436
+ if (visible) stale = stale.filter((n) => visible[n - 1]);
847
1437
  } else {
848
1438
  unrevoiced = r.why;
849
1439
  console.warn(` not re-voiced: ${r.why}`);
@@ -852,9 +1442,12 @@ export async function videoMain(argv, { exec: execRaw = run, log = console.log }
852
1442
  if (stale.length) {
853
1443
  const which = stale.length === 1 ? `slide ${stale[0]}` : `slides ${stale.join(', ')}`;
854
1444
  if (!argv.includes('--allow-stale')) {
1445
+ // the two fixes have two names (#919): your own voice is
1446
+ // re-recorded at the microphone, an engine's track is re-voiced
1447
+ const fix = narration.engine ? 're-voice' : 're-record';
855
1448
  throw new Error(`the narration in ${narration.dir} was recorded from older notes on ${which}`
856
1449
  + `${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`);
1450
+ + `${fix} ${stale.length === 1 ? 'it' : 'them'} from the deck (V, then › on ${basename(narration.dir)}) or pass --allow-stale`);
858
1451
  }
859
1452
  console.warn(` --allow-stale: rendering ${which} with the older narration`);
860
1453
  }
@@ -893,16 +1486,26 @@ export async function videoMain(argv, { exec: execRaw = run, log = console.log }
893
1486
  // `?gen=` the same way, for a theme that lives only in a browser.
894
1487
  const renderQuery = `?${['capture', ...themeParams].join('&')}`;
895
1488
  let probing = false;
1489
+ // a video voiced by an AI voice says so (TRANSLATION_VOICE): in its
1490
+ // metadata unless --no-disclose, and on its first slide with --disclose
1491
+ const deckLanguage = deckLang(html);
1492
+ const aiVoice = narration?.engine && !argv.includes('--no-disclose') ? narration.engine : null;
1493
+ const disclosure = aiVoice ? disclosureLine(aiVoice, deckLanguage) : null;
1494
+ const showDisclosure = !!disclosure && argv.includes('--disclose');
896
1495
  const inject = (text, file) => {
897
- if (resolve(file) !== deck || !probing) return text;
898
- return injectBeforeBodyEnd(exposeInstance(text), STEP_PROBE) ?? text;
1496
+ if (resolve(file) !== deck) return text;
1497
+ if (probing) return injectBeforeBodyEnd(exposeInstance(text), STEP_PROBE) ?? text;
1498
+ return showDisclosure ? withDisclosure(text, disclosure) : text;
899
1499
  };
900
- const deckPath = '/' + relative(root, deck).split(sep).join('/');
1500
+ const deckPath = '/' + relative(root, deck).split(sep).map(encodeURIComponent).join('/');
901
1501
 
1502
+ const chrome = chromeBin('video');
902
1503
  const work = mkdtempSync(join(tmpdir(), 'decklight-video-'));
903
- const server = await serveForRender(root, { html: inject });
1504
+ const media = new Map();
1505
+ let server;
1506
+ let total;
904
1507
  try {
905
- const chrome = chromeBin('video');
1508
+ server = await serveForRender(root, { html: inject, media });
906
1509
 
907
1510
  // Ask the deck how far each slide builds, in one extra load, before any
908
1511
  // frame is captured. A deck that will not answer is not an error: the
@@ -910,56 +1513,79 @@ export async function videoMain(argv, { exec: execRaw = run, log = console.log }
910
1513
  // command did before builds had frames of their own.
911
1514
  probing = true;
912
1515
  let steps = null;
1516
+ let kinds = null;
1517
+ let characterConfig = {};
913
1518
  try {
914
1519
  const dom = await exec(chrome, chromeArgs(
915
- '--hide-scrollbars', `--window-size=${w},${h}`,
1520
+ '--hide-scrollbars', `--window-size=${w},${h}`, `--user-data-dir=${join(work, 'probe')}`,
916
1521
  '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}${renderQuery}`,
917
- ), { maxBuffer: 64 * 1024 * 1024 });
1522
+ ), { maxBuffer: 64 * 1024 * 1024, timeout: 20000 });
918
1523
  steps = parseBuildSteps(dom.stdout, holds.length);
1524
+ kinds = parseMotion(dom.stdout, holds.length);
1525
+ characterConfig = parseCharacterConfig(dom.stdout);
919
1526
  } catch { /* fall through to one frame per slide */ }
920
1527
  probing = false;
921
1528
  if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
1529
+ else if (!kinds) console.warn(' motion: the deck did not report which slides move — every frame a still');
922
1530
 
923
- plan = planTimeline(narration?.slides ?? null, durations, holds, range,
1531
+ const basePlan = planTimeline(narration?.slides ?? null, durations, holds, range,
924
1532
  { steps, buildHold, pauses, marks: pauseMarks(html, steps), onWarn: (w) => console.warn(` ${w}`) });
1533
+ const faces = extractFaces(html);
1534
+ const faceOn = !argv.includes('--no-face');
1535
+ const faceContext = { narration, faces, defaultCorner: characterConfig.position };
1536
+ // the drawn character: the export card names it (a fresh browser cannot
1537
+ // see the panel's choice), else the deck's own config decides
1538
+ const { on: characterOn, force: characterForce } = characterPlan(opt('--character'), characterConfig.mode, !faceOn);
1539
+ const drafts = basePlan.map((p) => {
1540
+ const face = faceOn ? faceFor(p, faceContext) : null;
1541
+ if (face?.kind === 'full' && characterConfig.keep?.[p.slide - 1]) face.keep = true;
1542
+ const placement = exportFaceLayout(p, faces);
1543
+ const audio = p.audio ? join(narration.dir, p.audio) : null;
1544
+ const visemeFile = characterOn && audio && !face && placement.kind !== 'hide'
1545
+ ? audio.replace(/\.[^.]+$/, '.visemes.json') : null;
1546
+ return { p, audio, face, placement, visemeFile };
1547
+ });
1548
+ // Every sidecar is checked against the audio it will play beside before
1549
+ // a frame is drawn (#1244): one another recording left behind would have
1550
+ // the character mouth that recording. Missing or out of step, it is
1551
+ // made again when Rhubarb is here, and the export stops otherwise.
1552
+ const timelines = await visemesFor(drafts.filter((d) => d.visemeFile)
1553
+ .map((d) => ({ audio: d.audio, file: d.visemeFile, duration: durations[d.p.audio] })),
1554
+ { dir: narration?.dir, deck, log, skipBad: argv.includes('--no-remake-visemes') });
1555
+ const plan = drafts.map(({ p, audio, face, placement, visemeFile }) => {
1556
+ const poses = visemeFile && timelines.has(visemeFile)
1557
+ ? characterFrames({ ...p, placement }, timelines.get(visemeFile)).filter((pose) => pose.character)
1558
+ .map((pose) => ({ ...pose, force: characterForce }))
1559
+ : [];
1560
+ return { ...p, audio, face, poses, visemeFile };
1561
+ });
1562
+ if (!plan.length) throw new Error('the selected range has no visible slides');
925
1563
  const slideCount = new Set(plan.map((p) => p.slide)).size;
926
- log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
927
- + `${plan.filter((p) => p.audio).length} narrated`
928
- + (plan.length > slideCount ? `, ${plan.length} frames` : '')
929
- + (narration ? ` (${narration.dir})` : ' (silent)'));
930
-
931
- const segments = [];
932
- let f = 0;
933
- for (const p of plan) {
934
- const nn = String(p.slide).padStart(2, '0');
935
- const id = `${nn}-${String(f++).padStart(3, '0')}`;
936
- const frame = join(work, `frame-${id}.png`);
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)
940
- await exec(chrome, chromeArgs(
941
- '--hide-scrollbars',
942
- '--autoplay-policy=no-user-gesture-required',
943
- `--window-size=${w},${h}`,
944
- '--virtual-time-budget=1500',
945
- `--screenshot=${frame}`,
946
- `${server.origin}${deckPath}${renderQuery}#/${p.slide}/${p.step}`,
947
- ));
948
- if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
949
- const seg = join(work, `seg-${id}.${ENCODINGS[format].ext}`);
950
- await exec('ffmpeg', segmentArgs({
951
- frame, duration: p.duration, pad: p.pad, fps, out: seg, format, quality,
952
- audio: p.audio ? join(narration.dir, p.audio) : null,
953
- }));
954
- segments.push(seg);
955
- const where = p.step === LAST_STEP ? '' : ` · build ${p.step}`;
956
- log(` slide ${nn}${where}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
957
- }
1564
+ log(basename(deck) + ': ' + slideCount + (slideCount === 1 ? ' slide, ' : ' slides, ')
1565
+ + plan.filter((p) => p.audio).length + ' narrated (' + (narration?.dir ?? 'silent') + ')');
1566
+ const characterBeats = plan.filter((p) => p.poses.length).length;
1567
+ if (characterBeats) log(` animated character: ${characterBeats} narration beat(s)`);
1568
+ const url = server.origin + deckPath + renderQuery;
1569
+ const settings = { w, h, fps, format, quality };
1570
+ const segments = render === 'live'
1571
+ ? [await captureLive({
1572
+ plan, chrome, url: server.origin + deckPath + '?' + ['capture=live', ...themeParams].join('&'),
1573
+ settings, work, exec, signal: stopping.signal, media, log,
1574
+ encoding: ENCODINGS[format],
1575
+ })]
1576
+ : await renderExact({
1577
+ plan, kinds, chrome, url, settings, work, exec, signal: stopping.signal, log,
1578
+ parallel: Math.min(parallel, availableParallelism(), slideCount),
1579
+ cache: videoCache({ out, origin: server.origin, deckUrl: url, signal: stopping.signal }),
1580
+ markup: videoMarkup(await (await fetch(url, { signal: stopping.signal })).text()),
1581
+ refresh: argv.includes('--no-cache'),
1582
+ });
958
1583
 
959
1584
  // Subtitles are the words the audio speaks: the script voiceover wrote
960
1585
  // beside each clip when there is one (it may have been edited to change
961
1586
  // what is said), the deck's own notes for that beat when there is not.
962
1587
  let embedded = null;
1588
+ let sidecar = null;
963
1589
  if (subtitles !== 'none') {
964
1590
  const sections = sectionBodies(html);
965
1591
  const textOf = (p) => {
@@ -971,38 +1597,57 @@ export async function videoMain(argv, { exec: execRaw = run, log = console.log }
971
1597
  return k >= 0 ? (notesSegments(notes, { marks: true })?.[k] ?? '') : cleanNotes(notes, { marks: true });
972
1598
  };
973
1599
  const markHolds = markerPauses(html);
974
- const cues = narration ? subtitleCues(plan, textOf, (p) => markHolds[p.slide - 1] ?? 0) : [];
1600
+ const cues = narration ? subtitleCues(basePlan, textOf, (p) => markHolds[p.slide - 1] ?? 0, { max: cueMaxChars(deckLanguage) }) : [];
975
1601
  const enc = ENCODINGS[format];
976
1602
  if (!cues.length) {
977
1603
  console.warn(' subtitles: nothing is spoken in this render — none written');
978
1604
  } else {
979
- const file = subtitles === 'embed' ? join(work, `subtitles.${enc.subtitleExt}`) : subtitlesOut(out, format);
980
- writeFileSync(file, enc.subtitleExt === 'vtt' ? toVtt(cues) : toSrt(cues));
1605
+ const file = join(work, `subtitles.${enc.subtitleExt}`);
1606
+ writeFileSync(file, enc.subtitleExt === 'vtt' ? toVtt(cues, { lang: deckLanguage }) : toSrt(cues));
981
1607
  if (subtitles === 'embed') embedded = file;
982
- log(` subtitles: ${cues.length} cue${cues.length === 1 ? '' : 's'} ${subtitles === 'embed' ? 'embedded' : `→ ${file}`}`);
1608
+ else sidecar = file;
1609
+ log(` subtitles: ${cues.length} cue${cues.length === 1 ? '' : 's'} ${embedded ? 'embedded' : `→ ${subtitlesOut(out, format)}`}`);
983
1610
  }
984
1611
  }
985
1612
 
986
- const list = join(work, 'concat.txt');
987
- writeFileSync(list, concatList(segments));
988
- writing = true;
989
- await exec('ffmpeg', concatArgs(list, out, { format, subtitles: embedded }));
990
- writing = false;
1613
+ const concat = render === 'exact';
1614
+ const input = concat ? join(work, 'concat.txt') : segments[0];
1615
+ if (concat) writeFileSync(input, concatList(segments));
1616
+ const outputDir = mkdtempSync(join(dirname(out), '.decklight-output-'));
1617
+ try {
1618
+ const name = basename(out);
1619
+ const staged = join(outputDir, name.toLowerCase().endsWith('.' + format) ? name : name + '.' + format);
1620
+ await exec('ffmpeg', concatArgs(input, staged, {
1621
+ format, subtitles: embedded, concat, lang: deckLanguage, audio: !!narration,
1622
+ comment: disclosure ? `${disclosure} — a synthetic voice, not a recording of a person` : null,
1623
+ }));
1624
+ total = Number((await exec('ffprobe', ffprobeArgs(staged))).stdout.trim());
1625
+ const stagedSidecar = sidecar && join(outputDir, basename(sidecar));
1626
+ if (stagedSidecar) writeFileSync(stagedSidecar, readFileSync(sidecar));
1627
+ stopping.signal.throwIfAborted();
1628
+ renameSync(staged, out);
1629
+ if (stagedSidecar) renameSync(stagedSidecar, subtitlesOut(out, format));
1630
+ } finally {
1631
+ rmSync(outputDir, { recursive: true, force: true });
1632
+ }
991
1633
  } finally {
992
- await server.close();
993
- rmSync(work, { recursive: true, force: true });
1634
+ try { await server?.close(); } finally {
1635
+ rmSync(work, { recursive: true, force: true, maxRetries: 5 });
1636
+ }
994
1637
  }
995
1638
 
996
- const total = Number((await exec('ffprobe', ffprobeArgs(out))).stdout.trim());
997
1639
  log(`done → ${out} (${total.toFixed(1)}s)`);
998
1640
  } catch (e) {
999
1641
  if (stopping.signal.aborted) {
1000
- if (writing) rmSync(out, { force: true });
1001
1642
  console.error('decklight video: stopped — no video written');
1002
1643
  process.exit(143);
1003
1644
  }
1004
1645
  console.error(`decklight video: ${e.message}`);
1005
1646
  process.exit(1);
1647
+ } finally {
1648
+ process.removeListener('SIGTERM', stop);
1649
+ process.removeListener('SIGINT', stop);
1650
+ process.removeListener('message', onMessage);
1006
1651
  }
1007
1652
  }
1008
1653