decklight 0.2.0 → 0.3.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 +855 -80
  3. package/cli/agents.mjs +113 -9
  4. package/cli/associate.mjs +279 -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 +564 -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 +730 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +646 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +560 -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 +201 -0
  34. package/cli/units.mjs +488 -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 +5 -4
  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 +11 -2
  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 +139 -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 +316 -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
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight video — render a deck to a narrated mp4.
6
+ //
7
+ // decklight video deck.html -o deck.mp4
8
+ // [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
9
+ // [--theme <name>] [--slides a-b] [--voiceover]
10
+ //
11
+ // One still per slide (final build state), each held for the duration of its
12
+ // narration audio plus a short tail, muxed with that audio into one mp4 — a
13
+ // deck with generated narration becomes a watchable, shareable video in one
14
+ // command. Narration resolves --narration <dir> → <deckdir>/voiceover/
15
+ // (the manifest tools/voiceover.mjs writes) → a fully silent deck where every
16
+ // slide holds --hold seconds (per-slide override: data-video-hold="8" on the
17
+ // section). Silent slides still carry a silent audio segment (anullsrc) so the
18
+ // concatenated audio track stays continuous.
19
+ //
20
+ // Capture is the tools/shot.mjs mechanism: one one-shot headless Chrome per
21
+ // frame against the deck served over http://127.0.0.1 at #/n/999 (an oversized
22
+ // step clamps to the last build, so every slide renders fully built). The deck
23
+ // is served under the `present` CSP, NOT opened over file:// with
24
+ // --allow-file-access-from-files (#229): that flag let a deck's own JS read any
25
+ // local file and exfiltrate it, and video renders decks you may not have
26
+ // vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
27
+ // frames are stills, so the character overlay appears but frozen, and timing is
28
+ // per-slide, not per-build-step (animated lipsync needs a CDP screencast — a
29
+ // Node ≥22 follow-up).
30
+
31
+ import { execFile, execFileSync, spawnSync } from 'node:child_process';
32
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
33
+ import { tmpdir } from 'node:os';
34
+ import { basename, join, relative, resolve, sep } from 'node:path';
35
+ import { promisify } from 'node:util';
36
+ import { fileURLToPath } from 'node:url';
37
+ import { chromeBin, chromeArgs } from './chrome.mjs';
38
+ import { argReader, isMain } from './args.mjs';
39
+ import { sectionBodies } from './deck-html.mjs';
40
+ import { serveForRender } from '../cli/present.mjs';
41
+
42
+ const run = promisify(execFile);
43
+
44
+ /** Every slide breathes before the next one starts talking. */
45
+ export const TAIL_SECONDS = 0.4;
46
+
47
+ const HELP = `decklight video <deck.html> [options] — render the deck to a narrated mp4
48
+
49
+ -o, --out <file> output mp4 (default: <deck>.mp4 next to the deck)
50
+ --narration <dir> narration dir (default: <deckdir>/voiceover if it has a
51
+ manifest.json; otherwise the deck renders silent)
52
+ --size <WxH> frame size (default 1280x720; both must be even)
53
+ --fps <n> video frame rate (default 30)
54
+ --hold <s> seconds a slide without narration holds (default 5;
55
+ per-slide override: data-video-hold="8" on the section)
56
+ --theme <name> render with themes/<name>.css instead of the deck's theme
57
+ --slides <a-b> only this slide range (1-based, inclusive)
58
+ --voiceover run the voiceover batch (tools/voiceover.mjs) first
59
+
60
+ Slides with narration hold for the audio's real duration + ${TAIL_SECONDS}s; slides
61
+ without hold --hold seconds over silence, so the audio track stays continuous.
62
+ Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
63
+ `;
64
+
65
+ /** '1280x720' → { w, h }. Both even — libx264 yuv420p refuses odd dimensions. */
66
+ export function parseSize(s) {
67
+ const m = /^(\d+)x(\d+)$/.exec(s ?? '');
68
+ if (!m) throw new Error(`--size must be WxH, e.g. 1280x720 (got "${s}")`);
69
+ const w = Number(m[1]); const h = Number(m[2]);
70
+ if (w % 2 || h % 2) throw new Error(`--size must be even in both dimensions (yuv420p), got ${w}x${h}`);
71
+ return { w, h };
72
+ }
73
+
74
+ /** '2-5' or '3' → { from, to } (1-based, inclusive), validated against the deck. */
75
+ export function parseSlideRange(s, total) {
76
+ if (!s) return { from: 1, to: total };
77
+ const m = /^(\d+)(?:-(\d+))?$/.exec(s);
78
+ if (!m) throw new Error(`--slides must be a-b or a single slide number (got "${s}")`);
79
+ const from = Number(m[1]); const to = m[2] ? Number(m[2]) : from;
80
+ if (from < 1 || to > total || from > to) {
81
+ throw new Error(`--slides ${s} is outside this deck (${total} slide${total === 1 ? '' : 's'})`);
82
+ }
83
+ return { from, to };
84
+ }
85
+
86
+ /** Per-slide hold seconds: data-video-hold="8" on the section, else the default. */
87
+ export function extractHolds(html, defaultHold) {
88
+ return sectionBodies(html).map((sec) => {
89
+ const tag = sec.slice(0, sec.indexOf('>'));
90
+ const m = tag.match(/data-video-hold="([\d.]+)"/);
91
+ return m ? Number(m[1]) : defaultHold;
92
+ });
93
+ }
94
+
95
+ /**
96
+ * The per-slide schedule: which audio plays under slide n, and for how long.
97
+ *
98
+ * @param {Array|null} manifest manifest.slides from tools/voiceover.mjs
99
+ * ({ file } per slide, null for silent slides) —
100
+ * or null for a fully silent deck
101
+ * @param {object} durations audio file → real (ffprobe) seconds
102
+ * @param {number[]} holds per-slide hold seconds (one per section)
103
+ * @param {{from,to}} [range] 1-based inclusive slide range
104
+ * @returns {Array<{slide, audio, duration}>} audio null ⇒ silent hold
105
+ */
106
+ export function planTimeline(manifest, durations, holds, range = null) {
107
+ const from = range?.from ?? 1;
108
+ const to = range?.to ?? holds.length;
109
+ const plan = [];
110
+ for (let n = from; n <= to; n++) {
111
+ const file = manifest?.[n - 1]?.file ?? null;
112
+ const dur = file ? durations?.[file] : null;
113
+ plan.push(Number.isFinite(dur)
114
+ ? { slide: n, audio: file, duration: Math.round((dur + TAIL_SECONDS) * 1000) / 1000 }
115
+ : { slide: n, audio: null, duration: holds[n - 1] });
116
+ }
117
+ return plan;
118
+ }
119
+
120
+ /**
121
+ * ffmpeg argv for one slide's segment: the still looped at --fps under its
122
+ * audio. Narrated slides pad the audio with the tail and stop there; silent
123
+ * slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
124
+ * carries an audio stream and the concat-demuxer's `-c copy` audio track never
125
+ * goes discontinuous. -t bounds both the infinite loop and the infinite
126
+ * anullsrc (-shortest can't end a segment whose streams are both endless).
127
+ */
128
+ export function segmentArgs({ frame, audio, duration, fps, out }) {
129
+ return [
130
+ '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
131
+ ...(audio
132
+ ? ['-i', audio, '-af', `apad=pad_dur=${TAIL_SECONDS}`]
133
+ : ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
134
+ '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
135
+ '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
136
+ '-t', Number(duration).toFixed(3), '-movflags', '+faststart', out,
137
+ ];
138
+ }
139
+
140
+ /** The concat-demuxer list: one `file '…'` line per segment, quotes escaped. */
141
+ export function concatList(segments) {
142
+ return segments.map((s) => `file '${s.replaceAll("'", "'\\''")}'`).join('\n') + '\n';
143
+ }
144
+
145
+ /** ffmpeg argv joining the segments into the output without re-encoding. */
146
+ export function concatArgs(listFile, out) {
147
+ return ['-y', '-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy',
148
+ '-movflags', '+faststart', out];
149
+ }
150
+
151
+ /** ffprobe argv for a file's real duration in seconds (prints one number). */
152
+ export function ffprobeArgs(file) {
153
+ return ['-v', 'error', '-show_entries', 'format=duration',
154
+ '-of', 'default=noprint_wrappers=1:nokey=1', file];
155
+ }
156
+
157
+ /**
158
+ * Where the narration lives: --narration <dir> (its manifest is then required)
159
+ * → <deckdir>/voiceover/manifest.json → null (a silent deck).
160
+ * @returns {{ dir, slides }|null}
161
+ */
162
+ export function resolveNarration(deckPath, narrationDir) {
163
+ const load = (dir, required) => {
164
+ const path = join(dir, 'manifest.json');
165
+ if (!existsSync(path)) {
166
+ if (required) {
167
+ throw new Error(`--narration: no manifest.json in ${dir} — `
168
+ + 'run tools/voiceover.mjs (or decklight video --voiceover) first');
169
+ }
170
+ return null;
171
+ }
172
+ const m = JSON.parse(readFileSync(path, 'utf8'));
173
+ if (!Array.isArray(m?.slides)) {
174
+ throw new Error(`${path}: not a voiceover manifest (no slides array) — regenerate it with tools/voiceover.mjs`);
175
+ }
176
+ return { dir, slides: m.slides };
177
+ };
178
+ if (narrationDir) return load(resolve(narrationDir), true);
179
+ return load(join(resolve(deckPath, '..'), 'voiceover'), false);
180
+ }
181
+
182
+ const have = (bin) => {
183
+ try { execFileSync(bin, ['-version'], { stdio: 'ignore' }); return true; }
184
+ catch (e) { return e?.code !== 'ENOENT'; }
185
+ };
186
+
187
+ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
188
+ const { opt } = argReader(argv);
189
+ const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
190
+ if (argv.includes('--help') || !deckArg) {
191
+ (deckArg ? process.stdout : process.stderr).write(HELP);
192
+ process.exit(deckArg ? 0 : 1);
193
+ }
194
+ const deck = resolve(deckArg);
195
+ if (!existsSync(deck)) { console.error(`decklight video: no such deck: ${deck}`); process.exit(1); }
196
+
197
+ // The served root is the directory you run from — the deck must sit inside it
198
+ // so its relative assets (`../dist/decklight.js`, `themes/…`) resolve as URLs
199
+ // off the loopback origin the frames are captured against. This is `present`'s
200
+ // rule, for the same reason (#229): the deck runs under the CSP, and a read
201
+ // cannot escape the served tree. `cd` to a directory containing the deck.
202
+ const root = process.cwd();
203
+ if (deck !== root && !deck.startsWith(root + sep)) {
204
+ console.error(`decklight video: the deck must live under the current directory (${root}) — cd there first`);
205
+ process.exit(1);
206
+ }
207
+
208
+ // the voiceover encoder-detection policy: a missing tool is a hard, friendly
209
+ // error naming what to install — not a stack trace three steps later
210
+ if (!have('ffmpeg') || !have('ffprobe')) {
211
+ console.error('decklight video needs ffmpeg and ffprobe — install ffmpeg '
212
+ + '(apt install ffmpeg / brew install ffmpeg)');
213
+ process.exit(1);
214
+ }
215
+
216
+ let out; let plan; let narration;
217
+ try {
218
+ out = resolve(opt('-o', opt('--out', deck.replace(/\.html?$/i, '.mp4'))));
219
+ const { w, h } = parseSize(opt('--size', '1280x720'));
220
+ const fps = Number(opt('--fps', '30'));
221
+ const hold = Number(opt('--hold', '5'));
222
+ if (!Number.isFinite(fps) || fps <= 0) throw new Error(`--fps must be a positive number`);
223
+ if (!Number.isFinite(hold) || hold <= 0) throw new Error(`--hold must be positive seconds`);
224
+ const theme = opt('--theme');
225
+
226
+ const html = readFileSync(deck, 'utf8');
227
+ const holds = extractHolds(html, hold);
228
+ if (!holds.length) throw new Error(`${basename(deck)} has no <section> slides`);
229
+ const range = parseSlideRange(opt('--slides'), holds.length);
230
+
231
+ if (argv.includes('--voiceover')) {
232
+ const vo = [fileURLToPath(new URL('./voiceover.mjs', import.meta.url)), deck];
233
+ const nd = opt('--narration');
234
+ if (nd) vo.push('-o', resolve(nd));
235
+ const r = spawnSync(process.execPath, vo, { stdio: 'inherit' });
236
+ if (r.status !== 0) throw new Error('voiceover batch failed — see its output above');
237
+ }
238
+
239
+ narration = resolveNarration(deck, opt('--narration'));
240
+
241
+ // real durations, not the manifest's word count: ffprobe each audio file
242
+ const durations = {};
243
+ for (let n = range.from; n <= range.to; n++) {
244
+ const file = narration?.slides?.[n - 1]?.file;
245
+ if (!file || durations[file] != null) continue;
246
+ const path = join(narration.dir, file);
247
+ if (!existsSync(path)) {
248
+ console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk — holding ${holds[n - 1]}s of silence`);
249
+ continue;
250
+ }
251
+ durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
252
+ }
253
+
254
+ plan = planTimeline(narration?.slides ?? null, durations, holds, range);
255
+ log(`${basename(deck)}: ${plan.length} slide${plan.length === 1 ? '' : 's'}, `
256
+ + `${plan.filter((p) => p.audio).length} narrated`
257
+ + (narration ? ` (${narration.dir})` : ' (silent)'));
258
+
259
+ // --theme rides on the deck's response in memory (no temp file): only the
260
+ // deck itself gets the injected link; every other html asset under the root
261
+ // is served untouched. Over the loopback origin `themes/…` resolves exactly
262
+ // as the sibling-copy path used to, so a themed render is unchanged.
263
+ const inject = theme
264
+ ? (text, file) => (resolve(file) === deck
265
+ ? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`)
266
+ : text)
267
+ : null;
268
+ const deckPath = '/' + relative(root, deck).split(sep).join('/');
269
+
270
+ const work = mkdtempSync(join(tmpdir(), 'decklight-video-'));
271
+ const server = await serveForRender(root, { html: inject });
272
+ try {
273
+ const chrome = chromeBin('video');
274
+ const segments = [];
275
+ for (const p of plan) {
276
+ const nn = String(p.slide).padStart(2, '0');
277
+ const frame = join(work, `frame-${nn}.png`);
278
+ // one one-shot Chrome per frame; #/n/999 clamps to the last build step
279
+ await exec(chrome, chromeArgs(
280
+ '--hide-scrollbars',
281
+ '--autoplay-policy=no-user-gesture-required',
282
+ `--window-size=${w},${h}`,
283
+ '--virtual-time-budget=1500',
284
+ `--screenshot=${frame}`,
285
+ `${server.origin}${deckPath}#/${p.slide}/999`,
286
+ ));
287
+ if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
288
+ const seg = join(work, `seg-${nn}.mp4`);
289
+ await exec('ffmpeg', segmentArgs({
290
+ frame, duration: p.duration, fps, out: seg,
291
+ audio: p.audio ? join(narration.dir, p.audio) : null,
292
+ }));
293
+ segments.push(seg);
294
+ log(` slide ${nn}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
295
+ }
296
+
297
+ const list = join(work, 'concat.txt');
298
+ writeFileSync(list, concatList(segments));
299
+ await exec('ffmpeg', concatArgs(list, out));
300
+ } finally {
301
+ await server.close();
302
+ rmSync(work, { recursive: true, force: true });
303
+ }
304
+
305
+ const total = Number((await exec('ffprobe', ffprobeArgs(out))).stdout.trim());
306
+ log(`done → ${out} (${total.toFixed(1)}s)`);
307
+ } catch (e) {
308
+ console.error(`decklight video: ${e.message}`);
309
+ process.exit(1);
310
+ }
311
+ }
312
+
313
+ // direct execution still works: node tools/video.mjs deck.html -o deck.mp4
314
+ if (isMain(import.meta.url)) {
315
+ await videoMain(process.argv.slice(2));
316
+ }
@@ -3,23 +3,33 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  // Live voice bridge: a tiny local HTTP server the player calls to synthesize
6
- // narration ON THE FLY (SPEC §8 live voice). The browser can't mint Google
6
+ // narration ON THE FLY (SPEC PRESENTING live voice). The browser can't mint Google
7
7
  // credentials (nor run piper), so this process holds them and exposes:
8
8
  //
9
9
  // GET /ping → { ok, engine, model, voices, stylable } (player probes)
10
10
  // GET /voices → [[name, flavor], …]
11
11
  // POST /tts → audio/wav { text, voice, style }
12
12
  //
13
- // decklight tts [--port 8787] [--engine gemini|chirp|piper]
13
+ // decklight tts [--port 8787] [--engine gemini|chirp|piper|elevenlabs]
14
14
  // [--project <id>] (or set GOOGLE_CLOUD_PROJECT)
15
15
  // [--tts-model gemini-2.5-flash-tts] [--location global]
16
16
  // [--voice en_US-ryan-high] [--data-dir <dir>] [--lang en-US]
17
+ // [--tts-format pcm|mp3] (elevenlabs)
18
+ // [--setup] (re-run the guided setup)
19
+ //
20
+ // First run: with nothing configured on a terminal, tts walks through the
21
+ // guided setup (tts-setup.mjs) instead of exiting with the engine's error —
22
+ // engine choice, that engine's prerequisites, one test synthesis — and saves
23
+ // the answers to ~/.config/decklight/tts.json ($XDG_CONFIG_HOME honored).
24
+ // Precedence: flags > environment > saved config > built-in default.
17
25
  //
18
26
  // Engines differ in what they cost and what they can be told (tts-engines.mjs):
19
27
  // gemini takes a style instruction and has no free tier; chirp is ~1s a
20
- // sentence with 1M free chars a month; piper is offline and unlimited. /ping
28
+ // sentence with 1M free chars a month; piper is offline and unlimited;
29
+ // elevenlabs speaks your account's own voices, cloned ones included. /ping
21
30
  // reports which one is live, so the player's picker offers only voices this
22
- // bridge can actually speak.
31
+ // bridge can actually speak — which for ElevenLabs means asking the account
32
+ // first, so /ping and /voices await that lookup rather than guessing.
23
33
  //
24
34
  // CORS is wide open (decks run on file://, origin "null") — the server binds
25
35
  // 127.0.0.1 only. Responses are cached in memory by (text, voice, style), so
@@ -27,84 +37,156 @@
27
37
 
28
38
  import { createServer } from 'node:http';
29
39
  import { createHash } from 'node:crypto';
30
- import { createEngine, ENGINES } from './tts-engines.mjs';
40
+ import { createInterface } from 'node:readline/promises';
41
+ import { resolveEngine, ENGINES } from './tts-engines.mjs';
42
+ import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
43
+ import { argReader, isMain } from './args.mjs';
44
+ import { corsHeaders, readBody } from './bridge.mjs';
45
+ import { installedVoices } from '../cli/units.mjs';
31
46
 
32
47
  export async function ttsMain(args) {
33
48
  if (args.includes('--help')) {
34
- console.log(`usage: decklight tts [--port 8787] [--engine ${ENGINES.join('|')}] [--project <id>]
49
+ console.log(`usage: decklight tts [--port 8787] [--engine ${ENGINES.join('|')}|<installed>] [--project <id>]
35
50
  [--tts-model id] [--location global] [--voice name] [--data-dir dir] [--lang en-US]
51
+ [--tts-format pcm|mp3] [--tts-stability creative|natural|robust] [--setup]
36
52
 
37
53
  gemini gemini-2.5-pro-tts (default) or --tts-model gemini-2.5-flash-tts — Vertex AI, best
38
54
  delivery, the only engine that honors a style instruction. No free tier.
39
55
  chirp Chirp 3: HD on the Cloud Text-to-Speech API — same 30 voices, ~1s a sentence,
40
56
  1M characters a month free. Needs texttospeech.googleapis.com enabled.
41
57
  piper local neural TTS — offline, unlimited, no credentials, no cost.
58
+ elevenlabs your ElevenLabs account's own voices — the ones you cloned included, listed
59
+ first in the picker. Needs $ELEVENLABS_API_KEY (never written to disk).
60
+ --tts-model eleven_multilingual_v2 (default) / eleven_turbo_v2_5 for latency /
61
+ eleven_v3 to opt into style direction via audio tags — higher latency, more
62
+ variable consistency, and best on short prompts; the only ElevenLabs model
63
+ the picker's tone step appears for.
64
+ --tts-stability creative|natural|robust — how hard v3 follows a tag (v3 only;
65
+ refused on any other model rather than silently doing nothing).
66
+ --tts-format mp3 if your plan has no PCM output (costs you ⇧V and lip-sync).
67
+
68
+ <installed> any engine from a marketplace (decklight engine add <name>) — --engine
69
+ takes its name like any of the six above, and the picker treats it the same.
42
70
 
43
- project also read from $GOOGLE_CLOUD_PROJECT (gemini and chirp only)`);
71
+ project also read from $GOOGLE_CLOUD_PROJECT (gemini and chirp only)
72
+
73
+ first run: with nothing configured on a terminal, tts asks a few guided
74
+ questions (engine, prerequisites, one test synthesis) and saves the answers
75
+ to ${ttsConfigPath()} — --setup re-runs them.
76
+ precedence: flags > environment > saved config > built-in default`);
44
77
  return;
45
78
  }
46
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
79
+ const { opt } = argReader(args);
47
80
  const port = Number(opt('--port', 8787));
48
- const engineName = opt('--engine', 'gemini');
49
- if (!ENGINES.includes(engineName)) {
50
- console.error(`decklight tts: unknown engine '${engineName}' — use ${ENGINES.join(', ')}`);
51
- process.exitCode = 1;
52
- return;
53
- }
81
+ const saved = loadTtsConfig();
82
+ const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
83
+ const engineName = opt('--engine') ?? saved?.engine ?? 'gemini';
84
+ // saved voice/data-dir belong to the engine they were saved for — a piper
85
+ // model name is meaningless to gemini
86
+ const savedFor = saved?.engine === engineName ? saved : null;
87
+
88
+ const wizard = async () => {
89
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
90
+ try { return await runSetupWizard({ ask: (q) => rl.question(q), prefill: saved ?? {} }); }
91
+ finally { rl.close(); }
92
+ };
54
93
 
55
94
  let engine;
56
- try {
57
- engine = createEngine({
58
- engine: engineName,
59
- project: opt('--project', process.env.GOOGLE_CLOUD_PROJECT),
60
- model: opt('--tts-model'),
61
- location: opt('--location'),
62
- voice: opt('--voice'),
63
- dataDir: opt('--data-dir'),
64
- lang: opt('--lang'),
65
- });
66
- } catch (e) {
67
- console.error(`decklight tts: ${e.message}`);
68
- process.exitCode = 1;
69
- return;
95
+ if (args.includes('--setup')) {
96
+ if (!tty) {
97
+ console.error('decklight tts: --setup needs a terminal to ask its questions on');
98
+ process.exitCode = 1;
99
+ return;
100
+ }
101
+ engine = (await wizard())?.engine;
102
+ if (!engine) { process.exitCode = 1; return; }
103
+ } else {
104
+ try {
105
+ // resolveEngine, not createEngine: a name that is not one of the six
106
+ // built-ins may still be an INSTALLED engine (SPEC ENGINE_UNITS), and
107
+ // the bridge cannot know which kind it was handed.
108
+ engine = await resolveEngine({
109
+ engine: engineName,
110
+ project: opt('--project') ?? process.env.GOOGLE_CLOUD_PROJECT ?? saved?.project,
111
+ model: opt('--tts-model'),
112
+ location: opt('--location'),
113
+ voice: opt('--voice') ?? savedFor?.voice,
114
+ dataDir: opt('--data-dir') ?? savedFor?.dataDir,
115
+ lang: opt('--lang'),
116
+ format: opt('--tts-format') ?? savedFor?.format,
117
+ stability: opt('--tts-stability'),
118
+ });
119
+ } catch (e) {
120
+ // an explicit --engine/--project is a hand on the wheel — fail exactly
121
+ // as before; otherwise, on a terminal, the error becomes the first
122
+ // question of the guided setup instead of the end of the road
123
+ if (!tty || args.includes('--engine') || args.includes('--project')) {
124
+ console.error(`decklight tts: ${e.message}`);
125
+ process.exitCode = 1;
126
+ return;
127
+ }
128
+ console.log(`no voice engine configured yet (${e.message})`);
129
+ engine = (await wizard())?.engine;
130
+ if (!engine) { process.exitCode = 1; return; }
131
+ }
70
132
  }
71
133
 
134
+ // ElevenLabs' roster belongs to the account, so it is a network call, not a
135
+ // constant. Cached inside the engine; this just picks whichever kind of
136
+ // answer the live engine has.
137
+ // Installed marketplace voices are references, not audio (SPEC VOICE_UNITS):
138
+ // the library holds `{engine, voiceId}` and the engine does the speaking. Read
139
+ // once at startup — the library is a local directory the presenter edits with
140
+ // a CLI, not something that changes under a running bridge.
141
+ //
142
+ // The picker offers the human-readable name, so the id it stands for has to be
143
+ // put back before synth; that resolution lives HERE, next to the merge that
144
+ // made the name offerable, rather than in each engine — an engine that had to
145
+ // know about the unit library would be an engine that could no longer be
146
+ // tested without one.
147
+ const refs = installedVoices(engine.name);
148
+ const refIds = new Map(refs.map((r) => [r.label, r.voiceId]));
149
+ if (refs.length) console.log(` voices: +${refs.length} installed (decklight voice list)`);
150
+
151
+ const voiceRoster = async () => [
152
+ ...(engine.listVoices ? (await engine.listVoices()).map((v) => [v.name, v.flavor]) : engine.voices),
153
+ ...refs.map((r) => [r.label, r.marketplace ?? 'installed']),
154
+ ];
155
+
72
156
  const cache = new Map();
73
157
 
74
- const CORS = {
75
- 'access-control-allow-origin': '*',
76
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
77
- 'access-control-allow-headers': 'content-type',
78
- // the player reads the cost estimate for its debug window
79
- 'access-control-expose-headers': 'x-tts-cost, x-tts-tokens, x-tts-cached',
80
- };
158
+ // the player reads the cost estimate for its debug window
159
+ const CORS = corsHeaders('x-tts-cost, x-tts-tokens, x-tts-cached');
81
160
  let totalCost = 0;
82
161
  let totalChars = 0;
83
162
 
84
163
  const server = createServer(async (req, res) => {
85
164
  if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
86
165
  if (req.method === 'GET' && req.url === '/ping') {
166
+ // A roster the bridge cannot fetch is not a reason to report itself dead:
167
+ // the player falls back to its built-in list, and a synth would say why.
168
+ const voices = await voiceRoster().catch((e) => {
169
+ console.error(` voices: ${String(e.message ?? e).slice(0, 160)}`);
170
+ return [];
171
+ });
87
172
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
88
173
  return res.end(JSON.stringify({
89
174
  ok: true,
90
175
  engine: engine.name,
91
176
  model: engine.model,
92
177
  stylable: engine.stylable, // gemini alone can be told HOW to say it
93
- voices: engine.voices, // piper speaks one voice, not the star roster
178
+ voices, // piper speaks one voice, not the star roster
94
179
  }));
95
180
  }
96
181
  if (req.method === 'GET' && req.url === '/voices') {
97
182
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
98
- return res.end(JSON.stringify(engine.voices));
183
+ return res.end(JSON.stringify(await voiceRoster()));
99
184
  }
100
185
  if (req.method === 'POST' && req.url === '/tts') {
101
186
  try {
102
- // body read INSIDE the try: a client abort mid-request rejects the
103
- // stream, and outside the try it would crash the whole bridge
104
- let body = '';
105
- for await (const chunk of req) body += chunk;
106
- const { text, voice, style } = JSON.parse(body);
187
+ const { text, voice: picked, style } = JSON.parse((await readBody(req)).toString());
107
188
  if (!text?.trim()) { res.writeHead(400, CORS); return res.end('no text'); }
189
+ const voice = refIds.get(picked) ?? picked;
108
190
  // NUL joins the fields so they cannot run together (a style ending in a
109
191
  // space and a text starting with one must not hash like their neighbours)
110
192
  // — but written as an ESCAPE, not a raw byte. This file used to carry
@@ -114,25 +196,45 @@ export async function ttsMain(args) {
114
196
  .update([engine.name, voice, style, text].join('\u0000')).digest('hex');
115
197
  const fresh = !cache.has(key);
116
198
  if (fresh) {
117
- process.stdout.write(` ${engine.name} ${voice}: ${text.length} chars … `);
199
+ process.stdout.write(` ${engine.name} ${picked}: ${text.length} chars … `);
118
200
  const t0 = Date.now();
119
201
  cache.set(key, await engine.synth(text, { voice, style }));
120
202
  const u = cache.get(key).usage;
121
- totalCost += u.cost;
203
+ // `cost` is OPTIONAL, and an installed engine is why (SPEC
204
+ // ENGINE_UNITS): the six built-ins all happen to report one, so
205
+ // reading it unguarded worked until a marketplace engine that
206
+ // meters differently — or not at all — returned usage without it
207
+ // and took the sentence down mid-talk with a TypeError. A missing
208
+ // price is not zero either; it is "no list price to quote", which
209
+ // is what `hasCost` below shows instead of inventing $0.0000.
210
+ const hasCost = typeof u.cost === 'number' && Number.isFinite(u.cost);
211
+ if (hasCost) totalCost += u.cost;
122
212
  totalChars += u.chars ?? text.length;
123
213
  // chirp's free tier is denominated in CHARACTERS, so show those too —
124
214
  // a dollar estimate alone would read as a bill for something free
215
+ // A dollar figure is only honest where a list price exists. Chirp has
216
+ // one behind a free tier; ElevenLabs meters characters against a plan
217
+ // rate we cannot see, so it gets characters and no invented number.
125
218
  const spend = engine.name === 'chirp'
126
219
  ? `${(totalChars / 1000).toFixed(1)}k/1000k free chars this month · ~$${totalCost.toFixed(4)} list`
127
- : `~$${u.cost.toFixed(4)} (session ~$${totalCost.toFixed(4)})`;
128
- console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s · ${u.note} · ${spend}`);
220
+ : engine.name === 'elevenlabs'
221
+ ? `${totalChars} chars this session · billed against your plan`
222
+ : hasCost
223
+ ? `~$${u.cost.toFixed(4)} (session ~$${totalCost.toFixed(4)})`
224
+ : `${totalChars} chars this session`;
225
+ console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s · ${u.note ?? `${text.length} chars`} · ${spend}`);
129
226
  }
130
227
  const { wav, usage } = cache.get(key);
131
228
  res.writeHead(200, {
132
229
  ...CORS,
133
- 'content-type': 'audio/wav',
134
- // cost is charged once, at synthesis — cache replays are free
135
- 'x-tts-cost': fresh ? usage.cost.toFixed(6) : '0',
230
+ // mp3 is an ElevenLabs opt-in; every other path is a real WAV
231
+ 'content-type': engine.synth.mimeType ?? 'audio/wav',
232
+ // cost is charged once, at synthesis — cache replays are free.
233
+ // An engine that quotes no price sends no number rather than '0',
234
+ // which would read as "this was free" (SPEC ENGINE_UNITS).
235
+ 'x-tts-cost': fresh && typeof usage.cost === 'number' && Number.isFinite(usage.cost)
236
+ ? usage.cost.toFixed(6)
237
+ : '0',
136
238
  'x-tts-tokens': usage.note ?? '',
137
239
  'x-tts-cached': fresh ? '0' : '1',
138
240
  });
@@ -148,10 +250,17 @@ export async function ttsMain(args) {
148
250
  });
149
251
 
150
252
  server.listen(port, '127.0.0.1', () => {
151
- const cost = engine.name === 'piper' ? 'free · offline'
152
- : engine.name === 'chirp' ? 'first 1M chars/month free'
153
- : 'billed per call — no free tier';
154
- console.log(`decklight tts bridge on http://127.0.0.1:${port} — ${engine.name} · ${engine.model} (${cost}) — Ctrl-C stops`);
253
+ // The BOUND port, not the requested one: `--port 0` legitimately means
254
+ // "pick a free one", and printing the 0 back made the one line telling a
255
+ // presenter where their bridge is into an unusable URL.
256
+ const bound = server.address()?.port ?? port;
257
+ // `cost` is optional (SPEC ENGINE_UNITS) — an installed engine that
258
+ // quotes no list price says nothing here rather than "(undefined)".
259
+ const price = engine.cost ? ` (${engine.cost})` : '';
260
+ console.log(`decklight tts bridge on http://127.0.0.1:${bound} — ${engine.name} · ${engine.model}${price} — Ctrl-C stops`);
261
+ // Stated here, once, where the presenter is still choosing — not
262
+ // discovered mid-talk when the delivery already varied more than expected.
263
+ if (engine.caveat) console.log(` ${engine.caveat}`);
155
264
  // piper loads a ~120 MB model on start; do it now, while the deck is still
156
265
  // being opened, so the first sentence isn't a 13-second silence
157
266
  if (engine.synth.warm) {
@@ -161,4 +270,4 @@ export async function ttsMain(args) {
161
270
  });
162
271
  }
163
272
 
164
- if (import.meta.url === `file://${process.argv[1]}`) ttsMain(process.argv.slice(2));
273
+ if (isMain(import.meta.url)) ttsMain(process.argv.slice(2));