decklight 0.1.0 → 0.2.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 (87) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +61 -177
  3. package/SPEC.md +20 -8
  4. package/cli/agents.mjs +102 -0
  5. package/cli/bundle.mjs +37 -0
  6. package/cli/decklight.mjs +18 -0
  7. package/cli/dev.mjs +266 -0
  8. package/cli/edit.mjs +230 -17
  9. package/cli/init.mjs +58 -19
  10. package/cli/rec.mjs +7 -0
  11. package/dist/decklight.css +241 -51
  12. package/dist/decklight.js +120 -76
  13. package/dist/decklight.js.map +4 -4
  14. package/package.json +6 -4
  15. package/themes/aliens.css +3 -0
  16. package/themes/apple2.css +3 -0
  17. package/themes/aurora.css +3 -0
  18. package/themes/berry.css +3 -0
  19. package/themes/blade-runner.css +3 -0
  20. package/themes/c64.css +3 -0
  21. package/themes/carbon.css +3 -0
  22. package/themes/citrus.css +3 -0
  23. package/themes/coastal.css +3 -0
  24. package/themes/cosmos.css +3 -0
  25. package/themes/dune.css +3 -0
  26. package/themes/eclipse.css +3 -0
  27. package/themes/ember.css +3 -0
  28. package/themes/fjord.css +3 -0
  29. package/themes/friends.css +3 -0
  30. package/themes/gameboy.css +3 -0
  31. package/themes/genesis.css +3 -0
  32. package/themes/glacier.css +3 -0
  33. package/themes/godfather.css +3 -0
  34. package/themes/graphite.css +3 -0
  35. package/themes/harvest.css +3 -0
  36. package/themes/ibm-modern.css +3 -0
  37. package/themes/ibm-oldschool.css +3 -0
  38. package/themes/ink.css +3 -0
  39. package/themes/latte.css +3 -0
  40. package/themes/linen.css +3 -0
  41. package/themes/meadow.css +3 -0
  42. package/themes/metropolis.css +3 -0
  43. package/themes/miami-vice.css +3 -0
  44. package/themes/midnight.css +3 -0
  45. package/themes/mint.css +3 -0
  46. package/themes/moss.css +3 -0
  47. package/themes/obsidian.css +3 -0
  48. package/themes/orchid.css +3 -0
  49. package/themes/packs.json +2 -1
  50. package/themes/paper.css +3 -0
  51. package/themes/peony.css +3 -0
  52. package/themes/porcelain.css +3 -0
  53. package/themes/pulp-fiction.css +3 -0
  54. package/themes/reveal-beige.css +3 -0
  55. package/themes/reveal-black.css +3 -0
  56. package/themes/reveal-blood.css +3 -0
  57. package/themes/reveal-dracula.css +3 -0
  58. package/themes/reveal-league.css +3 -0
  59. package/themes/reveal-moon.css +3 -0
  60. package/themes/reveal-night.css +3 -0
  61. package/themes/reveal-serif.css +3 -0
  62. package/themes/reveal-simple.css +3 -0
  63. package/themes/reveal-sky.css +3 -0
  64. package/themes/reveal-solarized.css +3 -0
  65. package/themes/reveal-white.css +3 -0
  66. package/themes/sepia.css +3 -0
  67. package/themes/seriph.css +3 -0
  68. package/themes/severance.css +3 -0
  69. package/themes/slate.css +3 -0
  70. package/themes/snes.css +3 -0
  71. package/themes/star-wars.css +3 -0
  72. package/themes/storm.css +3 -0
  73. package/themes/stranger-things.css +3 -0
  74. package/themes/synthwave.css +3 -0
  75. package/themes/terminator.css +3 -0
  76. package/themes/velvet.css +3 -0
  77. package/themes/yamabuki.css +120 -0
  78. package/tools/chrome.mjs +43 -0
  79. package/tools/gemini-tts.mjs +19 -1
  80. package/tools/lipsync-server.mjs +249 -0
  81. package/tools/lipsync.mjs +166 -0
  82. package/tools/publish-site-voices.mjs +3 -0
  83. package/tools/shot.mjs +85 -0
  84. package/tools/tts-engines.mjs +226 -0
  85. package/tools/visemes.mjs +26 -0
  86. package/tools/voiceover-server.mjs +0 -0
  87. package/tools/voiceover.mjs +51 -34
package/tools/shot.mjs ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // Screenshot a deck — the evidence a reviewer actually looks at.
6
+ //
7
+ // node tools/shot.mjs <deck.html> -o shot.png
8
+ // [--size 1280x720] [--wait 1500] [--theme eclipse]
9
+ // [--slide N] [--drive <file.mjs>] [--keys "g,ArrowRight"]
10
+ //
11
+ // --drive runs a snippet INSIDE the page after Decklight.init, so a feature can
12
+ // be exercised before the shutter: the deck is on `window.__deck`, and `press(k)`
13
+ // dispatches a key exactly as a presenter would. That is the difference between
14
+ // a screenshot of a deck and a screenshot of the THING THE TICKET ASKED FOR.
15
+ //
16
+ // // shots/solo.mjs
17
+ // press('/'); for (const c of 'solo') press(c); await sleep(100); press('Enter');
18
+ //
19
+ // Headless Chrome renders it; no puppeteer, no node_modules, nothing to install
20
+ // that CI does not already have.
21
+
22
+ import { execFileSync } from 'node:child_process';
23
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
24
+ import { dirname, resolve } from 'node:path';
25
+ import { chromeBin, chromeArgs } from './chrome.mjs';
26
+
27
+ const args = process.argv.slice(2);
28
+ const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
29
+ const page = args.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
30
+ if (!page || args.includes('--help')) {
31
+ console.error('usage: shot.mjs <deck.html> -o shot.png [--size 1280x720] [--wait 1500]'
32
+ + ' [--theme name] [--slide N] [--drive file.mjs] [--keys "a,b"]');
33
+ process.exit(page ? 0 : 1);
34
+ }
35
+
36
+
37
+ const out = resolve(opt('-o', 'shot.png'));
38
+ const size = opt('--size', '1280x720');
39
+ const wait = Number(opt('--wait', 1500));
40
+ const theme = opt('--theme');
41
+ const slide = opt('--slide');
42
+ const keys = (opt('--keys') ?? '').split(',').map((k) => k.trim()).filter(Boolean);
43
+ const drive = opt('--drive');
44
+
45
+ // The driver runs in the page, so the shot can show a FEATURE and not just a
46
+ // title card. Injected by writing a sibling copy of the deck — a sibling so that
47
+ // every relative href in it (dist/, themes/, voices/) still resolves.
48
+ const src = resolve(page);
49
+ const driver = drive ? readFileSync(resolve(drive), 'utf8') : '';
50
+ const boot = `
51
+ <script type="module">
52
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
53
+ const press = (k, opts = {}) => document.body.dispatchEvent(
54
+ new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...opts }));
55
+ window.__deck = window.Decklight?.instances?.[0] ?? window.__decklight ?? null;
56
+ ${keys.length ? `for (const k of ${JSON.stringify(keys)}) { press(k); await sleep(120); }` : ''}
57
+ ${driver}
58
+ </script>`;
59
+
60
+ const tmp = src.replace(/\.html?$/i, `.__shot-${process.pid}.html`);
61
+ let html = readFileSync(src, 'utf8');
62
+ if (theme) html = html.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`);
63
+ html = html.replace(/(<\/body>)/i, `${boot}$1`);
64
+ writeFileSync(tmp, html);
65
+
66
+ mkdirSync(dirname(out), { recursive: true });
67
+ try {
68
+ execFileSync(chromeBin('shot'), chromeArgs(
69
+ '--hide-scrollbars',
70
+ '--allow-file-access-from-files',
71
+ '--autoplay-policy=no-user-gesture-required',
72
+ `--window-size=${size.replace('x', ',')}`,
73
+ `--virtual-time-budget=${wait}`,
74
+ `--screenshot=${out}`,
75
+ `file://${tmp}${slide ? `#/${slide}/0` : ''}`,
76
+ ), { stdio: ['ignore', 'ignore', 'ignore'] });
77
+ } finally {
78
+ rmSync(tmp, { force: true });
79
+ }
80
+
81
+ if (!existsSync(out)) {
82
+ console.error('shot: chrome produced no image');
83
+ process.exit(1);
84
+ }
85
+ console.log(`${out} (${(Buffer.byteLength(readFileSync(out)) / 1024).toFixed(0)} KB)`);
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // The voices decklight can speak with. One factory, three engines, one shape:
6
+ //
7
+ // createEngine({ engine, … }) → { name, model, voices, needsProject,
8
+ // synth(text, { voice, style }) → { wav, usage } }
9
+ //
10
+ // gemini — gemini-2.5-{pro,flash}-tts on Vertex AI. Best delivery, and the
11
+ // only engine that takes a STYLE instruction. No free tier, and a
12
+ // fresh project's per-minute quota is small: bursty narration 429s.
13
+ // pro is slow (~20s a sentence); flash is the one to reach for.
14
+ // chirp — Chirp 3: HD on the Cloud Text-to-Speech API. A DIFFERENT API from
15
+ // Vertex, with a permanent free tier (1M chars/month), ~1s a
16
+ // sentence, and — conveniently — the same 30 star-named voices as
17
+ // Gemini, so a deck keeps its voice when it changes engine. Style is
18
+ // ignored: Chirp has no delivery-instruction channel.
19
+ // piper — local neural TTS. Free, offline, unlimited, no credentials. One
20
+ // voice per installed model, so the picker's roster doesn't apply.
21
+ //
22
+ // Cost is always an ESTIMATE from published list prices. Chirp's estimate is
23
+ // the list price *ignoring* the free tier — we cannot see your monthly usage,
24
+ // so the bridge reports characters too, which is what the free tier is
25
+ // denominated in.
26
+
27
+ import { execFileSync, spawn } from 'node:child_process';
28
+ import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
29
+ import { homedir, tmpdir } from 'node:os';
30
+ import { join } from 'node:path';
31
+ import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId } from './gemini-tts.mjs';
32
+
33
+ export const ENGINES = ['gemini', 'chirp', 'piper'];
34
+
35
+ // Chirp 3: HD ships the same roster as Gemini TTS (verified against
36
+ // texttospeech.googleapis.com/v1/voices) — one name, two engines.
37
+ const CHIRP_PRICE_PER_1M = 30.0; // USD, list, after the 1M chars/month free tier
38
+ const chirpVoice = (voice, lang) => `${lang}-Chirp3-HD-${voice}`;
39
+
40
+ function createChirp({ project, lang = 'en-US' }) {
41
+ if (!project) throw new Error('chirp needs a GCP project — pass --project <id> or set GOOGLE_CLOUD_PROJECT');
42
+ if (!validProjectId(project)) throw new Error(`not a GCP project id: ${JSON.stringify(project)}`);
43
+ let token = null;
44
+
45
+ async function call(text, voice) {
46
+ const res = await fetch('https://texttospeech.googleapis.com/v1/text:synthesize', {
47
+ method: 'POST',
48
+ headers: {
49
+ authorization: `Bearer ${token}`,
50
+ 'content-type': 'application/json',
51
+ 'x-goog-user-project': project, // ADC is a user credential — bill/quota the project, not the user
52
+ },
53
+ body: JSON.stringify({
54
+ input: { text },
55
+ voice: { languageCode: lang, name: chirpVoice(voice, lang) },
56
+ audioConfig: { audioEncoding: 'LINEAR16', sampleRateHertz: 24000 },
57
+ }),
58
+ });
59
+ if (!res.ok) { const e = new Error(`${res.status} ${(await res.text()).slice(0, 200)}`); e.status = res.status; throw e; }
60
+ const { audioContent } = await res.json();
61
+ if (!audioContent) throw new Error('no audio in response');
62
+ // LINEAR16 comes back as a complete RIFF/WAVE — no header to bolt on
63
+ return Buffer.from(audioContent, 'base64');
64
+ }
65
+
66
+ return async function synth(text, { voice = 'Alnilam' } = {}) {
67
+ token ??= gcloudToken();
68
+ let lastErr;
69
+ for (let attempt = 0; attempt < 3; attempt++) {
70
+ try {
71
+ return {
72
+ wav: await call(text, voice),
73
+ usage: {
74
+ model: 'chirp3-hd',
75
+ chars: text.length,
76
+ cost: (text.length / 1e6) * CHIRP_PRICE_PER_1M,
77
+ note: `${text.length} chars`,
78
+ },
79
+ };
80
+ } catch (e) {
81
+ lastErr = e;
82
+ if (e.status === 401) { token = gcloudToken(); continue; }
83
+ if (e.status === 429 || e.status >= 500) { await new Promise((ok) => setTimeout(ok, 2000 * (attempt + 1))); continue; }
84
+ break;
85
+ }
86
+ }
87
+ throw lastErr;
88
+ };
89
+ }
90
+
91
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
92
+
93
+ /**
94
+ * Piper, kept RESIDENT.
95
+ *
96
+ * piper reloads its model on every start — ~13s for en_US-ryan-high (116 MB),
97
+ * against ~1.6s of interpreter startup — so a process per sentence would make
98
+ * the offline engine slower than the cloud one and useless for live narration.
99
+ * Held open it pays that once, and a warm sentence costs about twice its own
100
+ * playing time (~4s for 2s of speech on a laptop CPU) — which the player's
101
+ * lookahead buffer covers, since it synthesizes ahead of the playhead.
102
+ *
103
+ * Its stream interface is line-oriented: one line of text in, one WAV out, into
104
+ * a spool dir, in order. So requests are serialized and the next unseen file is
105
+ * ours — which also means the text must be flattened to a single line, or one
106
+ * request would silently become several utterances.
107
+ */
108
+ function createPiper({ voice = 'en_US-ryan-high', dataDir }) {
109
+ try { execFileSync('piper', ['--help'], { stdio: 'ignore' }); }
110
+ catch { throw new Error('piper not found — install with: uv tool install piper-tts'); }
111
+ // A bare model NAME only resolves against a data dir — without one, piper
112
+ // searches its own default and calls the voice missing even when it is
113
+ // sitting right there. A model PATH needs no dir at all.
114
+ const models = dataDir ?? join(homedir(), '.local', 'share', 'piper');
115
+ const byPath = voice.includes('/') || voice.endsWith('.onnx');
116
+
117
+ let proc = null, spool = null, seen = null;
118
+ let fatal = null; // a config error (missing voice) — retrying cannot fix it
119
+ let chain = Promise.resolve();
120
+
121
+ function ensure() {
122
+ if (proc) return;
123
+ if (fatal) throw new Error(fatal);
124
+ spool = mkdtempSync(join(tmpdir(), 'decklight-piper-'));
125
+ seen = new Set();
126
+ const p = spawn('piper', [
127
+ '-m', voice, ...(byPath ? [] : ['--data-dir', models]),
128
+ '-d', spool, '--output-dir-naming', 'timestamp',
129
+ ], { stdio: ['pipe', 'ignore', 'pipe'] });
130
+ let err = '';
131
+ p.stderr.on('data', (b) => { err = (err + b).slice(-4000); });
132
+ p.on('exit', (code) => {
133
+ if (proc === p) proc = null;
134
+ rmSync(spool, { recursive: true, force: true });
135
+ if (/Unable to find voice/.test(err)) {
136
+ fatal = `piper voice '${voice}' not in ${models} — fetch it with: `
137
+ + `python -m piper.download_voices ${voice} --data-dir ${models}`;
138
+ } else if (code) {
139
+ // a crash is not necessarily terminal: the next call respawns
140
+ lastExit = `piper exited (${code}) ${err.trim().split('\n').pop() ?? ''}`.trim();
141
+ }
142
+ });
143
+ proc = p;
144
+ }
145
+ let lastExit = null;
146
+
147
+ // A WAV is complete when the RIFF header's declared length matches the bytes
148
+ // on disk — piper patches that length when it closes the file. That is an
149
+ // exact signal; "the size stopped changing" is not, since a write can simply
150
+ // stall, and half a WAV is a corrupt WAV. (Belt and braces: if some build
151
+ // never patched the header, fall back to a file that has not grown for ~1s.)
152
+ const complete = (b) => b.length > 44 && b.readUInt32LE(4) + 8 === b.length;
153
+
154
+ async function nextWav(timeoutMs = 180_000) {
155
+ const t0 = Date.now();
156
+ while (Date.now() - t0 < timeoutMs) {
157
+ if (!proc) throw new Error(fatal ?? lastExit ?? 'piper stopped');
158
+ // one line in → one file out, in order, and we serialize: the next file
159
+ // we have not seen is this request's
160
+ const [name] = readdirSync(spool).filter((f) => f.endsWith('.wav') && !seen.has(f));
161
+ if (name) {
162
+ const f = join(spool, name);
163
+ let last = -1, still = 0;
164
+ for (;;) {
165
+ const b = readFileSync(f);
166
+ if (complete(b)) { seen.add(name); rmSync(f, { force: true }); return b; }
167
+ still = b.length === last ? still + 1 : 0;
168
+ last = b.length;
169
+ if (still >= 12 && b.length > 44) { seen.add(name); rmSync(f, { force: true }); return b; }
170
+ await sleep(80);
171
+ }
172
+ }
173
+ await sleep(40);
174
+ }
175
+ throw new Error('piper timed out');
176
+ }
177
+
178
+ function synth(text) {
179
+ const line = String(text).replace(/\s+/g, ' ').trim(); // one utterance, one line
180
+ chain = chain.catch(() => {}).then(async () => {
181
+ ensure();
182
+ proc.stdin.write(`${line}\n`);
183
+ return {
184
+ wav: await nextWav(),
185
+ usage: { model: voice, chars: line.length, cost: 0, note: `${line.length} chars · local` },
186
+ };
187
+ });
188
+ return chain;
189
+ }
190
+ // Start the model loading NOW rather than on the first sentence — otherwise
191
+ // the presenter's first keypress pays the whole ~13s load, which reads as a
192
+ // hung deck. By the time anyone has opened a slide, piper is warm.
193
+ synth.warm = () => { try { ensure(); } catch { /* reported at synth time */ } };
194
+ return synth;
195
+ }
196
+
197
+ /**
198
+ * One engine, one shape. `voices` is what the player should offer: the star
199
+ * roster for the cloud engines, and for piper the single installed model —
200
+ * offering 30 Gemini names it cannot speak would just be a lie.
201
+ */
202
+ export function createEngine({ engine = 'gemini', project, model, location, voice, dataDir, lang } = {}) {
203
+ if (!ENGINES.includes(engine)) throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')}`);
204
+
205
+ if (engine === 'piper') {
206
+ const m = voice ?? 'en_US-ryan-high';
207
+ return {
208
+ name: 'piper', model: m, needsProject: false, stylable: false,
209
+ voices: [[m, 'local']],
210
+ synth: createPiper({ voice: m, dataDir }),
211
+ };
212
+ }
213
+ if (engine === 'chirp') {
214
+ return {
215
+ name: 'chirp', model: 'chirp3-hd', needsProject: true, stylable: false,
216
+ voices: GEMINI_VOICES,
217
+ synth: createChirp({ project, lang: lang ?? 'en-US' }),
218
+ };
219
+ }
220
+ const m = model ?? 'gemini-2.5-pro-tts';
221
+ return {
222
+ name: 'gemini', model: m, needsProject: true, stylable: true,
223
+ voices: GEMINI_VOICES,
224
+ synth: createGemini({ project, ttsModel: m, location }),
225
+ };
226
+ }
@@ -0,0 +1,26 @@
1
+ // Shared viseme-timeline format (v1) — the contract between the lipsync
2
+ // bridge (tools/lipsync-server.mjs), the batch tool (tools/lipsync.mjs) and
3
+ // the player's character overlay:
4
+ //
5
+ // { v: 1, kind: 'visemes', duration: 7.42, source: 'rhubarb',
6
+ // cues: [ { t: 0.00, v: 'X' }, { t: 0.31, v: 'B' }, … ] }
7
+ //
8
+ // Cues carry START times only — each shape holds until the next cue, the
9
+ // last until `duration`. That is lossless versus Rhubarb's contiguous
10
+ // { start, end, value } runs and half the size on disk.
11
+
12
+ const r3 = (x) => Math.round(x * 1000) / 1000;
13
+
14
+ // Rhubarb `-f json` output → timeline v1. Collapses consecutive duplicate
15
+ // shapes (Rhubarb emits them across word boundaries).
16
+ export function normalizeRhubarb(rh) {
17
+ const cues = [];
18
+ let end = 0;
19
+ for (const c of rh?.mouthCues ?? []) {
20
+ const v = String(c.value ?? 'X').toUpperCase();
21
+ end = Math.max(end, c.end ?? 0);
22
+ if (cues.length && cues[cues.length - 1].v === v) continue;
23
+ cues.push({ t: r3(c.start ?? 0), v });
24
+ }
25
+ return { v: 1, kind: 'visemes', duration: r3(rh?.metadata?.duration ?? end), source: 'rhubarb', cues };
26
+ }
Binary file
@@ -1,23 +1,31 @@
1
1
  #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
2
5
  // Voice-over generator: per-slide narration audio from a deck's speaker notes.
3
6
  //
4
- // node tools/voiceover.mjs <deck.html> [-o <dir>] [--engine piper|gemini]
7
+ // node tools/voiceover.mjs <deck.html> [-o <dir>] [--engine piper|chirp|gemini]
5
8
  // [--voice <name>] [--data-dir <dir>]
6
- // [--project <id>] [--location global]
9
+ // [--project <id>] [--location global] [--lang en-US]
7
10
  // [--tts-model gemini-2.5-pro-tts]
8
11
  // [--model qwen3:30b-a3b] [--no-llm] [--reuse-text]
12
+ // [--keep-wav] (keep the lossless intermediates —
13
+ // tools/lipsync.mjs consumes them)
9
14
  //
10
- // Engines (the built-in macOS voices were dropped: not good enough):
11
- // piper — neural local TTS, fully offline. --voice takes a piper model
12
- // name (default en_US-ryan-high, a natural US male). Install:
15
+ // Engines (tools/tts-engines.mjs — the same three the live bridge speaks with;
16
+ // the built-in macOS voices were dropped: not good enough):
17
+ // piper — neural local TTS, fully offline, unlimited, free. --voice takes a
18
+ // piper model name (default en_US-ryan-high, a natural US male):
13
19
  // uv tool install piper-tts
14
20
  // python -m piper.download_voices en_US-ryan-high (in --data-dir)
15
- // gemini — gemini-2.5-pro-tts on Vertex AI. Set the GCP project with
16
- // --project or $GOOGLE_CLOUD_PROJECT. --voice takes a prebuilt voice name (default Alnilam;
17
- // also Charon, Puck, Fenrir, Iapetus, Kore…). --style sets the
18
- // delivery instruction prepended to every slide (default: warm,
19
- // welcoming battle-hardened senior engineer).
20
- // Auth: gcloud auth application-default login.
21
+ // chirp — Chirp 3: HD on the Cloud Text-to-Speech API. Same 30 star-named
22
+ // voices as gemini, ~1s a sentence, and 1M characters a month free.
23
+ // No --style: Chirp has no delivery-instruction channel.
24
+ // gemini — gemini-2.5-{pro,flash}-tts on Vertex AI. The only engine that
25
+ // honors --style (default: warm, welcoming battle-hardened senior
26
+ // engineer). No free tier, and pro is slow.
27
+ // Cloud engines: --project or $GOOGLE_CLOUD_PROJECT, auth via
28
+ // gcloud auth application-default login.
21
29
  //
22
30
  // Pipeline: extract each slide's notes (HTML asides or markdown Note: blocks,
23
31
  // ⟨CLICK⟩ markers removed) → optionally rewrite into flowing narration with a
@@ -31,7 +39,7 @@ import { createHash } from 'node:crypto';
31
39
  import { execFileSync } from 'node:child_process';
32
40
  import { resolve, join, basename } from 'node:path';
33
41
  import { homedir } from 'node:os';
34
- import { createSynth } from './gemini-tts.mjs';
42
+ import { createEngine } from './tts-engines.mjs';
35
43
 
36
44
  const args = process.argv.slice(2);
37
45
  const deckPath = args.find((a) => !a.startsWith('-'));
@@ -39,7 +47,7 @@ if (!deckPath) { console.error('usage: voiceover.mjs <deck.html> [-o dir] [--eng
39
47
  const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
40
48
  const outDir = resolve(opt('-o', join(resolve(deckPath, '..'), 'voiceover')));
41
49
  const engine = opt('--engine', 'piper');
42
- const voice = opt('--voice', engine === 'gemini' ? 'Alnilam' : 'en_US-ryan-high');
50
+ const voice = opt('--voice', engine === 'piper' ? 'en_US-ryan-high' : 'Alnilam');
43
51
  const style = opt('--style',
44
52
  'Read in a warm, welcoming tone, like a friendly battle-hardened senior ' +
45
53
  'engineer who is still curious about new technology.');
@@ -48,20 +56,34 @@ const project = opt('--project', process.env.GOOGLE_CLOUD_PROJECT);
48
56
  const model = opt('--model', 'qwen3:30b-a3b');
49
57
  const useLlm = !args.includes('--no-llm');
50
58
  const reuseText = args.includes('--reuse-text');
51
- if (engine === 'gemini' && !project) {
52
- console.error('gemini engine needs a GCP project — pass --project <id> or set GOOGLE_CLOUD_PROJECT'); process.exit(1);
59
+ const keepWav = args.includes('--keep-wav');
60
+
61
+ // one factory, three engines — the same ones the live bridge speaks with
62
+ let tts;
63
+ try {
64
+ tts = createEngine({
65
+ engine, project, voice, dataDir,
66
+ model: opt('--tts-model'), location: opt('--location'), lang: opt('--lang'),
67
+ });
68
+ } catch (e) {
69
+ console.error(e.message);
70
+ process.exit(1);
53
71
  }
54
- const synthGemini = engine === 'gemini'
55
- ? createSynth({ project, ttsModel: opt('--tts-model'), location: opt('--location') })
56
- : null;
57
72
 
58
- if (engine === 'piper') {
59
- try { execFileSync('piper', ['--help'], { stdio: 'ignore' }); }
60
- catch { console.error('piper not found — install with: uv tool install piper-tts'); process.exit(1); }
61
- } else if (engine !== 'gemini') {
62
- console.error(`unknown engine '${engine}' — use piper or gemini`);
73
+ // WAV → AAC. ffmpeg everywhere; afconvert is Core Audio, so it only exists on
74
+ // macOS — probing in that order keeps this working off a Mac (as tools/lipsync.mjs
75
+ // already does), and both engines' output goes through here.
76
+ const have = (bin, flags = ['-version']) => {
77
+ try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
78
+ };
79
+ const encoder = have('ffmpeg') ? 'ffmpeg' : have('afconvert') ? 'afconvert' : null;
80
+ if (!encoder) {
81
+ console.error('no AAC encoder — install ffmpeg (apt install ffmpeg / brew install ffmpeg)');
63
82
  process.exit(1);
64
83
  }
84
+ const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
85
+ ? ['-y', '-i', wav, '-c:a', 'aac', '-b:a', '128k', m4a]
86
+ : ['-f', 'm4af', '-d', 'aac', wav, m4a], { stdio: 'ignore' });
65
87
 
66
88
  // ── extract per-slide narration text ─────────────────────────────────────────
67
89
  const html = readFileSync(deckPath, 'utf8');
@@ -132,17 +154,12 @@ for (let i = 0; i < slides.length; i++) {
132
154
  console.log(` slide ${n}: unchanged — kept`);
133
155
  continue;
134
156
  }
135
- let costNote = '';
136
- if (engine === 'gemini') {
137
- const { wav: buf, usage } = await synthGemini(text, { voice, style });
138
- writeFileSync(wav, buf);
139
- totalCost += usage.cost;
140
- costNote = ` · ~$${usage.cost.toFixed(4)}`;
141
- } else {
142
- execFileSync('piper', ['-m', voice, '--data-dir', dataDir, '-f', wav], { input: text });
143
- }
144
- execFileSync('afconvert', ['-f', 'm4af', '-d', 'aac', wav, m4a]);
145
- rmSync(wav);
157
+ const { wav: buf, usage } = await tts.synth(text, { voice, style });
158
+ writeFileSync(wav, buf);
159
+ totalCost += usage.cost;
160
+ const costNote = usage.cost ? ` · ~$${usage.cost.toFixed(4)}` : '';
161
+ toAac(wav, m4a);
162
+ if (!keepWav) rmSync(wav);
146
163
  console.log(` slide ${n}: ${text.length} chars → ${basename(m4a)}${costNote}`);
147
164
  // crash-safe: persist progress after every slide so an interrupted run
148
165
  // resumes incrementally instead of re-synthesizing everything