decklight 0.5.0 → 0.7.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 (53) hide show
  1. package/README.md +20 -9
  2. package/SPEC.md +239 -17
  3. package/cli/agents.mjs +97 -2
  4. package/cli/banner.mjs +125 -0
  5. package/cli/bundle.mjs +14 -4
  6. package/cli/{rec.mjs → cast.mjs} +25 -8
  7. package/cli/comments.mjs +389 -0
  8. package/cli/commit-flow.mjs +157 -0
  9. package/cli/commit-message.mjs +475 -0
  10. package/cli/decklight.mjs +95 -25
  11. package/cli/dev.mjs +193 -25
  12. package/cli/edit.mjs +1055 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +370 -0
  15. package/cli/history.mjs +145 -0
  16. package/cli/init.mjs +199 -7
  17. package/cli/marketplace.mjs +123 -17
  18. package/cli/port-conflict.mjs +228 -22
  19. package/cli/present.mjs +297 -12
  20. package/cli/publish.mjs +15 -40
  21. package/cli/record.mjs +154 -0
  22. package/cli/restore.mjs +120 -4
  23. package/cli/review-remote.mjs +330 -0
  24. package/cli/review-store.mjs +107 -0
  25. package/cli/review-submit.mjs +292 -0
  26. package/cli/review.mjs +361 -0
  27. package/cli/serve.mjs +60 -1
  28. package/cli/skill-content.mjs +12 -1
  29. package/cli/theme.mjs +78 -11
  30. package/cli/units.mjs +2 -2
  31. package/cli/upstream.mjs +256 -0
  32. package/cli/util.mjs +59 -0
  33. package/dist/build-info.json +1 -0
  34. package/dist/decklight.css +534 -3
  35. package/dist/decklight.js +102 -76
  36. package/dist/decklight.js.map +4 -4
  37. package/docs/architecture.svg +7 -0
  38. package/package.json +2 -1
  39. package/tools/args.mjs +20 -0
  40. package/tools/deck-html.mjs +84 -0
  41. package/tools/elevenlabs-tts.mjs +1 -1
  42. package/tools/lipsync-server.mjs +64 -2
  43. package/tools/lipsync.mjs +40 -24
  44. package/tools/local-voice.mjs +170 -16
  45. package/tools/publish-voices.mjs +78 -18
  46. package/tools/recording-impact.mjs +110 -0
  47. package/tools/review-anchor.mjs +180 -0
  48. package/tools/test-impact.mjs +259 -0
  49. package/tools/tts-engines.mjs +211 -12
  50. package/tools/tts-setup.mjs +2 -9
  51. package/tools/video.mjs +56 -12
  52. package/tools/voiceover-server.mjs +262 -11
  53. package/tools/voiceover.mjs +32 -13
package/tools/video.mjs CHANGED
@@ -56,7 +56,10 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
56
56
  --size <WxH> frame size (default 1280x720; both must be even)
57
57
  --fps <n> video frame rate (default 30)
58
58
  --hold <s> seconds a slide without narration holds (default 5;
59
- per-slide override: data-video-hold="8" on the section)
59
+ per-slide override: data-video-hold="8" on the section).
60
+ A NARRATED slide holds for its audio instead — give that
61
+ one a beat with data-narration-pause="2", the same
62
+ attribute the live deck pauses on
60
63
  --build-hold <s> seconds each build-up frame holds on a silent slide
61
64
  (default: the slide's own hold, so builds move at the
62
65
  pace the deck does)
@@ -69,7 +72,9 @@ its own audio: ⟨CLICK⟩ in the speaker notes splits the narration, and segmen
69
72
  is spoken over build step k — the same rule the live player follows. Without
70
73
  markers it holds fully built for the audio's real duration. A silent slide holds
71
74
  --hold seconds, --build-hold per step. Either way the audio track is continuous
72
- and the finished slide gets a ${TAIL_SECONDS}s breath before the cut.
75
+ and the finished slide gets a ${TAIL_SECONDS}s breath before the cut — plus
76
+ whatever data-narration-pause="2" asks for, so the mp4 breathes where the
77
+ live deck does.
73
78
  Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
74
79
  `;
75
80
 
@@ -103,6 +108,35 @@ export function extractHolds(html, defaultHold) {
103
108
  });
104
109
  }
105
110
 
111
+ /**
112
+ * The runtime's built-in hold before a slide turns (SLIDE_PAUSE_S in
113
+ * src/core/narration.js — not imported, because src/ does not ship in the
114
+ * package; test/video.test.mjs pins the two equal). An exported mp4 must
115
+ * breathe where the live deck does, and the live deck now breathes here by
116
+ * default.
117
+ */
118
+ export const SLIDE_PAUSE_DEFAULT = 1;
119
+
120
+ /**
121
+ * Per-slide narration beat: data-narration-pause="2" on the section, else
122
+ * the built-in default above.
123
+ *
124
+ * The recorded mirror of the live rule (PRESENTING): src/core/narration.js
125
+ * holds that many seconds after a slide's last sentence before moving on, and
126
+ * an exported mp4 must breathe in the same places the deck does. Read off the
127
+ * raw open tag, like extractHolds, so the same attribute appearing in a
128
+ * slide's CONTENT cannot be mistaken for the slide's own. (The deck-wide
129
+ * `narration.slidePause` config tier is not read here: it lives inside the
130
+ * boot call, and this reads sections, not scripts.)
131
+ */
132
+ export function extractPauses(html) {
133
+ return sectionBodies(html).map((sec) => {
134
+ const tag = sec.slice(0, sec.indexOf('>'));
135
+ const m = tag.match(/data-narration-pause="([\d.]+)"/);
136
+ return m ? Number(m[1]) : SLIDE_PAUSE_DEFAULT;
137
+ });
138
+ }
139
+
106
140
  /**
107
141
  * An oversized step: the engine clamps it to the slide's last build, so this
108
142
  * always renders a slide fully built however many steps it turns out to have.
@@ -145,10 +179,13 @@ const round = (s) => Math.round(s * 1000) / 1000;
145
179
  * @param {{from,to}} [range] 1-based inclusive slide range
146
180
  * @param {object} [opts] steps: per-slide build-step counts (null ⇒ one
147
181
  * frame per slide); buildHold: seconds per
148
- * build-up frame (null ⇒ the slide's own hold)
149
- * @returns {Array<{slide, step, audio, duration}>} audio null ⇒ silent hold
182
+ * build-up frame (null ⇒ the slide's own hold);
183
+ * pauses: per-slide data-narration-pause seconds
184
+ * added to a NARRATED slide's finished frame
185
+ * @returns {Array<{slide, step, audio, duration, pad}>} audio null ⇒ silent hold;
186
+ * `pad` is the silence ffmpeg appends to the audio
150
187
  */
151
- export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, onWarn = null } = {}) {
188
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, pauses = null, onWarn = null } = {}) {
152
189
  const from = range?.from ?? 1;
153
190
  const to = range?.to ?? holds.length;
154
191
  const plan = [];
@@ -165,6 +202,10 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
165
202
  // segmentation. This makes the recorded render the mirror of it.
166
203
  const segs = entry?.segments ?? null;
167
204
  const builds = steps?.[n - 1] ?? 0;
205
+ // The slide's own beat rides on the tail of its finished frame — the one
206
+ // place the live deck pauses too. A silent slide has no narration to pause
207
+ // after; --hold and data-video-hold are its knobs.
208
+ const tail = TAIL_SECONDS + (pauses?.[n - 1] ?? 0);
168
209
  if (Number.isFinite(dur) && segs?.length && builds) {
169
210
  const times = segs.map((sg) => durations?.[sg.file]);
170
211
  if (segs.length === builds + 1 && times.every((t) => Number.isFinite(t))) {
@@ -176,7 +217,8 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
176
217
  audio: sg.file,
177
218
  // Only the finished slide gets the breath. A build that paused for
178
219
  // it would read as hesitation rather than as a beat.
179
- duration: round(times[k] + (last ? TAIL_SECONDS : 0)),
220
+ duration: round(times[k] + (last ? tail : 0)),
221
+ pad: last ? tail : 0,
180
222
  });
181
223
  });
182
224
  continue;
@@ -191,7 +233,7 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
191
233
  }
192
234
 
193
235
  if (Number.isFinite(dur)) {
194
- plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + TAIL_SECONDS) });
236
+ plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + tail), pad: tail });
195
237
  continue;
196
238
  }
197
239
  const hold = holds[n - 1];
@@ -205,17 +247,18 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
205
247
 
206
248
  /**
207
249
  * ffmpeg argv for one slide's segment: the still looped at --fps under its
208
- * audio. Narrated slides pad the audio with the tail and stop there; silent
250
+ * audio. Narrated slides pad the audio with `pad` — the tail, plus whatever
251
+ * beat the slide asked for (`data-narration-pause`) — and stop there; silent
209
252
  * slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
210
253
  * carries an audio stream and the concat-demuxer's `-c copy` audio track never
211
254
  * goes discontinuous. -t bounds both the infinite loop and the infinite
212
255
  * anullsrc (-shortest can't end a segment whose streams are both endless).
213
256
  */
214
- export function segmentArgs({ frame, audio, duration, fps, out }) {
257
+ export function segmentArgs({ frame, audio, duration, fps, out, pad = TAIL_SECONDS }) {
215
258
  return [
216
259
  '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
217
260
  ...(audio
218
- ? ['-i', audio, '-af', `apad=pad_dur=${TAIL_SECONDS}`]
261
+ ? ['-i', audio, '-af', `apad=pad_dur=${pad}`]
219
262
  : ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
220
263
  '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
221
264
  '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
@@ -363,6 +406,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
363
406
 
364
407
  const html = readFileSync(deck, 'utf8');
365
408
  const holds = extractHolds(html, hold);
409
+ const pauses = extractPauses(html);
366
410
  if (!holds.length) throw new Error(`${basename(deck)} has no <section> slides`);
367
411
  const range = parseSlideRange(opt('--slides'), holds.length);
368
412
 
@@ -434,7 +478,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
434
478
  if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
435
479
 
436
480
  plan = planTimeline(narration?.slides ?? null, durations, holds, range,
437
- { steps, buildHold, onWarn: (w) => console.warn(` ${w}`) });
481
+ { steps, buildHold, pauses, onWarn: (w) => console.warn(` ${w}`) });
438
482
  const slideCount = new Set(plan.map((p) => p.slide)).size;
439
483
  log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
440
484
  + `${plan.filter((p) => p.audio).length} narrated`
@@ -459,7 +503,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
459
503
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
460
504
  const seg = join(work, `seg-${id}.mp4`);
461
505
  await exec('ffmpeg', segmentArgs({
462
- frame, duration: p.duration, fps, out: seg,
506
+ frame, duration: p.duration, pad: p.pad, fps, out: seg,
463
507
  audio: p.audio ? join(narration.dir, p.audio) : null,
464
508
  }));
465
509
  segments.push(seg);
@@ -36,13 +36,64 @@
36
36
  // stepping back through slides replays instantly and costs nothing.
37
37
 
38
38
  import { createServer } from 'node:http';
39
- import { createHash } from 'node:crypto';
40
39
  import { createInterface } from 'node:readline/promises';
41
- import { resolveEngine, ENGINES } from './tts-engines.mjs';
40
+ import { canBind, resolvePortConflict } from '../cli/port-conflict.mjs';
41
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
42
+ import { homedir } from 'node:os';
43
+ import { join } from 'node:path';
44
+ import { execFile } from 'node:child_process';
45
+
46
+ /**
47
+ * The one exec a deck may trigger: open macOS's voice-download pane.
48
+ *
49
+ * The argv is a FROZEN CONSTANT — no byte of any request reaches it — and it
50
+ * opens a System Settings pane and nothing else; the download itself stays a
51
+ * human clicking through, which is the point of the pane. `exec` is injected
52
+ * so the test can assert the argv without a Settings window opening mid-suite.
53
+ */
54
+ export const VOICE_SETTINGS_URI = 'x-apple.systempreferences:com.apple.preference.universalaccess';
55
+ /** …and Windows' Narrator page, where "Add natural voices" lives. */
56
+ export const WINDOWS_VOICE_SETTINGS_URI = 'ms-settings:easeofaccess-narrator';
57
+ export function openVoiceSettings(exec = execFile, platform = process.platform) {
58
+ if (platform === 'win32') {
59
+ // `start` is a cmd builtin; the empty "" is its title argument, so the
60
+ // URI is never mistaken for one. Every token is a constant.
61
+ exec('cmd', ['/c', 'start', '""', WINDOWS_VOICE_SETTINGS_URI], () => { /* fire and forget */ });
62
+ return;
63
+ }
64
+ exec('open', [VOICE_SETTINGS_URI], () => { /* fire and forget — Settings owns the rest */ });
65
+ }
66
+ import { createHash } from 'node:crypto';
67
+ import { resolveEngine, engineBlocker, engineMenu, engineStatus, ENGINES } from './tts-engines.mjs';
42
68
  import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
43
69
  import { argReader, isMain } from './args.mjs';
44
70
  import { corsHeaders, readBody } from './bridge.mjs';
45
71
  import { installedVoices } from '../cli/units.mjs';
72
+ import { readyLine } from '../cli/banner.mjs';
73
+
74
+ /** One line from the terminal, for the taken-port question. Closed straight after. */
75
+ async function askLine(prompt) {
76
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
77
+ // EOF ANSWERS THE SAFE WAY. `rl.question` never settles if the input closes
78
+ // first (a Ctrl-D, a terminal whose stdin is a spent pipe), and an unsettled
79
+ // promise here aborted the bridge through the top-level handler — reported to
80
+ // the user as "this one is a bug, please report it", over a question about a
81
+ // port. An empty answer is the declining answer everywhere it is read.
82
+ try {
83
+ return await new Promise((resolve) => {
84
+ // `line` is registered FIRST and readline emits it before `close`, so a
85
+ // key that was actually typed always beats the EOF that follows it. The
86
+ // two racing as promises did not: a piped `k\n` lost to the close and
87
+ // read as a decline, which is a terrible way to lose a keystroke.
88
+ let answered = false;
89
+ const done = (v) => { if (!answered) { answered = true; resolve(v); } };
90
+ rl.once('line', done);
91
+ rl.once('close', () => done(''));
92
+ rl.setPrompt(prompt);
93
+ rl.prompt();
94
+ });
95
+ } finally { rl.close(); }
96
+ }
46
97
 
47
98
  export async function ttsMain(args) {
48
99
  if (args.includes('--help')) {
@@ -144,16 +195,79 @@ export async function ttsMain(args) {
144
195
  // made the name offerable, rather than in each engine — an engine that had to
145
196
  // know about the unit library would be an engine that could no longer be
146
197
  // 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)`);
198
+ // Everything derived from the live engine, recomputed together — because the
199
+ // deck can now change which engine that is (SPEC `NARRATION`), and a roster
200
+ // or an id map left behind from the previous one would offer voices the
201
+ // current engine cannot say.
202
+ let refs = [];
203
+ let refIds = new Map();
204
+ const useEngine = (e) => {
205
+ engine = e;
206
+ refs = installedVoices(e.name);
207
+ refIds = new Map(refs.map((r) => [r.label, r.voiceId]));
208
+ if (refs.length) console.log(` voices: +${refs.length} installed (decklight voice list)`);
209
+ };
210
+ useEngine(engine);
150
211
 
151
212
  const voiceRoster = async () => [
152
213
  ...(engine.listVoices ? (await engine.listVoices()).map((v) => [v.name, v.flavor]) : engine.voices),
153
214
  ...refs.map((r) => [r.label, r.marketplace ?? 'installed']),
154
215
  ];
155
216
 
217
+ // The engine's NAME is part of every cache key, so a swap cannot serve one
218
+ // engine's audio under another's voice — the cache survives the switch, and
219
+ // switching back replays instantly rather than re-billing.
156
220
  const cache = new Map();
221
+ // The DISK half of the cache, for the engines whose synthesis is free and
222
+ // local (say, sapi, piper): a machine's own voice saying the same sentence
223
+ // is the same audio tomorrow, and a voice's identity — its name, which is
224
+ // exactly what `say -v` selects by — is stable per machine. Warming 184
225
+ // previews took ~6 minutes of background `say`; it should cost that once
226
+ // per machine, not once per bridge. Cloud engines stay memory-only: their
227
+ // output drifts with server models, and a stale clip that sounds unlike
228
+ // today's voice is worse than a re-bill of one preview sentence.
229
+ const DISK_CACHED = new Set(['say', 'sapi', 'piper']);
230
+ const cacheDir = join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'decklight', 'tts');
231
+ const diskPath = (key) => join(cacheDir, `${key}.wav`);
232
+ const diskRead = (key) => {
233
+ if (!DISK_CACHED.has(engine.name)) return null;
234
+ try {
235
+ const wav = readFileSync(diskPath(key));
236
+ return { wav, usage: { chars: 0, cost: 0, note: 'cached on disk' } };
237
+ } catch { return null; }
238
+ };
239
+ const diskWrite = (key, wav) => {
240
+ if (!DISK_CACHED.has(engine.name)) return;
241
+ try { mkdirSync(cacheDir, { recursive: true }); writeFileSync(diskPath(key), wav); }
242
+ catch { /* a cache that cannot write is a cache, not a failure */ }
243
+ };
244
+ // Bounded at startup, oldest first: a per-sentence cache grows forever and
245
+ // a silent 10 GB in ~/.cache is not a cache, it is a leak with a euphemism.
246
+ try {
247
+ const entries = readdirSync(cacheDir)
248
+ .filter((f) => f.endsWith('.wav'))
249
+ .map((f) => ({ f, ...statSync(join(cacheDir, f)) }))
250
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
251
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
252
+ for (const e of entries) {
253
+ if (total <= 400 * 1024 * 1024) break;
254
+ try { unlinkSync(join(cacheDir, e.f)); total -= e.size; } catch { break; }
255
+ }
256
+ } catch { /* no cache dir yet */ }
257
+
258
+ // What the bridge could become, and what stands in the way. The options the
259
+ // deck's picker draws (SPEC `NARRATION`).
260
+ //
261
+ // The blockers are all fixed in a TERMINAL and this route never collects
262
+ // one: a key or a project id typed into a web page — even one on loopback —
263
+ // is a different thing from one exported in a shell, and a deck under
264
+ // `--remote` is reachable from a phone. So the deck lists what is missing and
265
+ // says where to fix it; it never becomes the place you configure credentials.
266
+ const menuOpts = () => ({
267
+ env: process.env,
268
+ project: opt('--project') ?? process.env.GOOGLE_CLOUD_PROJECT ?? saved?.project,
269
+ voice: opt('--voice'), dataDir: opt('--data-dir'), lang: opt('--lang'),
270
+ });
157
271
 
158
272
  // the player reads the cost estimate for its debug window
159
273
  const CORS = corsHeaders('x-tts-cost, x-tts-tokens, x-tts-cached');
@@ -175,9 +289,95 @@ export async function ttsMain(args) {
175
289
  engine: engine.name,
176
290
  model: engine.model,
177
291
  stylable: engine.stylable, // gemini alone can be told HOW to say it
292
+ // the engine's standing note — for `say` with no Siri voice this is
293
+ // the download hint, and the picker keys its install row off it
294
+ ...(engine.caveat ? { caveat: engine.caveat } : {}),
178
295
  voices, // piper speaks one voice, not the star roster
179
296
  }));
180
297
  }
298
+ // ── the one exec a deck may trigger: open the voice-download pane ──
299
+ // Darwin only, loopback only (like every route here), and the argv is a
300
+ // FROZEN CONSTANT — no byte of the request reaches it. It opens a System
301
+ // Settings pane and does nothing else; the download itself stays a human
302
+ // clicking, which is the whole point of the pane.
303
+ if (req.method === 'POST' && req.url === '/voices/install') {
304
+ if (process.platform !== 'darwin' && process.platform !== 'win32') { res.writeHead(404); return res.end(); }
305
+ try {
306
+ openVoiceSettings();
307
+ console.log(process.platform === 'win32'
308
+ ? ' voices: opened Settings → Accessibility → Narrator (add natural voices, then restart me)'
309
+ : ' voices: opened System Settings → Accessibility (download a Siri voice, then restart me)');
310
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
311
+ return res.end(JSON.stringify({ ok: true }));
312
+ } catch (e) {
313
+ res.writeHead(500, { ...CORS, 'content-type': 'application/json' });
314
+ return res.end(JSON.stringify({ ok: false, error: String(e?.message ?? e) }));
315
+ }
316
+ }
317
+ // ── which engine is speaking, and what else could (SPEC `NARRATION`) ──
318
+ if (req.method === 'GET' && req.url === '/engines') {
319
+ // Ready or not, every engine is listed. Hiding the ones this machine
320
+ // cannot use would answer "where did ElevenLabs go?" with silence — the
321
+ // useful answer is that it is there and needs a key.
322
+ const opts = menuOpts();
323
+ const menu = engineMenu(opts).map((e) => ({ ...e, current: e.name === engine.name }));
324
+ // An engine the bridge was STARTED with is ready by definition — it is
325
+ // speaking. Detection can disagree (a marketplace engine is not one of
326
+ // the six, and a project passed by flag is invisible to a later probe),
327
+ // and a picker that greyed out the running engine would be absurd.
328
+ if (!menu.some((e) => e.current)) {
329
+ menu.unshift({ name: engine.name, ready: true, reason: 'ok', current: true, cost: engine.cost });
330
+ }
331
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
332
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, engines: menu }));
333
+ }
334
+ if (req.method === 'POST' && req.url === '/engine') {
335
+ let name;
336
+ try { ({ engine: name } = JSON.parse((await readBody(req)).toString())); }
337
+ catch { name = null; }
338
+ if (typeof name !== 'string' || !name) {
339
+ res.writeHead(400, { ...CORS, 'content-type': 'application/json' });
340
+ return res.end(JSON.stringify({ ok: false, error: 'name the engine' }));
341
+ }
342
+ if (name === engine.name) {
343
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
344
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, model: engine.model,
345
+ stylable: engine.stylable, voices: await voiceRoster().catch(() => []), changed: false }));
346
+ }
347
+ const opts = menuOpts();
348
+ // Checked BEFORE building, because two of the six build perfectly well
349
+ // and only fail on the first sentence — which mid-talk is a keypress into
350
+ // silence. A refusal here is recoverable; that one is not.
351
+ const status = engineStatus(name, opts);
352
+ if (ENGINES.includes(name) && !status.ready) {
353
+ // The blocker travels WITH the refusal. The deck's picker normally has
354
+ // it already (it came down with /engines), but a menu can be a minute
355
+ // stale — a key exported and un-exported, a model deleted — and a
356
+ // refusal the deck cannot put words to is a row that does nothing when
357
+ // clicked.
358
+ res.writeHead(409, { ...CORS, 'content-type': 'application/json' });
359
+ return res.end(JSON.stringify({
360
+ ok: false, error: status.reason, ...status, ...(engineBlocker(status, opts) ?? {}),
361
+ }));
362
+ }
363
+ let next;
364
+ try {
365
+ next = await resolveEngine({ ...opts, engine: name, model: undefined });
366
+ } catch (e) {
367
+ res.writeHead(409, { ...CORS, 'content-type': 'application/json' });
368
+ return res.end(JSON.stringify({ ok: false, error: String(e.message ?? e).slice(0, 200) }));
369
+ }
370
+ // Only now, once the new engine exists: a failed swap must leave the
371
+ // bridge speaking exactly as it was, not half-way between two engines.
372
+ const was = engine.name;
373
+ useEngine(next);
374
+ console.log(` engine: ${was} → ${engine.name} (asked for by the deck)`);
375
+ if (engine.caveat) console.log(` ${engine.caveat}`);
376
+ const voices = await voiceRoster().catch(() => []);
377
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
378
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, model: engine.model,
379
+ stylable: engine.stylable, cost: engine.cost, caveat: engine.caveat, voices, changed: true }));
380
+ }
181
381
  if (req.method === 'GET' && req.url === '/voices') {
182
382
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
183
383
  return res.end(JSON.stringify(await voiceRoster()));
@@ -194,11 +394,20 @@ export async function ttsMain(args) {
194
394
  // it silently became undiffable and unreviewable.
195
395
  const key = createHash('sha256')
196
396
  .update([engine.name, voice, style, text].join('\u0000')).digest('hex');
197
- const fresh = !cache.has(key);
397
+ let fresh = !cache.has(key);
398
+ if (fresh) {
399
+ const onDisk = diskRead(key);
400
+ if (onDisk) {
401
+ cache.set(key, onDisk);
402
+ fresh = false;
403
+ console.log(` ${engine.name} ${picked}: ${text.length} chars · cached on disk`);
404
+ }
405
+ }
198
406
  if (fresh) {
199
407
  process.stdout.write(` ${engine.name} ${picked}: ${text.length} chars … `);
200
408
  const t0 = Date.now();
201
409
  cache.set(key, await engine.synth(text, { voice, style }));
410
+ diskWrite(key, cache.get(key).wav);
202
411
  const u = cache.get(key).usage;
203
412
  // `cost` is OPTIONAL, and an installed engine is why (SPEC
204
413
  // ENGINE_UNITS): the six built-ins all happen to report one, so
@@ -249,7 +458,41 @@ export async function ttsMain(args) {
249
458
  res.end();
250
459
  });
251
460
 
252
- server.listen(port, '127.0.0.1', () => {
461
+ // A TAKEN PORT IS NOT A CRASH. Without this the bind threw EADDRINUSE as an
462
+ // unhandled 'error' event: a raw Node stack trace in the middle of author's
463
+ // startup output, which reads as decklight falling over when the truth is
464
+ // that something else has the port. The edit server has resolved conflicts
465
+ // for a long time (cli/port-conflict.mjs) — the bridges simply never called
466
+ // it, so they were the one place the deck could still look broken.
467
+ //
468
+ // On a TTY it names the occupant and offers a choice; anywhere else — and
469
+ // author spawns these with a piped stdin, so that is the usual case — it
470
+ // moves to the next free port and says so. The player finds the bridge by
471
+ // probing, so a moved port costs nothing.
472
+ // `canBind`, NOT `isPortOpen`: this file's own note says why, and getting it
473
+ // wrong the first time proved the point. `isPortOpen` CONNECTS, answering "is
474
+ // somebody there" — a listener that never accepts (backlog full, or a socket
475
+ // opened and ignored) refuses the connect and reads as free, and then the
476
+ // bind fails anyway. "May I have this port" is a different question and only
477
+ // a trial bind answers it.
478
+ //
479
+ // `--port 0` is "let the OS pick", which cannot conflict — resolving it would
480
+ // turn a deliberate 0 into port 1. Only a REAL port that is taken gets the
481
+ // question; everything else binds exactly as before.
482
+ const asked = port && !(await canBind(port))
483
+ ? await resolvePortConflict(port, {
484
+ kind: 'bridge',
485
+ ask: process.stdin.isTTY && process.stdout.isTTY ? askLine : undefined,
486
+ log: console.log,
487
+ })
488
+ : port;
489
+ // null is "stand down" — either a bridge is already serving this port, or
490
+ // somebody else holds it and this one cannot move (the deck only ever calls
491
+ // the one number). Exiting is the honest outcome: author prints "carrying on
492
+ // without it" and the deck degrades where you can see it, instead of a
493
+ // bridge running somewhere nothing will ever knock.
494
+ if (asked === null) process.exit(0);
495
+ server.listen(asked, '127.0.0.1', () => {
253
496
  // The BOUND port, not the requested one: `--port 0` legitimately means
254
497
  // "pick a free one", and printing the 0 back made the one line telling a
255
498
  // presenter where their bridge is into an unusable URL.
@@ -257,10 +500,18 @@ export async function ttsMain(args) {
257
500
  // `cost` is optional (SPEC ENGINE_UNITS) — an installed engine that
258
501
  // quotes no list price says nothing here rather than "(undefined)".
259
502
  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}`);
503
+ // Under author this is a banner ROW, not a line: author prints one block
504
+ // ending in the DECK's url, and a bridge url above it is the wrong thing
505
+ // to click. Standalone, the bridge is the whole program and says so.
506
+ if (process.env.DECKLIGHT_BANNER) {
507
+ console.log(readyLine({ key: 'voice', text: `${engine.name} · ${engine.model}${price} — on :${bound}` }));
508
+ if (engine.caveat) console.log(readyLine({ key: 'voice', text: engine.caveat }));
509
+ } else {
510
+ console.log(`decklight tts bridge on http://127.0.0.1:${bound} — ${engine.name} · ${engine.model}${price} — Ctrl-C stops`);
511
+ // Stated here, once, where the presenter is still choosing — not
512
+ // discovered mid-talk when the delivery already varied more than expected.
513
+ if (engine.caveat) console.log(` ${engine.caveat}`);
514
+ }
264
515
  // piper loads a ~120 MB model on start; do it now, while the deck is still
265
516
  // being opened, so the first sentence isn't a 13-second silence
266
517
  if (engine.synth.warm) {
@@ -49,11 +49,36 @@ import { resolve, join, basename } from 'node:path';
49
49
  import { homedir } from 'node:os';
50
50
  import { createEngine } from './tts-engines.mjs';
51
51
  import { argReader } from './args.mjs';
52
- import { sectionBodies, NOTES_ASIDE } from './deck-html.mjs';
52
+ import { sectionBodies, NOTES_ASIDE, cleanNotes, notesSegments } from './deck-html.mjs';
53
53
 
54
54
  const args = process.argv.slice(2);
55
+
56
+ const HELP = `decklight voiceover — batch-synthesize a deck's narration into a folder
57
+
58
+ Usage:
59
+ decklight voiceover <deck.html> [-o <dir>] [--engine piper|chirp|gemini|elevenlabs]
60
+ [--voice <name>] [--no-llm] [--reuse-text] [--keep-wav]
61
+
62
+ The headless counterpart of the deck's \u21e7V: it reads each slide's speaker
63
+ notes and writes one slide-NN.m4a per slide (plus a file per \u27e8CLICK\u27e9 beat)
64
+ and a manifest.json into <dir>, so a deck can point at it with
65
+ narration: { files: [{ label, dir, segments: true }] }.
66
+
67
+ -o <dir> output folder (default: <deck>/voiceover)
68
+ --engine piper (local, free, default) · chirp · gemini · elevenlabs
69
+ --voice the engine's voice name (piper: a model name; elevenlabs: omit
70
+ for the first of YOUR voices)
71
+ --no-llm skip the local-LLM notes rewrite; voice the notes as written
72
+ --reuse-text re-voice the existing slide-NN.txt without re-rolling the text
73
+ — switch voices or engines without a new narration pass
74
+ --keep-wav keep the lossless WAVs (tools/lipsync.mjs consumes them)
75
+
76
+ Cloud engines need --project or $GOOGLE_CLOUD_PROJECT and application-default
77
+ credentials; elevenlabs needs $ELEVENLABS_API_KEY. Audio is a build artifact.`;
78
+
79
+ if (args.includes('--help') || args.includes('-h')) { console.log(HELP); process.exit(0); }
55
80
  const deckPath = args.find((a) => !a.startsWith('-'));
56
- if (!deckPath) { console.error('usage: voiceover.mjs <deck.html> [-o dir] [--engine piper|chirp|gemini|elevenlabs] [--voice name] [--no-llm] [--reuse-text]'); process.exit(1); }
81
+ if (!deckPath) { console.error('decklight voiceover: name the deck to voice\n\n' + HELP); process.exit(1); }
57
82
  const { opt } = argReader(args);
58
83
  const outDir = resolve(opt('-o', join(resolve(deckPath, '..'), 'voiceover')));
59
84
  const engine = opt('--engine', 'piper');
@@ -102,19 +127,13 @@ const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
102
127
  // ── extract per-slide narration text ─────────────────────────────────────────
103
128
  const html = readFileSync(deckPath, 'utf8');
104
129
  const sections = sectionBodies(html);
105
- const clean = (s) => s
106
- .replace(/⟨CLICK⟩/g, ' ')
107
- .replace(/<[^>]+>/g, ' ')
108
- .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
109
- .replace(/\s+/g, ' ')
110
- .trim();
111
130
  const raw = sections.map((sec) => {
112
131
  const aside = sec.match(NOTES_ASIDE);
113
132
  if (aside) return aside[1];
114
133
  const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
115
134
  return md ? md[1] : '';
116
135
  });
117
- const slides = raw.map(clean);
136
+ const slides = raw.map(cleanNotes);
118
137
  /**
119
138
  * A slide's ⟨CLICK⟩ segments, or null when there is only one.
120
139
  *
@@ -126,10 +145,6 @@ const slides = raw.map(clean);
126
145
  * as silence — a ⟨CLICK⟩ at the very start or end of a note is punctuation,
127
146
  * not a beat.
128
147
  */
129
- export const notesSegments = (notes) => {
130
- const parts = String(notes ?? '').split('⟨CLICK⟩').map(clean).filter(Boolean);
131
- return parts.length > 1 ? parts : null;
132
- };
133
148
  // Segmenting needs ffmpeg specifically: the per-slide file is CONCATENATED from
134
149
  // the segments, and afconvert (Core Audio, macOS-only) has no concat demuxer.
135
150
  // Without it the slide is synthesised whole, exactly as before.
@@ -211,6 +226,10 @@ for (let i = 0; i < slides.length; i++) {
211
226
  const sM4a = join(outDir, `slide-${n}-${kk}.m4a`);
212
227
  const out = await tts.synth(segs[k], { voice, style });
213
228
  writeFileSync(sWav, out.wav);
229
+ // The beat's own words, beside its own audio — tools/lipsync.mjs hands
230
+ // this to Rhubarb as the dialog hint, and a hint for the whole slide
231
+ // would be worse than none against one beat of it.
232
+ writeFileSync(join(outDir, `slide-${n}-${kk}.txt`), segs[k]);
214
233
  usage = { cost: usage.cost + (out.usage?.cost ?? 0) };
215
234
  toAac(sWav, sM4a);
216
235
  if (!keepWav) rmSync(sWav);