decklight 0.2.0 → 0.4.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +881 -80
  3. package/cli/agents.mjs +116 -10
  4. package/cli/associate.mjs +286 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +577 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +911 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +654 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +564 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +219 -0
  34. package/cli/units.mjs +500 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +7 -5
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +46 -11
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +144 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +440 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // Lip-sync bridge: a tiny local HTTP server the player calls to turn
3
- // narration audio into lip-sync data for the character overlay (SPEC §8).
3
+ // narration audio into lip-sync data for the character overlay (SPEC PRESENTING).
4
4
  // Everything runs on THIS machine — Rhubarb Lip Sync for viseme timelines,
5
5
  // Wav2Lip / SadTalker (local python repos, your GPU) for talking-head video.
6
6
  // No cloud service is involved; the browser just can't spawn native
@@ -33,11 +33,14 @@
33
33
  import { createServer } from 'node:http';
34
34
  import { createHash } from 'node:crypto';
35
35
  import { execFile } from 'node:child_process';
36
- import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, renameSync, readdirSync, statSync, copyFileSync } from 'node:fs';
36
+ import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, copyFileSync } from 'node:fs';
37
37
  import { join, resolve, basename } from 'node:path';
38
38
  import { homedir } from 'node:os';
39
39
  import { promisify } from 'node:util';
40
- import { normalizeRhubarb } from './visemes.mjs';
40
+ import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
41
+ import { argReader, isMain } from './args.mjs';
42
+ import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
43
+ import { corsHeaders, readBody } from './bridge.mjs';
41
44
 
42
45
  const run = promisify(execFile);
43
46
 
@@ -62,15 +65,27 @@ export async function lipsyncMain(args) {
62
65
  [--wav2lip-dir <repo> --wav2lip-ckpt <checkpoint.pth>]
63
66
  [--sadtalker-dir <repo>] [--python python3]
64
67
  [--cache-dir ~/.cache/decklight/lipsync]
68
+ [--veo] [--veo-project <id>] [--veo-model veo-3.1-lite-generate-001]
69
+ [--veo-seconds 4|6|8] [--veo-prompt "..."] [--veo-location us-central1]
70
+ [--veo-face-y 0.12] where the square crop starts, as a fraction of height
65
71
 
66
72
  Viseme timelines need rhubarb on PATH (or --rhubarb):
67
73
  https://github.com/DanielSWolf/rhubarb-lip-sync
68
74
  Talking-head video needs a local Wav2Lip and/or SadTalker checkout, a GPU,
69
- and at least one --portrait. Everything runs offline on this machine.`);
75
+ and at least one --portrait. Everything runs offline on this machine.
76
+
77
+ --veo is the exception, and the only thing here that leaves the machine: it
78
+ animates each portrait ONCE through Veo on Vertex AI (head turns, blinks,
79
+ shoulders) and hands Wav2Lip that clip instead of the still, so the narrator
80
+ moves like a person instead of staring. One billed call per portrait, cached
81
+ in --cache-dir forever; the per-sentence lip-sync stays local on your GPU.
82
+ Give it a HEAD-AND-SHOULDERS portrait (3:4 or taller). The clip is cropped
83
+ square around the head for the deck's circular overlay, and a tight square
84
+ photo puts the face lower in Veo's 9:16 frame — chin off the bottom. Nudge
85
+ --veo-face-y up (~0.22) for such a portrait, or feed it one with headroom.`);
70
86
  return;
71
87
  }
72
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
73
- const opts = (flag) => args.flatMap((a, i) => (a === flag ? [args[i + 1]] : []));
88
+ const { opt, opts } = argReader(args);
74
89
  const port = Number(opt('--port', 8789));
75
90
  const rhubarb = opt('--rhubarb', 'rhubarb');
76
91
  const python = opt('--python', 'python3');
@@ -80,6 +95,29 @@ and at least one --portrait. Everything runs offline on this machine.`);
80
95
  const cacheDir = resolve(opt('--cache-dir', join(homedir(), '.cache', 'decklight', 'lipsync')));
81
96
  mkdirSync(cacheDir, { recursive: true });
82
97
 
98
+ // Veo: the portrait's MOTION, bought once (tools/veo.mjs). Only wav2lip can
99
+ // use it — SadTalker animates the head itself and wants a still.
100
+ const veoOn = args.includes('--veo');
101
+ let veo = null;
102
+ if (veoOn) {
103
+ try {
104
+ veo = createVeo({
105
+ project: opt('--veo-project', process.env.GOOGLE_CLOUD_PROJECT),
106
+ location: opt('--veo-location', 'us-central1'),
107
+ model: opt('--veo-model', VEO_MODELS[0]),
108
+ seconds: Number(opt('--veo-seconds', 8)),
109
+ prompt: opt('--veo-prompt', DEFAULT_PROMPT),
110
+ faceY: Number(opt('--veo-face-y', 0.12)),
111
+ cacheDir,
112
+ });
113
+ } catch (e) {
114
+ // A misconfigured --veo must not cost you the whole bridge: visemes and
115
+ // still-portrait video still work, so say what broke and carry on.
116
+ console.error(`veo disabled — ${e.message}`);
117
+ veo = null;
118
+ }
119
+ }
120
+
83
121
  // portraits: --portrait alice=face.png (or a bare path — named by basename)
84
122
  const portraits = new Map();
85
123
  for (const p of opts('--portrait')) {
@@ -134,11 +172,10 @@ and at least one --portrait. Everything runs offline on this machine.`);
134
172
  const tmpTxt = join(cacheDir, `${key}.tmp.txt`);
135
173
  const tmpOut = join(cacheDir, `${key}.tmp.json`);
136
174
  writeFileSync(tmpWav, wav);
137
- const dialog = text.trim() ? (writeFileSync(tmpTxt, text), ['--dialogFile', tmpTxt]) : [];
175
+ if (text.trim()) writeFileSync(tmpTxt, text);
138
176
  try {
139
177
  const t0 = Date.now();
140
- await run(rhubarb, ['-f', 'json', '-o', tmpOut, '--machineReadable', ...dialog, tmpWav], { timeout: 120000 });
141
- const tl = normalizeRhubarb(JSON.parse(readFileSync(tmpOut, 'utf8')));
178
+ const tl = await runRhubarb(rhubarb, { wav: tmpWav, dialogFile: text.trim() ? tmpTxt : undefined, out: tmpOut, timeout: 120000 });
142
179
  writeFileSync(out, JSON.stringify(tl));
143
180
  console.log(` viseme: ${(wav.length / 1024).toFixed(0)} KB wav → ${tl.cues.length} cues · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
144
181
  } finally {
@@ -150,8 +187,16 @@ and at least one --portrait. Everything runs offline on this machine.`);
150
187
 
151
188
  async function video(wav, engine, portraitName) {
152
189
  if (!videoEngines.includes(engine)) throw new Error(`engine '${engine}' not available`);
153
- const face = portraits.get(portraitName);
154
- if (!face) throw new Error(`unknown portrait '${portraitName}'`);
190
+ const still = portraits.get(portraitName);
191
+ if (!still) throw new Error(`unknown portrait '${portraitName}'`);
192
+ // With --veo, wav2lip's source is the portrait's motion clip rather than the
193
+ // portrait: same model, same per-sentence cost, but the head is alive under
194
+ // the new mouth. Bought once per portrait and cached (tools/veo.mjs), so
195
+ // this awaits a network call only the very first time. SadTalker is left
196
+ // alone — it makes its own head motion and needs the still.
197
+ const face = veo && engine === 'wav2lip' ? await veo.motionFor(still) : still;
198
+ // the key reads `face`, so a veo clip and a still can never share a cache
199
+ // entry — flip --veo off and yesterday's clips are still there, untouched
155
200
  const key = sha('video|', engine, '|', readFileSync(face), '|', wav);
156
201
  const out = join(cacheDir, `${key}.mp4`);
157
202
  if (existsSync(out)) return { body: readFileSync(out), cached: true };
@@ -165,24 +210,23 @@ and at least one --portrait. Everything runs offline on this machine.`);
165
210
  const t0 = Date.now();
166
211
  process.stdout.write(` video ${engine} · ${portraitName}: ${(wav.length / 1024).toFixed(0)} KB wav … `);
167
212
  if (engine === 'wav2lip') {
168
- await run(python, ['inference.py', '--checkpoint_path', resolve(wav2lipCkpt),
169
- '--face', face, '--audio', tmpWav, '--outfile', tmpMp4],
170
- { cwd: resolve(wav2lipDir), timeout: 600000, maxBuffer: 64 * 1024 * 1024 });
213
+ // A still is ONE frame to detect a face in; a --veo motion clip is a
214
+ // couple of hundred. Wav2Lip's face detector batches 16 frames by
215
+ // default, halving on CUDA OOM until it gives up at 1 with "Image too
216
+ // big to run face detection on GPU" — which it will do on an 8 GB card
217
+ // that a desktop is already using half of. Batch small instead: the
218
+ // clip is short, and the GPU queue is serial anyway.
219
+ await runWav2lip(python, { dir: wav2lipDir, checkpoint: wav2lipCkpt, face,
220
+ wav: tmpWav, out: tmpMp4, smallBatches: face !== still, timeout: 600000 });
171
221
  } else {
172
- mkdirSync(tmpDir, { recursive: true });
173
- await run(python, ['inference.py', '--driven_audio', tmpWav,
174
- '--source_image', face, '--result_dir', tmpDir],
175
- { cwd: resolve(sadtalkerDir), timeout: 1800000, maxBuffer: 64 * 1024 * 1024 });
176
- // SadTalker writes <timestamp>/….mp4 into result_dir — take the newest
177
- const found = [];
178
- const walk = (d) => { for (const f of readdirSync(d)) { const p = join(d, f); const s = statSync(p); if (s.isDirectory()) walk(p); else if (f.endsWith('.mp4')) found.push([s.mtimeMs, p]); } };
179
- walk(tmpDir);
180
- if (!found.length) throw new Error('sadtalker produced no mp4');
181
- renameSync(found.sort((a, b) => b[0] - a[0])[0][1], tmpMp4);
222
+ // SadTalker writes <timestamp>/….mp4 into result_dir — runSadtalker
223
+ // takes the newest and moves it to tmpMp4.
224
+ await runSadtalker(python, { dir: sadtalkerDir, still: face,
225
+ wav: tmpWav, out: tmpMp4, resultDir: tmpDir, timeout: 1800000 });
182
226
  }
183
227
  // strip the audio track (playback is muted — narrAudio is the voice)
184
228
  // and front-load the moov atom so the player can start instantly
185
- if (ffmpegOk) await run('ffmpeg', ['-y', '-i', tmpMp4, '-an', '-movflags', '+faststart', '-c:v', 'copy', out], { timeout: 120000 });
229
+ if (ffmpegOk) await muteFaststart(tmpMp4, out, { timeout: 120000 });
186
230
  else copyFileSync(tmpMp4, out);
187
231
  console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s → ${(statSync(out).size / 1024).toFixed(0)} KB`);
188
232
  } finally {
@@ -193,12 +237,7 @@ and at least one --portrait. Everything runs offline on this machine.`);
193
237
  return { body: readFileSync(out), cached: false };
194
238
  }
195
239
 
196
- const CORS = {
197
- 'access-control-allow-origin': '*',
198
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
199
- 'access-control-allow-headers': 'content-type',
200
- 'access-control-expose-headers': 'x-lipsync-cached',
201
- };
240
+ const CORS = corsHeaders('x-lipsync-cached');
202
241
 
203
242
  const server = createServer(async (req, res) => {
204
243
  if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
@@ -208,16 +247,14 @@ and at least one --portrait. Everything runs offline on this machine.`);
208
247
  return res.end(JSON.stringify({
209
248
  ok: true,
210
249
  engines: { viseme: visemeOk, video: videoEngines },
250
+ // what the head is driven from: a veo motion clip, or the still photo
251
+ motion: veo ? { engine: 'veo', model: veo.model, seconds: veo.seconds } : null,
211
252
  portraits: [...portraits.keys()],
212
253
  }));
213
254
  }
214
255
  if (req.method === 'POST' && (url.pathname === '/viseme' || url.pathname === '/video')) {
215
256
  try {
216
- // body read INSIDE the try: a client abort mid-request rejects the
217
- // stream, and outside the try it would crash the whole bridge
218
- const chunks = [];
219
- for await (const c of req) chunks.push(c);
220
- const wav = Buffer.concat(chunks);
257
+ const wav = await readBody(req);
221
258
  if (wav.length < 44) { res.writeHead(400, CORS); return res.end('no audio'); }
222
259
  const out = url.pathname === '/viseme'
223
260
  ? await visemes(wav, url.searchParams.get('text') ?? '')
@@ -241,9 +278,13 @@ and at least one --portrait. Everything runs offline on this machine.`);
241
278
  server.listen(port, '127.0.0.1', () => {
242
279
  const what = [visemeOk && 'visemes (rhubarb)', ...videoEngines.map((e) => `video (${e})`)].filter(Boolean).join(' · ');
243
280
  console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
281
+ if (veo) {
282
+ console.log(`veo: ${veo.model} · ${veo.seconds}s — each portrait is animated ONCE (billed), `
283
+ + 'then wav2lip re-syncs that clip locally for every sentence');
284
+ }
244
285
  console.log(`cache: ${cacheDir}`);
245
286
  });
246
287
  return server;
247
288
  }
248
289
 
249
- if (import.meta.url === `file://${process.argv[1]}`) lipsyncMain(process.argv.slice(2));
290
+ if (isMain(import.meta.url)) lipsyncMain(process.argv.slice(2));
package/tools/lipsync.mjs CHANGED
@@ -25,11 +25,13 @@
25
25
  // (audio bytes, tool, engine, portrait) per slide, persisted after every
26
26
  // slide, so a rerun only regenerates what actually changed.
27
27
 
28
- import { readFileSync, writeFileSync, existsSync, readdirSync, rmSync, renameSync, mkdirSync, statSync } from 'node:fs';
28
+ import { readFileSync, writeFileSync, existsSync, readdirSync, rmSync, renameSync } from 'node:fs';
29
29
  import { createHash } from 'node:crypto';
30
30
  import { execFileSync } from 'node:child_process';
31
31
  import { resolve, join, basename } from 'node:path';
32
- import { normalizeRhubarb } from './visemes.mjs';
32
+ import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
33
+ import { argReader } from './args.mjs';
34
+ import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
33
35
 
34
36
  const args = process.argv.slice(2);
35
37
  const dirArg = args.find((a) => !a.startsWith('-'));
@@ -40,7 +42,7 @@ if (!dirArg || args.includes('--help')) {
40
42
  process.exit(dirArg ? 0 : 1);
41
43
  }
42
44
  const dir = resolve(dirArg);
43
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
45
+ const { opt } = argReader(args);
44
46
  const doVideo = args.includes('--video');
45
47
  const doVisemes = args.includes('--visemes') || !doVideo; // visemes by default
46
48
  const rhubarb = opt('--rhubarb', 'rhubarb');
@@ -50,6 +52,20 @@ const wav2lipDir = opt('--wav2lip-dir');
50
52
  const wav2lipCkpt = opt('--wav2lip-ckpt');
51
53
  const sadtalkerDir = opt('--sadtalker-dir');
52
54
  const python = opt('--python', 'python3');
55
+ // --veo: animate the portrait ONCE through Vertex (tools/veo.mjs) and give
56
+ // wav2lip that clip instead of the still, so the recorded narrator moves
57
+ // instead of staring. One billed call per portrait, cached next to the audio.
58
+ const veoOn = args.includes('--veo');
59
+
60
+ const veo = veoOn ? createVeo({
61
+ project: opt('--veo-project', process.env.GOOGLE_CLOUD_PROJECT),
62
+ location: opt('--veo-location', 'us-central1'),
63
+ model: opt('--veo-model', VEO_MODELS[0]),
64
+ seconds: Number(opt('--veo-seconds', 8)),
65
+ prompt: opt('--veo-prompt', DEFAULT_PROMPT),
66
+ faceY: Number(opt('--veo-face-y', 0.12)),
67
+ cacheDir: dir,
68
+ }) : null;
53
69
 
54
70
  const have = (bin, flags = ['--version']) => {
55
71
  try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
@@ -93,6 +109,11 @@ function toWav(nn) {
93
109
  return { path: tmp, tmp: true };
94
110
  }
95
111
 
112
+ // One portrait → one motion clip → every slide. Bought before the loop so the
113
+ // cost is one call, not one per slide, and so a failure stops us before any
114
+ // GPU time is spent.
115
+ const face = veo && engine === 'wav2lip' ? await veo.motionFor(portrait) : portrait;
116
+
96
117
  let made = 0, kept = 0;
97
118
  for (const nn of slides) {
98
119
  const audioFile = ['wav', 'm4a'].map((e) => join(dir, `slide-${nn}.${e}`)).find(existsSync);
@@ -108,7 +129,7 @@ for (const nn of slides) {
108
129
  const outFile = join(dir, job === 'visemes' ? `slide-${nn}.visemes.json` : `slide-${nn}.mp4`);
109
130
  const hash = job === 'visemes'
110
131
  ? sha('visemes|', text, '|', audioBytes)
111
- : sha('video|', engine, '|', readFileSync(portrait), '|', audioBytes);
132
+ : sha('video|', engine, '|', readFileSync(face), '|', audioBytes); // `face`, so --veo re-renders
112
133
  if (st[job] === hash && existsSync(outFile)) {
113
134
  kept++;
114
135
  console.log(` slide ${nn}: ${job} unchanged — kept`);
@@ -119,10 +140,9 @@ for (const nn of slides) {
119
140
  const t0 = Date.now();
120
141
  if (job === 'visemes') {
121
142
  const tmpOut = join(dir, `slide-${nn}.tmp.visemes.json`);
122
- const dialog = [];
123
- if (text) { writeFileSync(join(dir, `slide-${nn}.tmp.txt`), text); dialog.push('--dialogFile', join(dir, `slide-${nn}.tmp.txt`)); }
124
- execFileSync(rhubarb, ['-f', 'json', '-o', tmpOut, '--machineReadable', ...dialog, wav.path], { stdio: ['ignore', 'ignore', 'ignore'] });
125
- const tl = normalizeRhubarb(JSON.parse(readFileSync(tmpOut, 'utf8')));
143
+ let dialogFile;
144
+ if (text) { dialogFile = join(dir, `slide-${nn}.tmp.txt`); writeFileSync(dialogFile, text); }
145
+ const tl = await runRhubarb(rhubarb, { wav: wav.path, dialogFile, out: tmpOut });
126
146
  writeFileSync(outFile, JSON.stringify(tl));
127
147
  rmSync(tmpOut, { force: true });
128
148
  rmSync(join(dir, `slide-${nn}.tmp.txt`), { force: true });
@@ -130,25 +150,20 @@ for (const nn of slides) {
130
150
  } else {
131
151
  const tmpMp4 = join(dir, `slide-${nn}.tmp.mp4`);
132
152
  if (engine === 'wav2lip') {
133
- execFileSync(python, ['inference.py', '--checkpoint_path', resolve(wav2lipCkpt),
134
- '--face', portrait, '--audio', wav.path, '--outfile', tmpMp4],
135
- { cwd: resolve(wav2lipDir), stdio: 'inherit' });
153
+ // a --veo clip is hundreds of frames to detect faces in, not one:
154
+ // batch small or an 8GB card dies with "Image too big to run face
155
+ // detection on GPU" (see lipsync-server.mjs)
156
+ await runWav2lip(python, { dir: wav2lipDir, checkpoint: wav2lipCkpt, face,
157
+ wav: wav.path, out: tmpMp4, smallBatches: face !== portrait, inherit: true });
136
158
  } else {
137
159
  const resDir = join(dir, `slide-${nn}.tmp.d`);
138
- mkdirSync(resDir, { recursive: true });
139
- execFileSync(python, ['inference.py', '--driven_audio', wav.path,
140
- '--source_image', portrait, '--result_dir', resDir],
141
- { cwd: resolve(sadtalkerDir), stdio: 'inherit' });
142
- const found = [];
143
- const walk = (d) => { for (const f of readdirSync(d)) { const p = join(d, f); const s = statSync(p); if (s.isDirectory()) walk(p); else if (f.endsWith('.mp4')) found.push([s.mtimeMs, p]); } };
144
- walk(resDir);
145
- if (!found.length) throw new Error('sadtalker produced no mp4');
146
- renameSync(found.sort((a, b) => b[0] - a[0])[0][1], tmpMp4);
160
+ await runSadtalker(python, { dir: sadtalkerDir, still: portrait,
161
+ wav: wav.path, out: tmpMp4, resultDir: resDir, inherit: true });
147
162
  rmSync(resDir, { recursive: true, force: true });
148
163
  }
149
164
  // mute + faststart: the player's audio always comes from narrAudio
150
165
  if (ffmpegOk) {
151
- execFileSync('ffmpeg', ['-y', '-i', tmpMp4, '-an', '-movflags', '+faststart', '-c:v', 'copy', outFile], { stdio: 'ignore' });
166
+ await muteFaststart(tmpMp4, outFile);
152
167
  rmSync(tmpMp4, { force: true });
153
168
  } else renameSync(tmpMp4, outFile);
154
169
  console.log(` slide ${nn}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
@@ -0,0 +1,209 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // What can this machine say out loud, without a credential and without a
5
+ // download?
6
+ //
7
+ // Every desktop OS has shipped a speech synthesizer for twenty years, and on
8
+ // current ones they are neural and genuinely good — macOS's Premium and
9
+ // Personal Voices, Windows's mobile/neural SAPI voices. decklight already had
10
+ // a free offline engine (piper), but piper costs a toolchain install and a
11
+ // ~120 MB model download. The voice already on the machine costs nothing.
12
+ //
13
+ // So: look, and only propose piper when there is nothing to find. Everything
14
+ // here is pure over injected `exec`/`platform`, because the whole point is
15
+ // branching on an operating system that CI is not running.
16
+ //
17
+ // Android is detected and REFUSED, deliberately: Termux reports `android` and
18
+ // can run Node, but Android's TextToSpeech is an in-process Java API with no
19
+ // command line behind it, so there is nothing for a bridge to call. Saying so
20
+ // beats a bridge that starts and never speaks.
21
+
22
+ const PIPER_SUGGEST = 'piper is the free offline voice — install it with '
23
+ + '`uv tool install piper-tts`, then run `decklight tts --engine piper`';
24
+
25
+ /** `say -v '?'` on macOS: one voice per line, name, locale, sample sentence. */
26
+ export const SAY_LIST = ['-v', '?'];
27
+
28
+ /**
29
+ * PowerShell, because SAPI is a .NET API and there is no speech CLI on Windows.
30
+ * `-NoProfile` so a slow user profile cannot hang the probe.
31
+ */
32
+ export const SAPI_LIST = [
33
+ '-NoProfile', '-NonInteractive', '-Command',
34
+ 'Add-Type -AssemblyName System.Speech; '
35
+ + '(New-Object System.Speech.Synthesis.SpeechSynthesizer).GetInstalledVoices() '
36
+ + '| ForEach-Object { $_.VoiceInfo.Name }',
37
+ ];
38
+
39
+ /**
40
+ * Rank a macOS voice by how good it is likely to sound.
41
+ *
42
+ * The roster mixes twenty years of engines — 1990s formant voices sit in the
43
+ * same list as this year's neural ones — and picking the first alphabetically
44
+ * means picking Agnes. The parenthesised tier is macOS's own label, and a
45
+ * Personal Voice (the one the user recorded themselves, Apple's
46
+ * accessibility/Apple-Intelligence-era feature) outranks everything.
47
+ */
48
+ export function sayTier(name) {
49
+ if (/\(Personal Voice\)/i.test(name)) return 0;
50
+ if (/\(Premium\)/i.test(name)) return 1;
51
+ if (/\(Neural\)|\(Siri\)/i.test(name)) return 1;
52
+ if (/\(Enhanced\)/i.test(name)) return 2;
53
+ return 3;
54
+ }
55
+
56
+ const TIER_LABEL = ['personal voice', 'premium', 'enhanced', 'built-in'];
57
+
58
+ /**
59
+ * Parse `say -v '?'`.
60
+ *
61
+ * A voice NAME may contain spaces and a parenthesised tier, so the locale — the
62
+ * one token that always looks like `en_US` and always precedes the `#` — is the
63
+ * anchor, not a column position.
64
+ */
65
+ export function parseSayVoices(stdout, { lang } = {}) {
66
+ const out = [];
67
+ for (const line of String(stdout ?? '').split('\n')) {
68
+ const m = /^(.*?)\s{2,}([a-z]{2}(?:[-_][A-Za-z0-9]{2,8})*)\s*#/.exec(line)
69
+ ?? /^(.*?)\s+([a-z]{2}[-_][A-Z]{2})\s+#/.exec(line);
70
+ if (!m) continue;
71
+ const name = m[1].trim();
72
+ if (!name) continue;
73
+ out.push({ name, locale: m[2].replace('-', '_'), tier: sayTier(name) });
74
+ }
75
+ const want = (lang ?? 'en').slice(0, 2).toLowerCase();
76
+ // English (or the asked-for language) first, then by tier: a machine whose
77
+ // best voice speaks Italian should not narrate an English deck with it
78
+ return out.sort((a, b) =>
79
+ (a.locale.startsWith(want) ? 0 : 1) - (b.locale.startsWith(want) ? 0 : 1)
80
+ || a.tier - b.tier
81
+ || a.name.localeCompare(b.name));
82
+ }
83
+
84
+ /** Parse the PowerShell voice list — one name per line. */
85
+ export function parseSapiVoices(stdout) {
86
+ return String(stdout ?? '').split('\n').map((l) => l.trim()).filter(Boolean)
87
+ .map((name) => ({
88
+ name,
89
+ locale: /\b(en|fr|de|es|it|ja|zh|pt|nl|ko|ru)\b/i.exec(name)?.[1]?.toLowerCase() ?? '',
90
+ // Windows names its newer voices "Microsoft Aria Online (Natural)"
91
+ tier: /\bNatural\b/i.test(name) ? 1 : 3,
92
+ }))
93
+ .sort((a, b) => a.tier - b.tier || a.name.localeCompare(b.name));
94
+ }
95
+
96
+ /** The argv that makes macOS speak a line into a WAV file. */
97
+ export const sayArgs = (text, voice, file) => [
98
+ ...(voice ? ['-v', voice] : []),
99
+ // LEI16@24000 is little-endian 16-bit PCM at 24 kHz — the same shape every
100
+ // other engine hands the bridge, so nothing downstream has to care
101
+ '--data-format=LEI16@24000', '-o', file, '--', text,
102
+ ];
103
+
104
+ /** The PowerShell that makes Windows speak a line into a WAV file. */
105
+ export function sapiArgs(text, voice, file) {
106
+ const q = (s) => `'${String(s).replace(/'/g, "''")}'`; // PowerShell escaping
107
+ return ['-NoProfile', '-NonInteractive', '-Command',
108
+ 'Add-Type -AssemblyName System.Speech; '
109
+ + '$s = New-Object System.Speech.Synthesis.SpeechSynthesizer; '
110
+ + (voice ? `$s.SelectVoice(${q(voice)}); ` : '')
111
+ + `$s.SetOutputToWaveFile(${q(file)}); `
112
+ + `$s.Speak(${q(text)}); $s.Dispose()`];
113
+ }
114
+
115
+ /**
116
+ * What this machine can speak with, if anything.
117
+ *
118
+ * Returns `{ engine, voices, label }` when a native synthesizer is available,
119
+ * or `{ engine: null, why, suggest }` when there is none — `why` being the
120
+ * reason THIS machine has none, which differs enough between an Android
121
+ * device, a bare Linux box and a Mac with a broken `say` to be worth saying.
122
+ */
123
+ export function detectLocalVoice({
124
+ platform = process.platform,
125
+ hasBin = () => false,
126
+ exec = () => '',
127
+ lang,
128
+ } = {}) {
129
+ if (platform === 'android') {
130
+ return {
131
+ engine: null,
132
+ why: 'Android has a system voice, but only as an in-app Java API — there is no '
133
+ + 'command line behind it, so nothing here can drive it',
134
+ suggest: 'record the narration on a desktop (decklight tts, then ⇧V) and ship the '
135
+ + 'audio with the deck — a recorded track needs no bridge at all',
136
+ };
137
+ }
138
+
139
+ if (platform === 'darwin' && hasBin('say')) {
140
+ let voices = [];
141
+ try { voices = parseSayVoices(exec('say', SAY_LIST), { lang }); } catch { /* treated as none */ }
142
+ if (voices.length) {
143
+ return {
144
+ engine: 'say', voices,
145
+ label: `macOS ${TIER_LABEL[voices[0].tier]}: ${voices[0].name}`,
146
+ };
147
+ }
148
+ return { engine: null, why: 'macOS `say` is installed but reported no voices', suggest: PIPER_SUGGEST };
149
+ }
150
+
151
+ if (platform === 'win32') {
152
+ const shell = ['powershell.exe', 'pwsh.exe'].find((b) => hasBin(b));
153
+ if (shell) {
154
+ let voices = [];
155
+ try { voices = parseSapiVoices(exec(shell, SAPI_LIST)); } catch { /* treated as none */ }
156
+ if (voices.length) {
157
+ return {
158
+ engine: 'sapi', shell, voices,
159
+ label: `Windows ${voices[0].tier === 1 ? 'natural' : 'built-in'} voice: ${voices[0].name}`,
160
+ };
161
+ }
162
+ }
163
+ return { engine: null, why: 'no SAPI voices are installed on this Windows machine', suggest: PIPER_SUGGEST };
164
+ }
165
+
166
+ return {
167
+ engine: null,
168
+ why: platform === 'linux'
169
+ ? 'Linux ships no system speech synthesizer'
170
+ : `no system speech synthesizer on ${platform}`,
171
+ suggest: PIPER_SUGGEST,
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Ollama, which is not a speech engine and is the single most common thing a
177
+ * local-AI user expects to be one.
178
+ *
179
+ * It is probed only so the answer can be honest. Serving LLMs is not serving
180
+ * speech: there is no audio endpoint, and the models people name in this
181
+ * context (Kokoro, Orpheus) either are not Ollama models or need a separate
182
+ * audio decoder Ollama does not run.
183
+ */
184
+ export const OLLAMA_URL = 'http://127.0.0.1:11434/api/tags';
185
+
186
+ export async function ollamaRunning({ fetchImpl = fetch, timeoutMs = 300 } = {}) {
187
+ // A machine without Ollama must not pay for the question. The signal alone is
188
+ // not enough: it only helps if the implementation honors it, and a socket
189
+ // that hangs before the abort lands would stall dev's startup — which is the
190
+ // one thing this budget exists to prevent. So the timeout is RACED, and the
191
+ // abort is the courtesy that lets the request stop early.
192
+ const ac = new AbortController();
193
+ let timer;
194
+ const expired = new Promise((done) => {
195
+ timer = setTimeout(() => { ac.abort(); done(null); }, timeoutMs);
196
+ });
197
+ try {
198
+ const answered = Promise.resolve()
199
+ .then(() => fetchImpl(OLLAMA_URL, { signal: ac.signal }))
200
+ .catch(() => null);
201
+ const r = await Promise.race([answered, expired]);
202
+ return !!r?.ok;
203
+ } finally {
204
+ clearTimeout(timer);
205
+ }
206
+ }
207
+
208
+ export const OLLAMA_NOTE = 'Ollama is running, but it serves LLMs and cannot speak — '
209
+ + 'it has no speech endpoint';