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
@@ -17,17 +17,18 @@
17
17
  // chose ElevenLabs and lets your environment remember the secret.
18
18
 
19
19
  import { wavFromPcm } from './gemini-tts.mjs';
20
+ import { styleTag } from './tone-cue.mjs';
20
21
 
21
22
  export const KEY_ENV = 'ELEVENLABS_API_KEY';
22
23
  const API = 'https://api.elevenlabs.io/v1';
23
24
 
24
- // eleven_v4 is the default: it reads the audio tags a script is written with
25
- // ([whispers], [laughs], [long pause]) as direction, follows them more
26
- // reliably than v3, and answers sooner. --tts-model eleven_v4_turbo trades a
27
- // little quality for latency; eleven_multilingual_v2 is the pre-tag voice.
25
+ // eleven_v4_turbo is the default: it reads the audio tags a script is written
26
+ // with ([whispers], [laughs], [long pause]) as direction, follows them more
27
+ // reliably than v3, and answers soonest. --tts-model eleven_v4 trades that
28
+ // latency for a little more quality; eleven_multilingual_v2 is the pre-tag voice.
28
29
  // A track already recorded keeps the model its manifest names — voiceover
29
30
  // reads it back — so changing this default re-voices nothing.
30
- export const DEFAULT_MODEL = 'eleven_v4';
31
+ export const DEFAULT_MODEL = 'eleven_v4_turbo';
31
32
 
32
33
  // v3 was the first ElevenLabs model to read bracketed audio tags as
33
34
  // performance direction instead of words to pronounce; v4 follows them more
@@ -39,39 +40,40 @@ export const TAG_MODELS = ['eleven_v3', 'eleven_v4', 'eleven_v4_turbo'];
39
40
  /** Does this ElevenLabs model act on `[whispers]`-style audio tags? */
40
41
  export const readsAudioTags = (model) => TAG_MODELS.includes(model);
41
42
 
42
- // v3's stability slider is not the continuous 0–1 knob older models expose —
43
- // ElevenLabs documents exactly these three named positions. Creative follows
44
- // a tag hardest and drifts most; Robust barely moves and mostly ignores tags;
45
- // Natural is the middle ground. Unnamed values are refused rather than
46
- // silently rounded to the nearest preset.
47
- export const STABILITY_PRESETS = { creative: 0, natural: 0.5, robust: 1 };
48
-
49
- // A tag this long stops being a short performance cue and starts being a
50
- // second sentence — cut it back rather than let it run on. 40 chars covers
51
- // every named ElevenLabs tag with room for a typed phrase like "on the verge
52
- // of tears" and still reads as direction, not dialogue.
53
- const MAX_TAG_LEN = 40;
43
+ // The models that are sent `language_code`. Left to itself a model guesses the
44
+ // language from the text, and a beat that is a product name, a number or two
45
+ // words is exactly the text it guesses wrong. A model outside this list is
46
+ // sent none, as before: eleven_multilingual_v2 does not take the field.
47
+ export const LANGUAGE_MODELS = [...TAG_MODELS, 'eleven_turbo_v2_5', 'eleven_flash_v2_5'];
54
48
 
55
49
  /**
56
- * A `style` string, or free-typed text, as a single ElevenLabs v3 audio tag —
57
- * or '' if there is nothing to say.
58
- *
59
- * Someone who already knows v3 syntax can type `[whispers]` and get exactly
60
- * that cue: the first well-formed bracketed group survives untouched (and
61
- * only the first — a second `[…]` later in the string would be a second cue
62
- * riding along uninvited, so everything after the first close-bracket is
63
- * dropped). Anyone else just types a word or a short phrase, which is wrapped
64
- * in brackets for them. Either way the result is capped to MAX_TAG_LEN so a
65
- * persona too long to be a cue is cut back rather than spoken.
50
+ * The `language_code` a deck's language asks of `model`, or undefined: the
51
+ * two-letter code of a deck that is not in English, on a model that takes one.
52
+ * English is sent nothing, which is what every deck was sent before the
53
+ * language reached the voice: an English take recorded then is still the take.
66
54
  */
67
- export function styleTag(style, maxLen = MAX_TAG_LEN) {
68
- const raw = String(style ?? '').trim();
69
- if (!raw) return '';
70
- const bracketed = raw.match(/^\[([^[\]]+)\]/);
71
- const cue = (bracketed ? bracketed[1] : raw).trim().slice(0, maxLen).trim();
72
- return cue ? `[${cue}]` : '';
55
+ export function languageCode(model, lang) {
56
+ const code = String(lang ?? '').trim().split(/[-_]/)[0].toLowerCase();
57
+ return /^[a-z]{2}$/.test(code) && code !== 'en' && LANGUAGE_MODELS.includes(model) ? code : undefined;
73
58
  }
74
59
 
60
+ // The tag models' stability slider is not the continuous 0–1 knob older
61
+ // models expose: ElevenLabs documents exactly these three named positions.
62
+ // Creative follows a tag hardest and drifts most; Robust barely moves and
63
+ // mostly ignores tags; Natural is the middle ground. Unnamed values are
64
+ // refused rather than silently rounded to the nearest preset.
65
+ export const STABILITY_PRESETS = { creative: 0, natural: 0.5, robust: 1 };
66
+
67
+ // A very short input is where a tag model is least stable: ElevenLabs' own
68
+ // guidance, and how "You ask, it answers." came back as "You ask, you ask, it
69
+ // answers" (#1005). Below this many characters a sentence goes at Robust,
70
+ // unless --tts-stability chose a position for every sentence.
71
+ export const SHORT_TEXT = 60;
72
+
73
+ // The tag a tone becomes, and where it is cut, live with the built-in tones:
74
+ // the deck's tone picker needs both too (tools/tone-cue.mjs).
75
+ export { styleTag, cutTag, cueFor, MAX_TAG_LEN } from './tone-cue.mjs';
76
+
75
77
  // PCM is what the rest of decklight is built on: the deck's recorder stitches per-slide WAVs
76
78
  // out of the sentence cache, and rhubarb reads WAV to find visemes. mp3 plays
77
79
  // perfectly well in the deck but does neither, so it is opt-in rather than a
@@ -159,10 +161,12 @@ export function pickVoice(roster, requested) {
159
161
  if (!requested) return roster[0];
160
162
  const squash = (t) => String(t).trim().toLowerCase().replace(/\s+/g, '');
161
163
  const want = String(requested).trim().toLowerCase();
162
- const exact = roster.find((v) => v.id === requested)
163
- ?? roster.find((v) => v.name.toLowerCase() === want)
164
- ?? roster.find((v) => squash(v.name) === squash(want));
165
- if (exact) return exact;
164
+ const byId = roster.find((v) => v.id === requested);
165
+ if (byId) return byId;
166
+ const exact = roster.filter((v) => v.name.toLowerCase() === want);
167
+ if (exact.length) return exact.length === 1 ? exact[0] : null;
168
+ const normalized = roster.filter((v) => squash(v.name) === squash(want));
169
+ if (normalized.length) return normalized.length === 1 ? normalized[0] : null;
166
170
  const byShortName = roster.filter((v) => squash(shortName(v.name)) === squash(want));
167
171
  return byShortName.length === 1 ? byShortName[0] : null;
168
172
  }
@@ -184,8 +188,8 @@ export function synthError(status, body, { format = 'pcm' } = {}) {
184
188
  }
185
189
  if (format === 'pcm' && /output_format|pcm|tier|subscription/i.test(text)) {
186
190
  return 'ElevenLabs will not serve pcm_24000 on this plan (PCM output is a paid tier). '
187
- + 'Pass --tts-format mp3 to use mp3 instead — the deck plays it fine, but the panel\'s Record this deck… offline '
188
- + 'recording and the lip-sync bridge both need WAV and will not work with it.';
191
+ + 'Pass --tts-format mp3 to use mp3 instead — the deck plays it fine, but the panel\'s Save with the deck '
192
+ + 'and the lip-sync bridge both need WAV and will not work with it.';
189
193
  }
190
194
  if (status === 429) return 'ElevenLabs rate limit (429) — the lookahead buffer is bursty; try a smaller deck or wait';
191
195
  return `${status} ${text}`;
@@ -202,8 +206,9 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
202
206
  * probe rather than needing a restart.
203
207
  */
204
208
  export function createSynth({
205
- key, model = DEFAULT_MODEL, format = 'pcm', stability, fetchImpl = fetch,
209
+ key, model = DEFAULT_MODEL, format = 'pcm', stability, lang, fetchImpl = fetch,
206
210
  } = {}) {
211
+ const language = languageCode(model, lang);
207
212
  if (!key) {
208
213
  throw new Error(`ElevenLabs needs an API key — set $${KEY_ENV} `
209
214
  + '(create one at https://elevenlabs.io/app/settings/api-keys)');
@@ -213,8 +218,8 @@ export function createSynth({
213
218
  // up front, at construction, rather than accepted and quietly doing nothing.
214
219
  let stabilityValue;
215
220
  if (stability != null) {
216
- if (model !== V3_MODEL) {
217
- throw new Error(`--tts-stability is a v3 feature — pass --tts-model ${V3_MODEL}, or drop --tts-stability`);
221
+ if (!readsAudioTags(model)) {
222
+ throw new Error(`--tts-stability is a v3/v4 feature — pass --tts-model ${DEFAULT_MODEL}, or drop --tts-stability`);
218
223
  }
219
224
  stabilityValue = STABILITY_PRESETS[stability];
220
225
  if (stabilityValue == null) {
@@ -224,16 +229,16 @@ export function createSynth({
224
229
  const headers = { 'xi-api-key': key };
225
230
 
226
231
  let roster = null;
227
- function listVoices() {
232
+ function listVoices({ refresh = false } = {}) {
233
+ if (refresh) roster = null;
228
234
  roster ??= (async () => {
229
235
  const res = await fetchImpl(`${API}/voices`, { headers });
230
236
  if (!res.ok) throw new Error(synthError(res.status, await res.text(), { format }));
231
- const shaped = shapeVoices(await res.json());
232
- if (!shaped.length) throw new Error('ElevenLabs returned no voices for this key');
233
- return shaped;
237
+ return shapeVoices(await res.json());
234
238
  })();
235
- roster.catch(() => { roster = null; });
236
- return roster;
239
+ const pending = roster;
240
+ pending.catch(() => { if (roster === pending) roster = null; });
241
+ return pending;
237
242
  }
238
243
 
239
244
  /**
@@ -275,11 +280,13 @@ export function createSynth({
275
280
  return { id: j.voice_id ?? id, name };
276
281
  }
277
282
 
278
- async function call(text, voice) {
279
- const payload = { text, model_id: model };
283
+ async function call(text, voice, short) {
284
+ const payload = { text, model_id: model, ...(language ? { language_code: language } : {}) };
280
285
  // Unasked, the account's own voice settings are left alone — sending a
281
286
  // voice_settings object at all overrides them, even to "no opinion".
282
- if (stabilityValue != null) payload.voice_settings = { stability: stabilityValue };
287
+ // The one exception is a short sentence on a tag model, held at Robust.
288
+ const stable = stabilityValue ?? (short ? STABILITY_PRESETS.robust : null);
289
+ if (stable != null) payload.voice_settings = { stability: stable };
283
290
  const res = await fetchImpl(
284
291
  `${API}/text-to-speech/${encodeURIComponent(voice.id)}?output_format=${OUTPUT[format]}`,
285
292
  {
@@ -310,11 +317,12 @@ export function createSynth({
310
317
  // is NEVER attached unless this is a model that can act on it.
311
318
  const tag = readsAudioTags(model) ? styleTag(style) : '';
312
319
  const sent = tag ? `${tag} ${text}` : text;
320
+ const short = readsAudioTags(model) && String(text).trim().length < SHORT_TEXT;
313
321
  let lastErr;
314
322
  for (let attempt = 0; attempt < 3; attempt++) {
315
323
  try {
316
324
  return {
317
- wav: await call(sent, picked),
325
+ wav: await call(sent, picked, short),
318
326
  usage: {
319
327
  model,
320
328
  // Billed on what actually went out — the tag rides inside the same
@@ -325,7 +333,8 @@ export function createSynth({
325
333
  // the per-character rate depends on a tier we cannot see. Reporting a
326
334
  // dollar figure would be inventing one, so the bridge shows characters.
327
335
  cost: 0,
328
- note: tag ? `${sent.length} chars · ${picked.name} · ${tag}` : `${sent.length} chars · ${picked.name}`,
336
+ note: [`${sent.length} chars`, picked.name, tag, short && stabilityValue == null ? 'robust (short)' : '']
337
+ .filter(Boolean).join(' · '),
329
338
  },
330
339
  };
331
340
  } catch (e) {
package/tools/exec.mjs CHANGED
@@ -69,11 +69,19 @@ export function run(bin, args, { timeout = NETWORK_MS, why = '', ...opts } = {})
69
69
  *
70
70
  * Use this — never `run` — whenever the process that spawns the child is also
71
71
  * serving it (tools/shot.mjs, tools/video.mjs, cli/pptx-export.mjs).
72
+ *
73
+ * A `signal` stops the child (SIGKILL, like the timeout) and rejects with the
74
+ * AbortError itself, so a caller can tell "stopped" from "hung".
72
75
  */
73
- export function runAsync(bin, args, { timeout = NETWORK_MS, why = '', ...opts } = {}) {
76
+ export function runAsync(bin, args, { timeout = NETWORK_MS, why = '', signal = null, ...opts } = {}) {
74
77
  return new Promise((resolve, reject) => {
75
- execFile(bin, args, { ...opts, timeout, killSignal: 'SIGKILL' }, (e, stdout, stderr) => {
78
+ // execFile throws on `signal: null`, which is what a caller with nothing
79
+ // that could stop it (the command line) passes along
80
+ execFile(bin, args, { ...opts, ...(signal ? { signal } : {}), timeout, killSignal: 'SIGKILL' }, (e, stdout, stderr) => {
76
81
  if (!e) return resolve(stdout);
82
+ // `signal` aborted: somebody STOPPED it (the edit server's stop routes),
83
+ // which is not a hang and must not read as one
84
+ if (e.name === 'AbortError') return reject(e);
77
85
  if (e.killed || e.code === 'ETIMEDOUT' || (e.signal === 'SIGKILL' && e.status == null)) {
78
86
  const err = new Error(`${bin} hung for ${Math.round(timeout / 1000)}s and was killed`
79
87
  + (why ? ` — ${why}` : ''));
@@ -0,0 +1,96 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Your face, filmed while you recorded the deck (PRESENTING, the your-voice
5
+ // recorder), made into the clips the character plays and `decklight video`
6
+ // composes: slide-NN-KK.mp4 beside each beat's slide-NN-KK.wav, and
7
+ // slide-NN.mp4 joined from them beside the whole-slide file.
8
+ //
9
+ // The browser films with MediaRecorder: webm in Chrome, mp4 in Safari, a
10
+ // variable frame rate in both, and a start that lands a few frames after the
11
+ // audio's. So every clip is made the same thing here: H.264, 25 fps, no sound
12
+ // (the voice is the WAV's), and exactly as long as the beat's WAV, cut or held
13
+ // on its last frame. A clip a tenth of a second long or short is invisible on
14
+ // one beat and a visible drift by the end of a slide of eight; the WAV is the
15
+ // clock both players already follow.
16
+
17
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
18
+ import { runAsync, CODEC_MS, PROBE_MS } from './exec.mjs';
19
+
20
+ export const FACE_FPS = 25;
21
+
22
+ /** The seconds a 16-bit PCM WAV runs, from its own header; null when it is not one. */
23
+ export function wavSeconds(buf) {
24
+ if (!buf || buf.length < 12 || buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') return null;
25
+ let byteRate = 0;
26
+ for (let at = 12; at + 8 <= buf.length;) {
27
+ const id = buf.toString('ascii', at, at + 4);
28
+ const size = buf.readUInt32LE(at + 4);
29
+ if (id === 'fmt ' && at + 16 <= buf.length) byteRate = buf.readUInt32LE(at + 16);
30
+ if (id === 'data') return byteRate ? Math.min(size, buf.length - at - 8) / byteRate : null;
31
+ at += 8 + size + (size % 2);
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /**
37
+ * ffmpeg argv: one filmed take → a clip of exactly `seconds`. `tpad` holds the
38
+ * last frame long enough for a take that came in short, and `-t` cuts one
39
+ * that came in long. Even dimensions, because yuv420p refuses odd ones.
40
+ */
41
+ export function faceClipArgs({ input, out, seconds }) {
42
+ const t = Math.max(0.04, Number(seconds) || 0).toFixed(3);
43
+ return ['-y', '-loglevel', 'error', '-i', input, '-an',
44
+ '-vf', `fps=${FACE_FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1,tpad=stop_mode=clone:stop_duration=${t}`,
45
+ '-t', t, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p',
46
+ '-movflags', '+faststart', out];
47
+ }
48
+
49
+ /** ffmpeg argv: the beats' clips, made alike by faceClipArgs, joined without re-encoding. */
50
+ export function faceJoinArgs({ list, out }) {
51
+ return ['-y', '-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', '-movflags', '+faststart', out];
52
+ }
53
+
54
+ /** Is there an ffmpeg to make clips with? */
55
+ export async function hasFfmpeg({ env = process.env } = {}) {
56
+ try { await runAsync('ffmpeg', ['-version'], { timeout: PROBE_MS, env }); return true; } catch { return false; }
57
+ }
58
+
59
+ /**
60
+ * Write `out` from the filmed `bytes`, as long as the WAV at `wav` (or as
61
+ * filmed, when there is no WAV to measure). The take goes through a scratch
62
+ * file beside `out`, since ffmpeg reads a webm's duration by seeking in it.
63
+ */
64
+ export async function writeFaceClip({ bytes, out, wav = null, env = process.env }) {
65
+ let seconds = null;
66
+ if (wav && existsSync(wav)) seconds = wavSeconds(readFileSync(wav));
67
+ const raw = `${out}.take`;
68
+ const tmp = out.replace(/\.mp4$/, '.tmp.mp4');
69
+ writeFileSync(raw, bytes);
70
+ try {
71
+ const args = seconds == null
72
+ ? ['-y', '-loglevel', 'error', '-i', raw, '-an', '-vf', `fps=${FACE_FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1`,
73
+ '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', tmp]
74
+ : faceClipArgs({ input: raw, out: tmp, seconds });
75
+ await runAsync('ffmpeg', args, { timeout: CODEC_MS, env, why: 'making a filmed beat into a clip' });
76
+ renameSync(tmp, out);
77
+ } finally {
78
+ rmSync(raw, { force: true });
79
+ rmSync(tmp, { force: true });
80
+ }
81
+ return { seconds };
82
+ }
83
+
84
+ /** Join `parts` (paths, in order) into `out`. */
85
+ export async function joinFaceClips({ parts, out, env = process.env }) {
86
+ const list = `${out}.list.txt`;
87
+ const tmp = out.replace(/\.mp4$/, '.tmp.mp4');
88
+ writeFileSync(list, parts.map((p) => `file '${p.replaceAll("'", "'\\''")}'`).join('\n') + '\n');
89
+ try {
90
+ await runAsync('ffmpeg', faceJoinArgs({ list, out: tmp }), { timeout: CODEC_MS, env, why: 'joining the filmed beats of a slide' });
91
+ renameSync(tmp, out);
92
+ } finally {
93
+ rmSync(list, { force: true });
94
+ rmSync(tmp, { force: true });
95
+ }
96
+ }
@@ -0,0 +1,94 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Where a filmed face shows on a slide, and from which beat (FACE_LAYOUT):
5
+ // the `data-face` attribute on a <section>. ONE reader, for the two places
6
+ // that place the face: the deck's character overlay (src/core/character.js,
7
+ // which bundles this the way src/core/review.js bundles review-anchor.mjs)
8
+ // and `decklight video`, which composes it into the frames. Written twice,
9
+ // a slide would be full screen in the deck and in the corner of its video.
10
+ //
11
+ // data-face="full" your face fills the screen, the slide steps aside
12
+ // data-face="full 1.4" …zoomed in 1.4×, on the face
13
+ // data-face="hide" no face on this slide; the voice still plays
14
+ // data-face="top-right" the medallion, in that corner for this slide
15
+ // (top-left, top-right, bottom-left, bottom-right)
16
+ // data-face="hide 3:full 1.5 4:corner"
17
+ // hidden for beats 1-2, full screen at 1.5× from
18
+ // beat 3, the medallion again from beat 4
19
+ //
20
+ // A beat is a [click] beat of the slide's notes, counted the way the recorder
21
+ // counts them ("beat 3 of 4") and numbered like its files (slide-NN-03.wav).
22
+ // A value holds until the next one. No attribute, or one that says nothing
23
+ // this understands, is the corner: the medallion, as the deck has always
24
+ // shown it.
25
+ //
26
+ // No imports and no DOM.
27
+
28
+ export const FACE_KINDS = ['corner', 'hide', 'full'];
29
+ export const FACE_ZOOM_MAX = 4;
30
+
31
+ /** `corner`, the default, at no zoom. */
32
+ export const FACE_CORNER = Object.freeze({ kind: 'corner', zoom: 1 });
33
+
34
+ /**
35
+ * The medallion's four named corners, and the short form the character's
36
+ * `pos-*` classes use. A named corner is `corner` in a place of its own; a
37
+ * bare `corner` is wherever the deck puts the character.
38
+ */
39
+ export const FACE_CORNERS = Object.freeze({ 'top-left': 'tl', 'top-right': 'tr', 'bottom-left': 'bl', 'bottom-right': 'br' });
40
+
41
+ /**
42
+ * `data-face` → its rules, earliest beat first: `[{ from, kind, zoom }]`, and
43
+ * the tokens it could not read (for a check that wants to say so).
44
+ */
45
+ export function parseFaceLayout(attr) {
46
+ const rules = [];
47
+ const bad = [];
48
+ let from = 1;
49
+ for (const raw of String(attr ?? '').trim().split(/\s+/).filter(Boolean)) {
50
+ const tok = raw.toLowerCase();
51
+ const at = /^(\d+):(.*)$/.exec(tok);
52
+ const word = at ? at[2] : tok;
53
+ if (at) from = Math.max(1, Number(at[1]));
54
+ // a zoom belongs to the `full` before it: `full 1.4`, `full 1.4x`, `full ×1.4`
55
+ const zoom = /^[x×]?(\d+(?:\.\d+)?)[x×]?$/.exec(word);
56
+ if (zoom && !at) {
57
+ const last = rules[rules.length - 1];
58
+ if (last?.kind === 'full') { last.zoom = Math.min(FACE_ZOOM_MAX, Math.max(1, Number(zoom[1]))); continue; }
59
+ bad.push(raw);
60
+ continue;
61
+ }
62
+ const named = FACE_CORNERS[word];
63
+ if (!named && !FACE_KINDS.includes(word)) { bad.push(raw); continue; }
64
+ const rule = named ? { from, kind: 'corner', zoom: 1, at: named } : { from, kind: word, zoom: 1 };
65
+ // a later rule for the same beat replaces the earlier one
66
+ const same = rules.findIndex((r) => r.from === from);
67
+ if (same >= 0) rules[same] = rule; else rules.push(rule);
68
+ }
69
+ rules.sort((a, b) => a.from - b.from);
70
+ return { rules, bad };
71
+ }
72
+
73
+ /** How the face shows on `beat` (1-based) of a slide whose section says `attr`. */
74
+ export function faceLayout(attr, beat = 1) {
75
+ const { rules } = parseFaceLayout(attr);
76
+ let at = FACE_CORNER;
77
+ for (const r of rules) if (r.from <= (beat ?? 1)) at = { kind: r.kind, zoom: r.zoom, ...(r.at ? { at: r.at } : {}) };
78
+ return at;
79
+ }
80
+
81
+ /**
82
+ * One placement for a whole slide, written back as `data-face` (the V panel's
83
+ * the panel's Where…): '' for the default corner, which is no attribute at all.
84
+ * The inverse of faceLayout for a slide-wide value.
85
+ */
86
+ export function faceValue({ kind, zoom = 1, at } = {}) {
87
+ if (kind === 'hide') return 'hide';
88
+ if (kind === 'full') {
89
+ const z = Math.min(FACE_ZOOM_MAX, Math.max(1, Number(zoom) || 1));
90
+ return z === 1 ? 'full' : `full ${z}`;
91
+ }
92
+ const name = Object.keys(FACE_CORNERS).find((k) => FACE_CORNERS[k] === at);
93
+ return name ?? '';
94
+ }
@@ -69,7 +69,7 @@ function estimateCost(model, usage) {
69
69
  /**
70
70
  * Wrap headerless 16-bit mono PCM in a RIFF/WAVE header. Every engine that
71
71
  * gets raw samples back lands here (Gemini's audio/L16, ElevenLabs' pcm_24000)
72
- * — WAV is what the deck's recorder (V → Record this deck…) stitching and the lip-sync bridge both read.
72
+ * — WAV is what the deck's recorder (V → Save with the deck) stitching and the lip-sync bridge both read.
73
73
  */
74
74
  export function wavFromPcm(pcm, rate) {
75
75
  const h = Buffer.alloc(44);
@@ -0,0 +1,27 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * What `invisible-in-print` says (#1184): one sentence for `decklight pdf`,
6
+ * `decklight check` and the Check deck… panel, so the three read alike. Pure,
7
+ * and here rather than in src/ for the reason tools/click-match.mjs gives:
8
+ * cli/ never imports src/, src/ may import a tool.
9
+ */
10
+
11
+ /** What usually makes such a hole, and the way out of it. */
12
+ export const INVISIBLE_ADVICE = 'print shows an entrance the deck animates with its own CSS as it ends, '
13
+ + 'and this one does not end visible: make it a build (SPEC BUILDS), or mark it data-invisible-ok if it is meant';
14
+
15
+ /**
16
+ * The element a slide does not show and how many more: `a box “Batch”
17
+ * (opacity 0), and 1 more element`. `what` is the runtime's naming
18
+ * (`data-invisible`), '' for nothing.
19
+ */
20
+ export function invisibleSaidOf(what, more = 0) {
21
+ if (!what) return '';
22
+ const n = Number(more);
23
+ return `${what}${n > 0 ? `, and ${n} more element${n === 1 ? '' : 's'}` : ''}`;
24
+ }
25
+
26
+ /** The finding's message, as `check` prints it. */
27
+ export const invisibleMessage = (said) => `invisible in print: ${said} — ${INVISIBLE_ADVICE}`;
@@ -0,0 +1,197 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Lip-sync that follows the audio (#1244, SPEC CHARACTER).
6
+ *
7
+ * A deck with a 2D character (`narration.character.mode: 'viseme'`) plays a
8
+ * `slide-NN[-KK].visemes.json` beside each audio file. Whatever writes that
9
+ * audio — `decklight narrate`, the export's re-voicing of stale slides, the
10
+ * deck's own "Generate an AI recording" — calls THIS afterwards, so the
11
+ * sidecars are cut from the audio that is now on disk instead of waiting for
12
+ * someone to remember `decklight narrate <deck> --face`.
13
+ *
14
+ * Two halves:
15
+ * - `lipsyncStatus(dir)`: which stems' sidecars are missing or belong to
16
+ * another recording (tools/viseme-match.mjs: the `audio` stamp, then the
17
+ * lipsync.json hash, then the length). The voice card shows it.
18
+ * - `makeLipsync(dir, stems)`: tools/lipsync.mjs on just those stems, in
19
+ * parallel (`--jobs`), its `[k/N]` progress passed on line by line.
20
+ *
21
+ * Without Rhubarb the sidecars are still made, read from the voice
22
+ * (tools/mouth.mjs, marked `source: 'builtin'`), and the caller says ONCE how
23
+ * to get Rhubarb's (`RHUBARB_HINT`). Once Rhubarb is here those count as out
24
+ * of date (tools/viseme-match.mjs), so the next run replaces them.
25
+ *
26
+ * A slide filmed with your face (the manifest's `face`, and its .mp4 beside
27
+ * the audio) plays the film, not the character, so it is never counted or cut.
28
+ *
29
+ * Node-only.
30
+ */
31
+
32
+ import { spawn } from 'node:child_process';
33
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
34
+ import { join, basename } from 'node:path';
35
+ import { fileURLToPath } from 'node:url';
36
+ import { run, PROBE_MS } from './exec.mjs';
37
+ import { loadLipsyncConfig } from './lipsync-config.mjs';
38
+ import { visemeMismatch, wavDuration } from './viseme-match.mjs';
39
+ import { deckConfigSource } from '../cli/runtime-link.mjs';
40
+
41
+ const LIPSYNC = fileURLToPath(new URL('./lipsync.mjs', import.meta.url));
42
+
43
+ /** Said once, when audio was written and its lip-sync could not be. */
44
+ export const RHUBARB_HINT = 'lip-sync read from the voice: Rhubarb is not installed, which makes it more exact. '
45
+ + 'Install it from https://github.com/DanielSWolf/rhubarb-lip-sync and run decklight setup face --rhubarb <bin>; '
46
+ + 'then decklight narrate <deck> --face (or the voice card\'s "Update lip-sync") remakes it';
47
+
48
+ /** The deck's configured character mode: 'viseme', 'video', 'off', or null when it names none. */
49
+ export function characterMode(html) {
50
+ try { return deckConfigSource(html).config?.narration?.character?.mode ?? null; } catch { return null; }
51
+ }
52
+
53
+ /** The Rhubarb this machine would run: what `decklight setup face` saved, else the one on PATH. */
54
+ export function rhubarbBin(env = process.env) {
55
+ return loadLipsyncConfig(env)?.rhubarb ?? 'rhubarb';
56
+ }
57
+
58
+ /** Whether Rhubarb runs here. */
59
+ export function haveRhubarb(bin = rhubarbBin(), probe = run) {
60
+ try { probe(bin, ['--version'], { stdio: 'ignore', timeout: PROBE_MS }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
61
+ }
62
+
63
+ // asked at most every 30 s: the voice card polls the status, and installing
64
+ // Rhubarb mid-session should still be noticed
65
+ let rhubarbSeen = null;
66
+ function rhubarbNow() {
67
+ if (!rhubarbSeen || Date.now() - rhubarbSeen.at > 30_000) rhubarbSeen = { at: Date.now(), have: haveRhubarb() };
68
+ return rhubarbSeen.have;
69
+ }
70
+
71
+ /** The stems of slides filmed with your face: they play the film, never the character. */
72
+ function filmedStems(dir, stems) {
73
+ let m;
74
+ try { m = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')); } catch { return new Set(); }
75
+ const filmed = new Set((m?.slides ?? []).map((e, i) => (e?.face === true ? String(i + 1).padStart(2, '0') : null)).filter(Boolean));
76
+ return new Set(stems.filter((st) => filmed.has(st.slice(6, 8)) && existsSync(join(dir, `${st}.mp4`))));
77
+ }
78
+
79
+ // file → [stat key, verdict]: a track of 150 WAVs is read once, not on every
80
+ // open of the voice card
81
+ const memo = new Map();
82
+ const statKey = (f) => { try { const s = statSync(f); return `${s.size}:${s.mtimeMs}`; } catch { return 'none'; } };
83
+
84
+ /**
85
+ * The lip-sync of the track in `dir`: `{ stems, stale }` — every stem with
86
+ * audio the character plays, and those whose sidecar is missing or is not
87
+ * this audio's, each `{ stem, why }`.
88
+ */
89
+ export function lipsyncStatus(dir, { rhubarb = rhubarbNow() } = {}) {
90
+ let names;
91
+ try { names = readdirSync(dir); } catch { return { stems: [], stale: [] }; }
92
+ const audioOf = new Map();
93
+ for (const f of names) {
94
+ const m = /^(slide-\d+(?:-\d+)?)\.(wav|m4a)$/.exec(f);
95
+ // wav first: it is what lipsync.mjs cuts from, and what the deck plays
96
+ if (m && (!audioOf.has(m[1]) || m[2] === 'wav')) audioOf.set(m[1], join(dir, f));
97
+ }
98
+ const all = [...audioOf.keys()].sort();
99
+ const filmed = filmedStems(dir, all);
100
+ const stems = all.filter((st) => !filmed.has(st));
101
+ let state = {};
102
+ try { state = JSON.parse(readFileSync(join(dir, 'lipsync.json'), 'utf8')); } catch { /* none kept */ }
103
+ const stale = [];
104
+ for (const stem of stems) {
105
+ const audio = audioOf.get(stem);
106
+ const side = join(dir, `${stem}.visemes.json`);
107
+ const txt = join(dir, `${stem}.txt`);
108
+ const key = [statKey(audio), statKey(side), statKey(txt), state[stem]?.visemes ?? '', rhubarb].join('|');
109
+ const hit = memo.get(side);
110
+ let why;
111
+ if (hit?.[0] === key) why = hit[1];
112
+ else {
113
+ why = null;
114
+ if (!existsSync(side)) why = 'it is missing';
115
+ else {
116
+ let tl = null;
117
+ try { tl = JSON.parse(readFileSync(side, 'utf8')); } catch { /* unreadable */ }
118
+ if (!Array.isArray(tl?.cues)) why = 'it is not a viseme timeline';
119
+ else {
120
+ const bytes = readFileSync(audio);
121
+ why = visemeMismatch(tl, {
122
+ audioBytes: bytes,
123
+ stateHash: state[stem]?.visemes ?? null,
124
+ text: existsSync(txt) ? readFileSync(txt, 'utf8').trim() : '',
125
+ duration: audio.endsWith('.wav') ? wavDuration(bytes) : null,
126
+ rhubarb,
127
+ });
128
+ }
129
+ }
130
+ memo.set(side, [key, why]);
131
+ }
132
+ if (why) stale.push({ stem, why });
133
+ }
134
+ return { stems, stale };
135
+ }
136
+
137
+ /**
138
+ * tools/lipsync.mjs on `stems` of `dir` (all that need it when omitted), in
139
+ * parallel. Each progress line goes to `log`. Resolves `{ ok, made, why }`;
140
+ * never rejects. `spawnImpl` is for tests.
141
+ */
142
+ export function makeLipsync(dir, stems = null, { log = console.log, jobs = null, spawnImpl = spawn, env = process.env } = {}) {
143
+ const list = stems ?? lipsyncStatus(dir).stale.map((s) => s.stem);
144
+ if (!list.length) return Promise.resolve({ ok: true, made: 0, why: null });
145
+ const args = [LIPSYNC, dir, '--visemes', '--remake', list.join(',')];
146
+ if (jobs) args.push('--jobs', String(jobs));
147
+ return new Promise((done) => {
148
+ let child;
149
+ try { child = spawnImpl(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe'], env }); } catch (e) {
150
+ done({ ok: false, made: 0, why: e.message });
151
+ return;
152
+ }
153
+ let made = 0;
154
+ let err = '';
155
+ let buf = '';
156
+ child.stdout?.setEncoding?.('utf8');
157
+ child.stdout?.on('data', (chunk) => {
158
+ buf += chunk;
159
+ let nl;
160
+ while ((nl = buf.indexOf('\n')) !== -1) {
161
+ const line = buf.slice(0, nl).trimEnd();
162
+ buf = buf.slice(nl + 1);
163
+ if (/cues →/.test(line)) made++;
164
+ // the per-file lines and the pool size; the tool's own header and
165
+ // summary say what the caller says better
166
+ if (/^\s+(\[\d+\/\d+\]|cutting up to)/.test(line)) log(` lip-sync: ${line.trim()}`);
167
+ }
168
+ });
169
+ child.stderr?.on('data', (chunk) => { err += chunk; });
170
+ child.on('error', (e) => done({ ok: false, made, why: e.message }));
171
+ child.on('close', (code) => done(code === 0
172
+ ? { ok: true, made, why: null }
173
+ : { ok: false, made, why: String(err).trim().split('\n').pop() || `lipsync exited ${code}` }));
174
+ });
175
+ }
176
+
177
+ /**
178
+ * After audio was written into `dir` for the deck `html`: cut its lip-sync
179
+ * when the deck has a 2D character. New audio deleted its old sidecar
180
+ * (synthesizeSlides' `encode`), so what the run wrote is among the stale
181
+ * stems, and any other stale sidecar of the folder comes along: one run of
182
+ * Rhubarb is the cheapest place to fix it. Says what it did, or once why it
183
+ * did nothing. Resolves `{ ran, made, why }`.
184
+ */
185
+ export async function lipsyncAfterVoicing({ html, dir, log = console.log, have = haveRhubarb, make = makeLipsync }) {
186
+ if (characterMode(html) !== 'viseme') return { ran: false, made: 0, why: null };
187
+ const rhubarb = have();
188
+ const stems = lipsyncStatus(dir, { rhubarb }).stale.map((s) => s.stem);
189
+ if (!stems.length) return { ran: false, made: 0, why: null };
190
+ if (!rhubarb) log(` ${RHUBARB_HINT}`);
191
+ log(` lip-sync: cutting ${stems.length} file${stems.length === 1 ? '' : 's'} for the 2D character in ${basename(dir)}/`
192
+ + `${rhubarb ? ' with Rhubarb' : ', read from the voice'}…`);
193
+ const r = await make(dir, stems, { log });
194
+ if (!r.ok) log(` lip-sync: not made — ${r.why}; decklight narrate <deck> --face tries again`);
195
+ else log(` lip-sync: ${r.made} file${r.made === 1 ? '' : 's'} made`);
196
+ return { ran: true, made: r.made, why: r.ok ? null : r.why };
197
+ }