decklight 0.9.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 (133) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +61 -3
  3. package/README.md +58 -28
  4. package/SPEC.md +1326 -85
  5. package/cli/agent-review.mjs +5 -4
  6. package/cli/agents.mjs +148 -18
  7. package/cli/bundle-audio.mjs +10 -3
  8. package/cli/bundle-module.mjs +95 -0
  9. package/cli/bundle.mjs +125 -7
  10. package/cli/cast.mjs +86 -19
  11. package/cli/check-fixes.mjs +194 -0
  12. package/cli/check-watch.mjs +151 -0
  13. package/cli/check.mjs +491 -75
  14. package/cli/code-editor.mjs +287 -0
  15. package/cli/commands.mjs +13 -2
  16. package/cli/commit-flow.mjs +7 -3
  17. package/cli/commit-message.mjs +35 -8
  18. package/cli/commit-split.mjs +125 -25
  19. package/cli/deck-refs.mjs +8 -3
  20. package/cli/decklight.mjs +11 -1
  21. package/cli/design-system-edit.mjs +37 -1
  22. package/cli/design-system-refs.mjs +263 -6
  23. package/cli/design-system.mjs +82 -14
  24. package/cli/edit-address.mjs +184 -0
  25. package/cli/edit-git.mjs +23 -6
  26. package/cli/edit-handover.mjs +257 -40
  27. package/cli/edit-look.mjs +293 -6
  28. package/cli/edit-open.mjs +143 -0
  29. package/cli/edit-slides.mjs +1043 -67
  30. package/cli/edit-translate.mjs +243 -0
  31. package/cli/edit.mjs +3680 -319
  32. package/cli/editor-support.mjs +286 -0
  33. package/cli/enhance.mjs +157 -27
  34. package/cli/find-replace.mjs +142 -0
  35. package/cli/fix-review.mjs +368 -0
  36. package/cli/git.mjs +13 -0
  37. package/cli/init.mjs +101 -22
  38. package/cli/keep-awake.mjs +68 -0
  39. package/cli/marketplace-autocheck.mjs +200 -0
  40. package/cli/marketplace.mjs +250 -13
  41. package/cli/migrate-writing.mjs +214 -0
  42. package/cli/narrate.mjs +121 -5
  43. package/cli/open.mjs +53 -15
  44. package/cli/outside-edit.mjs +257 -0
  45. package/cli/paste.mjs +92 -0
  46. package/cli/pdf.mjs +88 -10
  47. package/cli/pptx-export.mjs +10 -5
  48. package/cli/publish.mjs +24 -3
  49. package/cli/record.mjs +86 -15
  50. package/cli/remote.mjs +32 -6
  51. package/cli/rewrite.mjs +265 -0
  52. package/cli/runtime-link.mjs +218 -17
  53. package/cli/serve.mjs +9 -6
  54. package/cli/setup.mjs +2 -2
  55. package/cli/skill-content.mjs +251 -10
  56. package/cli/skills/slide-writing.md +333 -0
  57. package/cli/skills/voiceover.md +423 -0
  58. package/cli/skills.mjs +282 -15
  59. package/cli/starter-full.mjs +353 -0
  60. package/cli/supervise.mjs +14 -0
  61. package/cli/theme-refs.mjs +14 -2
  62. package/cli/theme.mjs +3 -2
  63. package/cli/translate-core.mjs +466 -0
  64. package/cli/translate-files.mjs +149 -0
  65. package/cli/translate.mjs +458 -0
  66. package/cli/units.mjs +75 -7
  67. package/cli/util.mjs +25 -0
  68. package/cli/vocabulary-docs.mjs +138 -0
  69. package/dist/decklight.css +2506 -113
  70. package/dist/decklight.js +385 -175
  71. package/dist/decklight.js.map +4 -4
  72. package/docs/GLOSSARY.md +9 -2
  73. package/docs/WRITING_RESEARCH.md +327 -0
  74. package/package.json +5 -3
  75. package/themes/coastal.css +3 -0
  76. package/themes/metropolis.css +2 -0
  77. package/themes/reveal-blood.css +3 -0
  78. package/themes/reveal-league.css +2 -0
  79. package/themes/reveal-moon.css +2 -0
  80. package/themes/reveal-serif.css +1 -0
  81. package/themes/reveal-sky.css +1 -0
  82. package/themes/reveal-solarized.css +4 -0
  83. package/tools/brand-palette.mjs +6 -1
  84. package/tools/build-groups.mjs +28 -8
  85. package/tools/cdp.mjs +176 -0
  86. package/tools/chart-spec.mjs +242 -0
  87. package/tools/click-match.mjs +70 -0
  88. package/tools/code-options.mjs +174 -0
  89. package/tools/conversation.mjs +49 -0
  90. package/tools/deck-family.mjs +101 -0
  91. package/tools/deck-html.mjs +212 -15
  92. package/tools/design-system-format.mjs +40 -1
  93. package/tools/design-system-migrations.mjs +207 -0
  94. package/tools/diagram-shapes.mjs +221 -0
  95. package/tools/elevenlabs-tts.mjs +62 -53
  96. package/tools/exec.mjs +10 -2
  97. package/tools/face-clip.mjs +96 -0
  98. package/tools/face-layout.mjs +94 -0
  99. package/tools/gemini-tts.mjs +1 -1
  100. package/tools/invisible-in-print.mjs +27 -0
  101. package/tools/lipsync-auto.mjs +197 -0
  102. package/tools/lipsync-config.mjs +16 -0
  103. package/tools/lipsync-engines.mjs +22 -4
  104. package/tools/lipsync-server.mjs +8 -5
  105. package/tools/lipsync.mjs +122 -30
  106. package/tools/local-voice.mjs +1 -1
  107. package/tools/mouth-file.mjs +26 -0
  108. package/tools/mouth.mjs +320 -0
  109. package/tools/narration-manifest.mjs +100 -6
  110. package/tools/narration-synth.mjs +96 -76
  111. package/tools/recording-impact.mjs +16 -1
  112. package/tools/sentences.mjs +7 -1
  113. package/tools/site-clip.mjs +114 -0
  114. package/tools/starters.mjs +402 -0
  115. package/tools/steps.mjs +118 -0
  116. package/tools/take-check.mjs +146 -0
  117. package/tools/template-theme.mjs +3 -1
  118. package/tools/test-impact.mjs +36 -12
  119. package/tools/theme-check.mjs +196 -1
  120. package/tools/tone-cue.mjs +108 -0
  121. package/tools/tts-cache.mjs +9 -3
  122. package/tools/tts-engines.mjs +100 -11
  123. package/tools/video-cache.mjs +93 -0
  124. package/tools/video-live.mjs +349 -0
  125. package/tools/video-options.mjs +11 -0
  126. package/tools/video.mjs +825 -117
  127. package/tools/viseme-fit.mjs +27 -0
  128. package/tools/viseme-match.mjs +77 -0
  129. package/tools/vocabulary.mjs +397 -0
  130. package/tools/voice-renumber.mjs +605 -0
  131. package/tools/voiceover-server.mjs +42 -11
  132. package/tools/voiceover.mjs +48 -20
  133. package/dist/build-info.json +0 -1
@@ -27,7 +27,7 @@
27
27
  // Needs $ELEVENLABS_API_KEY (never saved to disk). Metered in
28
28
  // characters against a plan allowance we cannot see, so it reports
29
29
  // characters and no dollar estimate. Style reaches only the tag
30
- // models — eleven_v4 (the default), eleven_v4_turbo, eleven_v3 —
30
+ // models — eleven_v4_turbo (the default), eleven_v4, eleven_v3 —
31
31
  // whose delivery channel is bracketed audio tags read as direction,
32
32
  // not words; so `stylable` and `audioTags` here depend on the model
33
33
  // chosen, not just the engine.
@@ -50,20 +50,77 @@ import { delimiter, join } from 'node:path';
50
50
  import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId, authHeaders } from './gemini-tts.mjs';
51
51
  import { run, PROBE_MS, NETWORK_MS } from './exec.mjs';
52
52
  import {
53
- createSynth as createElevenLabs, apiKey as elevenLabsKey, KEY_ENV as ELEVENLABS_KEY_ENV,
54
- DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL, readsAudioTags,
53
+ createSynth as createElevenLabs, pickVoice, apiKey as elevenLabsKey, KEY_ENV as ELEVENLABS_KEY_ENV,
54
+ DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL, readsAudioTags, languageCode,
55
55
  } from './elevenlabs-tts.mjs';
56
56
  import {
57
57
  detectLocalVoice, sayArgs, sapiArgs, winrtArgs, TIER_LABEL, withoutSupersededPlain, baseName,
58
58
  } from './local-voice.mjs';
59
59
 
60
60
  export const ENGINES = ['gemini', 'chirp', 'piper', 'elevenlabs', 'say', 'sapi'];
61
+
62
+ /** `fr-CA` → `fr`; null for nothing. */
63
+ export const primaryLang = (lang) => String(lang ?? '').trim().split(/[-_]/)[0].toLowerCase() || null;
64
+
65
+ /**
66
+ * The language the voice is asked for (SPEC PRESENTING_VOICE): a `--lang`
67
+ * flag, else the deck's own `<html lang>` when the deck is not in English,
68
+ * else the language saved by `decklight setup voice --lang`.
69
+ *
70
+ * An English deck names no language here, deliberately. `en` is what
71
+ * `decklight init` writes into every deck, so it says "nobody chose" far more
72
+ * often than "this is English", and it must not outrank a language somebody
73
+ * saved on purpose; and English is what every engine assumed before a deck's
74
+ * language reached it, so sending nothing is what keeps those takes current.
75
+ */
76
+ export function voiceLang({ flag, deck, saved } = {}) {
77
+ const fromDeck = primaryLang(deck) && primaryLang(deck) !== 'en' ? deck : undefined;
78
+ return flag ?? fromDeck ?? saved ?? undefined;
79
+ }
80
+
81
+ // Chirp names a voice by locale (`fr-FR-Chirp3-HD-Kore`), and a deck usually
82
+ // says only `fr`. The region each bare language gets; a deck that says
83
+ // `fr-CA` is taken at its word.
84
+ const CHIRP_REGION = {
85
+ ar: 'ar-XA', de: 'de-DE', en: 'en-US', es: 'es-ES', fr: 'fr-FR', hi: 'hi-IN', it: 'it-IT', ja: 'ja-JP',
86
+ ko: 'ko-KR', nl: 'nl-NL', pl: 'pl-PL', pt: 'pt-BR', ru: 'ru-RU', tr: 'tr-TR', zh: 'cmn-CN',
87
+ };
88
+ /** The Chirp locale for a language tag; throws on one it cannot place, never guesses English. */
89
+ export function chirpLocale(lang) {
90
+ const tag = String(lang ?? '').trim().replace('_', '-');
91
+ if (!tag) return 'en-US';
92
+ const full = /^([a-z]{2,3})-([a-z]{2})$/i.exec(tag);
93
+ if (full) return `${full[1].toLowerCase()}-${full[2].toUpperCase()}`;
94
+ const region = CHIRP_REGION[primaryLang(tag)];
95
+ if (!region) throw new Error(`chirp needs a locale for the language '${tag}' — pass --lang, as in --lang ${primaryLang(tag)}-XX`);
96
+ return region;
97
+ }
61
98
  /** The two engines that are already on the machine — nothing to install. */
62
99
  export const NATIVE_ENGINES = ['say', 'sapi'];
63
100
 
64
101
  // Piper's defaults, shared with the setup wizard (tools/tts-setup.mjs) so the
65
102
  // model it checks for is the model createPiper will load.
66
103
  export const PIPER_DEFAULT_VOICE = 'en_US-ryan-high';
104
+
105
+ /**
106
+ * Piper's voice for a language when none is named (SPEC TRANSLATION_VOICE):
107
+ * piper has one model per language, so the English default reads a French
108
+ * deck in English. One voice per language, each a key of piper's own catalog
109
+ * (rhasspy/piper-voices voices.json), high quality where there is one. A
110
+ * language not listed keeps the English default, which the bridge's startup
111
+ * line names, rather than a guessed name that would fail to download.
112
+ */
113
+ export const PIPER_VOICES = {
114
+ en: PIPER_DEFAULT_VOICE, fr: 'fr_FR-siwis-medium', de: 'de_DE-thorsten-high', es: 'es_AR-daniela-high',
115
+ it: 'it_IT-serena-high', pt: 'pt_BR-cadu-medium', nl: 'nl_NL-alex-medium', pl: 'pl_PL-bass-high',
116
+ ru: 'ru_RU-denis-medium', zh: 'zh_CN-chaowen-medium', uk: 'uk_UA-mykyta-high', sv: 'sv_SE-alma-medium',
117
+ fi: 'fi_FI-harri-medium', tr: 'tr_TR-dfki-medium', cs: 'cs_CZ-jirka-medium', da: 'da_DK-talesyntese-medium',
118
+ no: 'no_NO-nvcc-medium', nb: 'no_NO-nvcc-medium', el: 'el_GR-joy-medium', hu: 'hu_HU-anna-medium',
119
+ ro: 'ro_RO-mihai-medium', vi: 'vi_VN-vais1000-medium', ar: 'ar_JO-kareem-medium', ca: 'ca_ES-upc_ona-medium',
120
+ };
121
+
122
+ /** The piper voice for `lang`: its own, else the English default. */
123
+ export const piperVoiceFor = (lang) => PIPER_VOICES[primaryLang(lang) ?? 'en'] ?? PIPER_DEFAULT_VOICE;
67
124
  export const piperModelDir = (env = process.env) =>
68
125
  join(env.HOME || homedir(), '.local', 'share', 'piper');
69
126
 
@@ -428,6 +485,32 @@ function createNative({
428
485
  };
429
486
  }
430
487
 
488
+ export async function listVoiceIdentities(engine, { refresh = false } = {}) {
489
+ if (engine.listVoices) {
490
+ return (await engine.listVoices({ refresh })).map(({ id, name, flavor }) => ({ id: id ?? name, name, flavor }));
491
+ }
492
+ return (engine.voices ?? []).map(([name, flavor]) => ({ id: name, name, flavor }));
493
+ }
494
+
495
+ /** Resolve before a cache lookup or synthesis, so the key and audio describe the same voice. */
496
+ export async function resolveTtsVoice(engine, { voice, voiceId, refresh = false } = {}) {
497
+ const roster = await listVoiceIdentities(engine, { refresh });
498
+ const asked = voice || engine.defaultVoice || (engine.modelIsDefaultVoice || engine.voiceIsFixed ? engine.model : null);
499
+ if (!roster.length && !engine.listVoices && !voiceId) {
500
+ return { name: asked ?? null, id: null, request: asked ?? undefined };
501
+ }
502
+ const picked = voiceId ? roster.find((v) => v.id === voiceId)
503
+ : engine.name === 'elevenlabs' ? pickVoice(roster, asked)
504
+ : asked ? roster.find((v) => v.name === asked)
505
+ ?? (engine.name === 'say' ? roster.find((v) => baseName(v.name) === asked) : null)
506
+ : roster[0];
507
+ if (!picked) {
508
+ const label = voice || voiceId || asked;
509
+ throw new Error(label ? `Voice “${label}” is unavailable on ${engine.name}` : `${engine.name} has no voices available`);
510
+ }
511
+ return { ...picked, request: engine.listVoices ? picked.id : picked.name };
512
+ }
513
+
431
514
  export function createEngine(opts = {}) {
432
515
  return buildEngine(opts);
433
516
  }
@@ -450,7 +533,7 @@ function buildEngine({
450
533
  // `cost` is the human-facing price note — the bridge's startup line and the
451
534
  // setup wizard's test-synthesis report both quote it.
452
535
  if (engine === 'piper') {
453
- const m = voice ?? PIPER_DEFAULT_VOICE;
536
+ const m = voice ?? piperVoiceFor(lang);
454
537
  return {
455
538
  name: 'piper', model: m, needsProject: false, stylable: false,
456
539
  // piper's synth takes only text: the model is loaded once and a
@@ -517,10 +600,13 @@ function buildEngine({
517
600
  const isV3 = m === ELEVENLABS_V3_MODEL;
518
601
  const tagged = readsAudioTags(m);
519
602
  const { listVoices, synth, searchLibrary, addLibraryVoice } = createElevenLabs({
520
- key: elevenLabsKey(env), model: m, format: format ?? 'pcm', stability,
603
+ key: elevenLabsKey(env), model: m, format: format ?? 'pcm', stability, lang,
521
604
  });
605
+ // the language this model is told to speak, which is then part of what a
606
+ // clip is (tools/tts-cache.mjs); absent for English and for a model told none
607
+ const told = languageCode(m, lang);
522
608
  return {
523
- name: 'elevenlabs', model: m, needsProject: false,
609
+ name: 'elevenlabs', model: m, needsProject: false, ...(told ? { lang: told } : {}),
524
610
  // v3 and v4 read audio tags as direction — every other ElevenLabs model
525
611
  // would read a tag's brackets aloud as words, so the tone step and a
526
612
  // deck's own tags ([whispers], [laughs]) are for those models only,
@@ -536,7 +622,7 @@ function buildEngine({
536
622
  caveat: isV3
537
623
  ? 'eleven_v3: higher latency, more variable consistency, and ElevenLabs '
538
624
  + 'recommends prompts over ~250 characters — a live decklight sentence is '
539
- + 'shorter than that, so delivery may vary more than a recorded take (V → Record this deck…).'
625
+ + 'shorter than that, so delivery may vary more than a recorded take (V → Save with the deck).'
540
626
  : undefined,
541
627
  // the real roster arrives from the account; until it does the picker has
542
628
  // nothing truthful to show, which is better than thirty names it cannot say
@@ -548,18 +634,21 @@ function buildEngine({
548
634
  };
549
635
  }
550
636
  if (engine === 'chirp') {
637
+ const locale = chirpLocale(lang);
551
638
  return {
552
639
  name: 'chirp', model: 'chirp3-hd', needsProject: true, stylable: false,
640
+ // en-US is what chirp spoke before it was told anything, and stays unnamed
641
+ ...(locale !== 'en-US' ? { lang: locale } : {}),
553
642
  cost: 'first 1M chars/month free',
554
- voices: GEMINI_VOICES,
555
- synth: createChirp({ project, lang: lang ?? 'en-US' }),
643
+ defaultVoice: 'Alnilam', voices: GEMINI_VOICES,
644
+ synth: createChirp({ project, lang: locale }),
556
645
  };
557
646
  }
558
647
  const m = model ?? 'gemini-2.5-pro-tts';
559
648
  return {
560
649
  name: 'gemini', model: m, needsProject: true, stylable: true,
561
650
  cost: 'billed per call — no free tier',
562
- voices: GEMINI_VOICES,
651
+ defaultVoice: 'Alnilam', voices: GEMINI_VOICES,
563
652
  synth: createGemini({ project, ttsModel: m, location }),
564
653
  };
565
654
  }
@@ -613,7 +702,7 @@ export function engineStatus(name, {
613
702
 
614
703
  if (name === 'piper') {
615
704
  if (!hasBin('piper', env)) return no('no-binary');
616
- const v = voice ?? PIPER_DEFAULT_VOICE;
705
+ const v = voice ?? piperVoiceFor(lang);
617
706
  const models = dataDir ?? piperModelDir(env);
618
707
  if (!exists(piperModelPath(v, models))) return no('no-model', { voice: v, dataDir: models });
619
708
  return { name, ready: true, reason: 'ok' };
@@ -0,0 +1,93 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { createHash } from 'node:crypto';
5
+ import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { basename, dirname, join } from 'node:path';
7
+
8
+ export function videoDigest(value) {
9
+ return createHash('sha256').update(value).digest('hex');
10
+ }
11
+
12
+ // Retain the head, scripts, and everything between slides in the shared key.
13
+ // The slide's own markup is fingerprinted separately.
14
+ export function videoMarkup(html) {
15
+ const slides = [];
16
+ const shared = html.replace(/<section\b[\s\S]*?<\/section\s*>/gi, (slide) => {
17
+ slides.push(slide);
18
+ return '<section></section>';
19
+ });
20
+ return { shared, slides };
21
+ }
22
+
23
+ export function videoCache({ out, origin, deckUrl, signal }) {
24
+ const root = join(dirname(out), '.' + basename(out) + '.decklight-cache');
25
+ const assets = new Map();
26
+
27
+ function asset(path) {
28
+ if (!assets.has(path)) assets.set(path, (async () => {
29
+ const url = new URL(path, origin);
30
+ if (url.origin !== origin || url.pathname === new URL(deckUrl).pathname) return null;
31
+ const response = await fetch(url, { signal, redirect: 'error' });
32
+ const hash = createHash('sha256').update(String(response.status));
33
+ for await (const chunk of response.body ?? []) hash.update(chunk);
34
+ return hash.digest('hex');
35
+ })().catch(() => null));
36
+ return assets.get(path);
37
+ }
38
+
39
+ const metadataFor = (slide) => join(root, slide + '.json');
40
+ function read(slide) {
41
+ try { return JSON.parse(readFileSync(metadataFor(slide), 'utf8')); } catch { return null; }
42
+ }
43
+
44
+ async function load(slide, key, work) {
45
+ try {
46
+ const meta = read(slide);
47
+ if (meta?.key !== key || !meta.files.length) return null;
48
+ const dir = join(root, basename(meta.dir));
49
+ for (const [path, digest] of meta.assets) {
50
+ if (await asset(path) !== digest) return null;
51
+ }
52
+ return meta.files.map((file) => {
53
+ const name = basename(file);
54
+ const target = join(work, 'cached-' + name);
55
+ copyFileSync(join(dir, name), target);
56
+ return target;
57
+ });
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ async function save(slide, key, files, resources) {
64
+ const paths = new Set();
65
+ for (const resource of resources) {
66
+ const url = new URL(resource);
67
+ if (url.protocol === 'data:' || url.protocol === 'blob:') continue;
68
+ if (url.origin !== origin) return;
69
+ if (url.pathname === new URL(deckUrl).pathname) continue;
70
+ paths.add(url.pathname + url.search);
71
+ }
72
+ const checks = await Promise.all([...paths].map(async (path) => [path, await asset(path)]));
73
+ if (checks.some(([, digest]) => digest === null)) return;
74
+ mkdirSync(root, { recursive: true });
75
+ const temp = mkdtempSync(join(root, 'slide-'));
76
+ const previous = read(slide);
77
+ try {
78
+ const names = files.map((file) => basename(file));
79
+ files.forEach((file, i) => copyFileSync(file, join(temp, names[i])));
80
+ const metadata = join(temp, 'slide.json');
81
+ writeFileSync(metadata, JSON.stringify({ key, dir: basename(temp), files: names, assets: checks }));
82
+ renameSync(metadata, metadataFor(slide));
83
+ } catch (error) {
84
+ rmSync(temp, { recursive: true, force: true });
85
+ throw error;
86
+ }
87
+ if (/^slide-[\w-]+$/.test(previous?.dir)) {
88
+ rmSync(join(root, previous.dir), { recursive: true, force: true });
89
+ }
90
+ }
91
+
92
+ return { load, save };
93
+ }
@@ -0,0 +1,349 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { pipeline } from 'node:stream/promises';
8
+ import { setTimeout as delay } from 'node:timers/promises';
9
+ import { promisify } from 'node:util';
10
+ import { openPage } from './cdp.mjs';
11
+
12
+ // Runs inside the deck. The page keeps time by its own wall clock, the same
13
+ // clock the capture samples frames by, so a slow capture does not slow the
14
+ // talk down and the picture stays where the narration is (the encoder lays the
15
+ // narration in from the WAV; the page never plays it). An <audio> element
16
+ // streaming a WAV of hundreds of megabytes used to be the clock here: when it
17
+ // stalled partway through a long talk, the deck froze on one frame and nothing
18
+ // noticed (#1254).
19
+ //
20
+ // Everything the watchdog reads is on `window.__dlLive`: when the loop last
21
+ // ran, the talk time it showed, the beat it is on, when the slide last
22
+ // changed, the first error, and the media events the watchdog has not read yet.
23
+ function playTalk(beats, fps, fault) {
24
+ const root = document.querySelector('.decklight');
25
+ const deck = root?.__decklight;
26
+ if (!deck) throw new Error('the deck did not initialize');
27
+ const wall = () => performance.timeOrigin + performance.now();
28
+ const state = window.__dlLive = { tick: wall(), time: 0, index: -1, changedAt: 0, dropped: 0, error: null, errorAt: null, events: [] };
29
+ let index = -1;
30
+ let pose = -1;
31
+ let shown = null;
32
+ let overlay;
33
+ let video;
34
+ const note = (what) => { if (state.events.length < 200) state.events.push(what); };
35
+ function show(time) {
36
+ if (fault?.kind === 'throw' && time >= fault.at) throw new Error('simulated failure at ' + fault.at + ' s');
37
+ let next = Math.max(0, index);
38
+ while (beats[next + 1]?.start <= time) next++;
39
+ const beat = beats[next];
40
+ const elapsed = Math.max(0, time - beat.start);
41
+ if (next !== index) {
42
+ index = next;
43
+ state.index = next;
44
+ pose = -1;
45
+ const at = beat.slide + '/' + beat.step;
46
+ if (at !== shown) { shown = at; state.changedAt = wall(); }
47
+ deck.goto(beat.slide, beat.step);
48
+ deck.character?.stop();
49
+ if (video) video.pause();
50
+ overlay?.remove();
51
+ root.classList.remove('decklight-face-full');
52
+ video = null;
53
+ if (beat.face) {
54
+ overlay = document.createElement('div');
55
+ const full = beat.face.kind === 'full';
56
+ overlay.className = 'decklight-character show mode-video pos-' + (beat.face.at ?? 'br');
57
+ overlay.classList.toggle('face-full', full);
58
+ overlay.style.setProperty('--face-zoom', beat.face.zoom);
59
+ root.classList.toggle('decklight-face-full', full);
60
+ const face = video = document.createElement('video');
61
+ face.muted = true;
62
+ face.playsInline = true;
63
+ face.className = 'live';
64
+ for (const type of ['waiting', 'stalled', 'error']) {
65
+ face.addEventListener(type, () => note('slide ' + beat.slide + ' face video: ' + type
66
+ + (type === 'error' && face.error ? ' (' + (face.error.message || 'code ' + face.error.code) + ')' : '')));
67
+ }
68
+ face.src = beat.face.url;
69
+ overlay.append(face);
70
+ root.append(overlay);
71
+ face.currentTime = elapsed;
72
+ face.play().catch(() => {});
73
+ }
74
+ }
75
+ if (video && video.readyState >= 1 && !video.ended && !video.seeking
76
+ && elapsed < video.duration && Math.abs(video.currentTime - elapsed) > 0.06) {
77
+ video.currentTime = elapsed;
78
+ }
79
+ let current = Math.max(0, pose);
80
+ while (beat.poses[current + 1]?.audioOffset <= elapsed) current++;
81
+ const shape = beat.poses[current];
82
+ if (shape && current !== pose) {
83
+ pose = current;
84
+ deck.character?.capture(shape.character, shape.placement, shape.force);
85
+ }
86
+ }
87
+ show(0);
88
+ deck._replayWriting?.();
89
+ const started = wall();
90
+ const end = beats.at(-1).end;
91
+ let lastPaint = performance.now();
92
+ function advance(now) {
93
+ const time = (wall() - started) / 1000;
94
+ if (fault?.kind === 'freeze' && time >= fault.at) return;
95
+ // the next tick is asked for first: one bad frame must not end the loop
96
+ // unseen, and the watchdog stops the capture on the error recorded here
97
+ if (time < end) requestAnimationFrame(advance);
98
+ state.dropped += Math.max(0, Math.round((now - lastPaint) * fps / 1000) - 1);
99
+ lastPaint = now;
100
+ state.tick = wall();
101
+ state.time = time;
102
+ try { show(time); } catch (err) {
103
+ state.errorAt ??= time;
104
+ state.error ??= String(err?.stack || err).split('\n').slice(0, 3).map((line) => line.trim()).join(' · ');
105
+ }
106
+ }
107
+ requestAnimationFrame(advance);
108
+ return started;
109
+ }
110
+
111
+ /** Seconds as m:ss, for the log. */
112
+ export function clock(seconds) {
113
+ const s = Math.max(0, Math.floor(seconds));
114
+ return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
115
+ }
116
+
117
+ /** The index of the beat a talk `time` (seconds) falls in. */
118
+ function beatAt(beats, time) {
119
+ return Math.max(0, beats.findLastIndex((beat) => beat.start <= time));
120
+ }
121
+
122
+ /**
123
+ * Why a live capture has stopped progressing, or null while it is fine.
124
+ * `state` is the page's `window.__dlLive`; `now` and `started` are wall-clock
125
+ * milliseconds. A still picture is not a problem in itself, since a slide that
126
+ * does not move sends no new image, so this judges the page's own clock and
127
+ * not the frames.
128
+ */
129
+ export function liveStall(state, { now, started, beats, grace = 2 }) {
130
+ if (!state) return 'the live player is gone from the page';
131
+ if (state.error) return 'page error: ' + state.error;
132
+ const talk = (now - started) / 1000;
133
+ const quiet = (now - state.tick) / 1000;
134
+ if (quiet > grace) return `the page stopped animating ${quiet.toFixed(1)} s ago`;
135
+ if (talk - state.time > grace) return `the deck's clock is ${(talk - state.time).toFixed(1)} s behind the talk`;
136
+ const expected = beatAt(beats, talk - grace);
137
+ if (state.index < expected) {
138
+ const on = beats[state.index] ?? beats[0];
139
+ const due = beats[expected];
140
+ return `the deck is still on slide ${on.slide} step ${on.step}, but the talk is at slide ${due.slide} step ${due.step}`;
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /** `throw@12` or `freeze@12` (seconds into the talk): a simulated stall, for the tests. */
146
+ export function liveFault(spec) {
147
+ const m = /^(throw|freeze)@(\d+(?:\.\d+)?)$/.exec(spec ?? '');
148
+ return m ? { kind: m[1], at: Number(m[2]) } : null;
149
+ }
150
+
151
+ const exec = promisify(execFile);
152
+
153
+ // Consult host evidence only after a frame stall. A generic Chrome stall can
154
+ // look identical, so a missing power event leaves the original diagnosis.
155
+ export async function displayStall({ platform = process.platform, tick, now, run = exec }) {
156
+ if (platform !== 'darwin') return null;
157
+ const read = (file, args) => run(file, args, { timeout: 3000, maxBuffer: 16 * 1024 * 1024 })
158
+ .then(({ stdout }) => stdout, () => '');
159
+ const [power, session] = await Promise.all([
160
+ read('/usr/bin/pmset', ['-g', 'log']),
161
+ read('/usr/sbin/ioreg', ['-n', 'Root', '-d1']),
162
+ ]);
163
+ let display;
164
+ for (const match of power.matchAll(/^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d) ([+-]\d{4})[^\n]*?\bDisplay is turned (off|on)\b/gm)) {
165
+ const [, date, time, zone, state] = match;
166
+ const at = Date.parse(`${date}T${time}${zone}`);
167
+ if (at >= tick - 2000 && at <= now) display = state;
168
+ }
169
+ if (display === 'off') return 'the display turned off';
170
+ if (/"(?:CGSSessionScreenIsLocked|IOConsoleLocked)"\s*=\s*(?:Yes|true|1)\b/i.test(session)) return 'the screen locked';
171
+ return null;
172
+ }
173
+
174
+ const READ_STATE = '(() => { const s = window.__dlLive; return s ? { ...s, events: s.events.splice(0) } : null; })()';
175
+
176
+ export async function captureLive({ plan, chrome, url, settings, work, exec, signal, media, log, encoding }) {
177
+ const { w, h, fps, format, quality } = settings;
178
+ const beats = [];
179
+ const audioFiles = [];
180
+ const fmt = ['-ar', String(encoding.sampleRate), '-ac', '2', '-c:a', 'pcm_s16le'];
181
+ let duration = 0;
182
+ for (const [i, beat] of plan.entries()) {
183
+ const file = join(work, 'live-audio-' + i + '.wav');
184
+ const input = beat.audio ? ['-i', beat.audio, '-af', 'apad'] : ['-f', 'lavfi', '-i', 'anullsrc'];
185
+ await exec('ffmpeg', ['-y', ...input, ...fmt, '-t', String(beat.duration), file]);
186
+ audioFiles.push(file);
187
+ const face = beat.face && { kind: beat.face.kind, at: beat.face.at, zoom: beat.face.zoom, url: '/decklight-live/face-' + i + '.mp4' };
188
+ if (face) media.set(face.url, beat.face.clip);
189
+ const poses = beat.poses.map(({ character, placement, audioOffset, force }) => ({ character, placement, audioOffset, force }));
190
+ beats.push({ slide: beat.slide, step: beat.step, start: duration, end: duration + beat.duration, face, poses });
191
+ duration += beat.duration;
192
+ }
193
+ const list = join(work, 'live-audio.txt');
194
+ writeFileSync(list, audioFiles.map((file) => "file '" + file.replaceAll("'", "'\\''") + "'").join('\n') + '\n');
195
+ const audio = join(work, 'live.wav');
196
+ await exec('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c:a', 'copy', audio]);
197
+ const out = join(work, 'live.' + format);
198
+ const encoder = spawn('ffmpeg', [
199
+ '-y', '-v', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', 'pipe:0', '-i', audio,
200
+ ...encoding.video(quality, true), ...encoding.audio(quality), '-t', duration.toFixed(3), out,
201
+ ], { stdio: ['pipe', 'ignore', 'pipe'], signal });
202
+ let error = null;
203
+ let stderr = '';
204
+ encoder.on('error', (err) => { error = err; });
205
+ encoder.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-8192); });
206
+ const encoded = new Promise((resolve) => encoder.once('close', resolve));
207
+ const count = Math.ceil(duration * fps);
208
+ const fault = liveFault(process.env.DECKLIGHT_TEST_LIVE_FAULT);
209
+ const screencast = { format: 'jpeg', quality: 92, maxWidth: w, maxHeight: h, everyNthFrame: 1 };
210
+ let dropped = 0;
211
+ async function* frames({ signal }) {
212
+ const page = await openPage(chrome, { w, h, signal, args: ['--mute-audio'] });
213
+ let latest;
214
+ let lastFrameAt = 0;
215
+ const offs = [
216
+ page.on('Page.screencastFrame', ({ data, sessionId }) => {
217
+ latest = Buffer.from(data, 'base64');
218
+ lastFrameAt = Date.now();
219
+ page.send('Page.screencastFrameAck', { sessionId }).catch(() => {});
220
+ }),
221
+ page.on('Runtime.exceptionThrown', ({ exceptionDetails: d }) => {
222
+ log(' live capture: page error: ' + (d.exception?.description ?? d.text ?? 'unknown').split('\n')[0]);
223
+ }),
224
+ page.on('Runtime.consoleAPICalled', ({ type, args }) => {
225
+ if (type !== 'error' && type !== 'warning') return;
226
+ const text = args.map((a) => a.value ?? a.description ?? a.type).join(' ');
227
+ log(` live capture: console.${type === 'warning' ? 'warn' : type}: ${text}`);
228
+ }),
229
+ ];
230
+ const watching = new AbortController();
231
+ let watch = Promise.resolve();
232
+ try {
233
+ const first = beats[0];
234
+ await page.navigate(url + '#/' + first.slide + '/' + first.step);
235
+ await page.send('Page.bringToFront');
236
+ latest = await page.screenshot('jpeg');
237
+ await page.send('Page.startScreencast', screencast);
238
+ const started = await page.evaluate('(' + playTalk + ')(' + JSON.stringify(beats) + ', ' + fps + ', ' + JSON.stringify(fault) + ')');
239
+ log(` live capture: recording ${duration.toFixed(1)}s at ${fps} fps`);
240
+ let failure = null;
241
+ let state = null;
242
+ let lastSample = started;
243
+ // where the page last was: a frozen page is named where it froze, not
244
+ // where the capture noticed
245
+ const where = () => {
246
+ const talk = Math.min(duration, state ? (state.errorAt ?? state.time) : (lastSample - started) / 1000);
247
+ return `slide ${beats[beatAt(beats, talk)].slide}, ${clock(talk)} into the talk`;
248
+ };
249
+ // Check before sampling or querying Chrome. After resume the page may
250
+ // already have jumped to the last slide, with no new frames to record.
251
+ const checkClock = () => {
252
+ const now = Date.now();
253
+ if (now - lastSample > 5000) failure = 'the computer went to sleep or stopped responding';
254
+ if (!failure) lastSample = now;
255
+ };
256
+ // Once a second: is the page still moving through the talk? A stall
257
+ // stops the capture with where and why; a video whose second half is
258
+ // one frame is never written.
259
+ watch = (async () => {
260
+ let warned = 0;
261
+ while (!failure) {
262
+ await delay(1000, undefined, { signal: watching.signal });
263
+ checkClock();
264
+ if (failure) break;
265
+ const now = Date.now();
266
+ const read = await Promise.race([page.evaluate(READ_STATE), delay(5000, 'timeout', { signal: watching.signal, ref: false })]);
267
+ checkClock();
268
+ if (failure) break;
269
+ if (read === 'timeout') { failure = 'the page did not answer for 5 s'; break; }
270
+ state = read;
271
+ for (const event of state?.events ?? []) log(' live capture: ' + event);
272
+ failure = liveStall(state, { now, started, beats });
273
+ // The slide changed but no screencast frame followed: take the
274
+ // picture by hand and restart the screencast.
275
+ if (!failure && state.changedAt > lastFrameAt && now - state.changedAt > 1500) {
276
+ if (now - warned > 30000) log(` live capture: warning — the screencast sent nothing after the slide changed (${where()}); restarting it`);
277
+ warned = now;
278
+ latest = await page.screenshot('jpeg');
279
+ lastFrameAt = Date.now();
280
+ await page.send('Page.stopScreencast');
281
+ await page.send('Page.startScreencast', screencast);
282
+ }
283
+ }
284
+ })().catch((err) => { if (!watching.signal.aborted) failure ??= 'lost the page: ' + err.message; });
285
+ const stalled = async () => {
286
+ const position = where();
287
+ const frameStall = state && failure?.startsWith('the page stopped animating');
288
+ const display = frameStall ? await displayStall({ tick: state.tick, now: Date.now() }) : null;
289
+ return Object.assign(new Error(`live capture stopped at ${position}: ${display ?? failure}`), { liveStall: true });
290
+ };
291
+ let index = 0;
292
+ let currentSlide = null;
293
+ let previous;
294
+ while (index < count) {
295
+ signal.throwIfAborted();
296
+ if (failure) throw await stalled();
297
+ const target = started + index * 1000 / fps;
298
+ const wait = target - Date.now();
299
+ if (wait > 0) await delay(wait, undefined, { signal });
300
+ checkClock();
301
+ if (failure) throw await stalled();
302
+ const actual = Math.min(count - 1, Math.max(index, Math.floor((Date.now() - started) * fps / 1000)));
303
+ const image = latest;
304
+ for (let missing = index; missing < actual; missing++) {
305
+ yield previous ?? image;
306
+ dropped++;
307
+ }
308
+ yield image;
309
+ previous = image;
310
+ index = actual + 1;
311
+ const beat = beats.findLast((beat) => beat.start <= actual / fps);
312
+ if (beat.slide !== currentSlide) {
313
+ currentSlide = beat.slide;
314
+ log(` slide ${String(currentSlide).padStart(2, '0')}: recorded`);
315
+ }
316
+ }
317
+ await delay(Math.max(0, started + duration * 1000 - Date.now()), undefined, { signal });
318
+ checkClock();
319
+ if (failure) throw await stalled();
320
+ // A still viewport need not send a new image. Count missed animation
321
+ // ticks and late sampling, without counting the same stall twice.
322
+ const final = await page.evaluate(READ_STATE);
323
+ checkClock();
324
+ if (failure) throw await stalled();
325
+ for (const event of final?.events ?? []) log(' live capture: ' + event);
326
+ if (final?.error) { failure = 'page error: ' + final.error; throw await stalled(); }
327
+ dropped = Math.min(count, Math.max(dropped, final?.dropped ?? 0));
328
+ } finally {
329
+ watching.abort();
330
+ await watch;
331
+ for (const off of offs) off();
332
+ await page.close();
333
+ }
334
+ }
335
+ try {
336
+ await pipeline(frames, encoder.stdin, { signal });
337
+ } catch (err) {
338
+ encoder.kill();
339
+ await encoded;
340
+ if (err?.liveStall) throw new Error(err.message);
341
+ if (error || stderr) throw new Error(error?.message || stderr.trim());
342
+ throw err;
343
+ }
344
+ if (await encoded !== 0) throw new Error(stderr.trim() || 'FFmpeg could not encode the live recording');
345
+ if (error) throw error;
346
+ if (dropped) log(` live capture: warning — ${dropped} dropped or late frames at ${fps} fps`);
347
+ else log(' live capture: no dropped frames detected');
348
+ return out;
349
+ }
@@ -30,5 +30,16 @@ export const VIDEO_SUBTITLES = [
30
30
  { value: 'file', label: 'Beside the video — .srt (.vtt for WebM)' },
31
31
  ];
32
32
 
33
+ export const VIDEO_RENDER_MODES = [
34
+ { value: 'exact', label: 'Exact — repeatable frame by frame, using several cores to finish faster.' },
35
+ { value: 'live', label: 'Live capture — plays once in real time, may drop frames or lose lip-sync, and restarts if interrupted.' },
36
+ ];
37
+
38
+ // your face, filmed while you recorded the narration (`--no-face` leaves it out)
39
+ export const VIDEO_FACE = [
40
+ { value: 'on', label: 'Your face, where you filmed it — as each slide places it' },
41
+ { value: 'off', label: 'Leave it out' },
42
+ ];
43
+
33
44
  /** The values alone, as a flag's error message lists them. */
34
45
  export const valuesOf = (list) => list.map((o) => o.value);