decklight 0.5.0 → 0.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "A presentation library designed to be authored by AI agents and humans alike: single-file decks, Keynote-style builds, theme-aware SVG diagrams, and truthful terminal recordings.",
5
5
  "type": "module",
6
6
  "main": "dist/decklight.js",
@@ -21,6 +21,40 @@ export const NOTES_ASIDE = /<aside class="notes">([\s\S]*?)<\/aside>/;
21
21
  */
22
22
  export const sectionBodies = (html) => html.split(/<section\b/).slice(1);
23
23
 
24
+ /**
25
+ * Speaker-note HTML as plain text: tags out, entities back, whitespace flat.
26
+ *
27
+ * The runtime gets this for free from `textContent`; a tool reading the FILE
28
+ * has to do it, and has to do it the same way or the two disagree about what a
29
+ * segment says.
30
+ */
31
+ export const cleanNotes = (s) => String(s ?? '')
32
+ .replace(/⟨CLICK⟩/g, ' ')
33
+ .replace(/<[^>]+>/g, ' ')
34
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
35
+ .replace(/\s+/g, ' ')
36
+ .trim();
37
+
38
+ /**
39
+ * A slide's notes split into the ⟨CLICK⟩ segments that become FILES, or null
40
+ * when there are not enough to be worth segmenting.
41
+ *
42
+ * Lives here rather than in tools/voiceover.mjs — which cannot be imported at
43
+ * all, it arg-parses and exits at load — so the runtime's
44
+ * `segmentFileIndex` can be tested against the very function that names the
45
+ * files it is predicting. Those two disagreeing is a silent bug: the runtime
46
+ * keeps empty segments (segment k must line up with build step k) and this
47
+ * drops them (it is naming files), so a ⟨CLICK⟩ at the start of a note shifts
48
+ * every filename by one.
49
+ *
50
+ * An empty segment is dropped rather than recorded as silence — a ⟨CLICK⟩ at
51
+ * the very start or end of a note is punctuation, not a beat.
52
+ */
53
+ export const notesSegments = (notes) => {
54
+ const parts = String(notes ?? '').split('⟨CLICK⟩').map(cleanNotes).filter(Boolean);
55
+ return parts.length > 1 ? parts : null;
56
+ };
57
+
24
58
  /**
25
59
  * Locate slide `n` (1-based) for a round-trip rewrite. Returns the capturing
26
60
  * split (`[preamble, '<section', body1, '<section', body2, …]`) and the index
@@ -43,12 +43,12 @@
43
43
  // registered reaches its own voice exactly as it always did.
44
44
 
45
45
  import { execFileSync, spawn } from 'node:child_process';
46
- import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
46
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
47
47
  import { homedir, tmpdir } from 'node:os';
48
- import { join } from 'node:path';
48
+ import { delimiter, join } from 'node:path';
49
49
  import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId, authHeaders } from './gemini-tts.mjs';
50
50
  import {
51
- createSynth as createElevenLabs, apiKey as elevenLabsKey,
51
+ createSynth as createElevenLabs, apiKey as elevenLabsKey, KEY_ENV as ELEVENLABS_KEY_ENV,
52
52
  DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL,
53
53
  } from './elevenlabs-tts.mjs';
54
54
  import { detectLocalVoice, sayArgs, sapiArgs } from './local-voice.mjs';
@@ -333,10 +333,32 @@ function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
333
333
  * Neither takes a delivery instruction, so both are `stylable: false` and the
334
334
  * picker skips the tone step, exactly as it does for piper and ElevenLabs.
335
335
  */
336
- function createNative({ kind, voice, shell = 'powershell.exe' }) {
336
+ function createNative({ kind, voice, shell = 'powershell.exe', voices = [] }) {
337
337
  const bin = kind === 'say' ? 'say' : shell;
338
338
  const build = kind === 'say' ? sayArgs : sapiArgs;
339
- return async (text) => {
339
+ // The roster this machine actually has, for the guard below. Held as names
340
+ // because that is what the player sends and what `say -v` takes.
341
+ const known = new Set(voices.map((v) => v?.name ?? v).filter(Boolean));
342
+ /**
343
+ * `(text, { voice })` — the SECOND argument is the voice for THIS sentence,
344
+ * and it is the whole contract every other engine here implements.
345
+ *
346
+ * This used to be `async (text) =>`, closing over the voice chosen when the
347
+ * bridge started. So the picker offered 184 macOS voices, the log printed
348
+ * whichever one you picked, and all 184 played the same one — the failure was
349
+ * invisible in the logs because the log line quotes the REQUEST.
350
+ */
351
+ return async (text, { voice: asked } = {}) => {
352
+ const pick = asked || voice;
353
+ // A name this machine cannot say is an ERROR, not a shrug. `say -v Zephyr`
354
+ // exits 0 and quietly produces the SYSTEM DEFAULT voice — so a typo, a
355
+ // stale saved voice, or a roster from another engine all sound like
356
+ // success while giving you somebody else's voice. (PowerShell's
357
+ // SelectVoice already throws on an unknown name; this makes the two agree.)
358
+ if (kind === 'say' && known.size && pick && !known.has(pick)) {
359
+ throw new Error(`no ${kind} voice named ${JSON.stringify(pick)} on this machine`
360
+ + ` — this bridge speaks ${known.size} others (GET /voices)`);
361
+ }
340
362
  // one line: `say` treats newlines as pauses and PowerShell quoting gets
341
363
  // harder the moment a string spans lines
342
364
  const line = String(text).replace(/\s+/g, ' ').trim();
@@ -344,7 +366,7 @@ function createNative({ kind, voice, shell = 'powershell.exe' }) {
344
366
  const dir = mkdtempSync(join(tmpdir(), 'decklight-native-'));
345
367
  const file = join(dir, 'out.wav');
346
368
  try {
347
- execFileSync(bin, build(line, voice, file), { stdio: ['ignore', 'ignore', 'pipe'] });
369
+ execFileSync(bin, build(line, pick, file), { stdio: ['ignore', 'ignore', 'pipe'] });
348
370
  const wav = readFileSync(file);
349
371
  if (!wav.length) throw new Error(`${kind} produced no audio`);
350
372
  // `{ wav, usage }`, like every other engine and like this file's own
@@ -355,7 +377,8 @@ function createNative({ kind, voice, shell = 'powershell.exe' }) {
355
377
  // behind a door that never opened.
356
378
  return {
357
379
  wav,
358
- usage: { model: voice ?? kind, chars: line.length, cost: 0, note: `${line.length} chars · local` },
380
+ // the voice that SPOKE, not the one the bridge booted with
381
+ usage: { model: pick ?? kind, chars: line.length, cost: 0, note: `${line.length} chars · local` },
359
382
  };
360
383
  } catch (e) {
361
384
  throw new Error(`${kind}: ${String(e.stderr ?? e.message).trim().split('\n')[0] || 'synthesis failed'}`);
@@ -367,6 +390,10 @@ function createNative({ kind, voice, shell = 'powershell.exe' }) {
367
390
 
368
391
  export function createEngine({
369
392
  engine = 'gemini', project, model, location, voice, dataDir, lang, format, stability, env = process.env,
393
+ // Injected like every other probe in this file, so a native engine can be
394
+ // built — and its voice handling asserted — on a machine that is not the one
395
+ // the test happens to run on.
396
+ detect = detectLocalVoice,
370
397
  } = {}) {
371
398
  if (!ENGINES.includes(engine)) {
372
399
  throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')},`
@@ -385,14 +412,16 @@ export function createEngine({
385
412
  };
386
413
  }
387
414
  if (engine === 'say' || engine === 'sapi') {
388
- const detected = detectLocalVoice({ lang });
415
+ const detected = detect({ lang });
389
416
  const pick = voice ?? detected.voices?.[0]?.name;
390
417
  if (!pick) throw new Error(detected.why ?? `no ${engine} voices on this machine`);
391
418
  return {
392
419
  name: engine, model: pick, needsProject: false, stylable: false,
393
420
  cost: 'free · offline · already on this machine',
394
421
  voices: (detected.voices ?? []).map((v) => [v.name, v.locale || 'system']),
395
- synth: createNative({ kind: engine, voice: pick, shell: detected.shell }),
422
+ synth: createNative({
423
+ kind: engine, voice: pick, shell: detected.shell, voices: detected.voices ?? [],
424
+ }),
396
425
  };
397
426
  }
398
427
  if (engine === 'elevenlabs') {
@@ -440,6 +469,154 @@ export function createEngine({
440
469
  };
441
470
  }
442
471
 
472
+ /**
473
+ * Is `bin` on PATH? The bare-name probe the readiness check needs.
474
+ *
475
+ * `cli/agents.mjs` has the full version (explicit paths, execute bits); this
476
+ * one is here rather than there because `tools/` cannot import from `cli/`,
477
+ * and `tools/tts-setup.mjs` shares it so the wizard and the readiness check
478
+ * cannot disagree about whether piper is installed.
479
+ */
480
+ export function binOnPath(bin, env = process.env) {
481
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
482
+ return (env.PATH || '').split(delimiter)
483
+ .some((dir) => dir && exts.some((ext) => existsSync(join(dir, bin + ext))));
484
+ }
485
+
486
+ /**
487
+ * Can this machine speak with `name` right now, and if not, what is missing?
488
+ *
489
+ * WHY THIS IS NOT `createEngine` THROWING. Two of the six build perfectly well
490
+ * and fail later: `gemini` and `chirp` construct a synth against a project id
491
+ * nobody has checked, so the bridge would come up looking healthy and only die
492
+ * on the first keypress — with a 403 naming a project the presenter never
493
+ * typed. Readiness is a question about the MACHINE (a binary, a model file, a
494
+ * key, a project), and it has to be asked before anything is constructed.
495
+ *
496
+ * WHY IT LIVES HERE. Two callers now ask it: `decklight author`, deciding
497
+ * whether to start the bridge at all, and the bridge itself, listing what the
498
+ * deck may switch to (SPEC `NARRATION`). They must not disagree — a picker
499
+ * offering an engine that `author` would have refused is a picker that lies.
500
+ * So the DECISION is shared and only the presentation differs: `reason` is a
501
+ * code the caller phrases for its own audience.
502
+ *
503
+ * Every probe is injected, so this is testable without a PATH, a filesystem,
504
+ * or a credential.
505
+ */
506
+ export function engineStatus(name, {
507
+ // `project` defaults from the environment rather than to null: a caller that
508
+ // passes only `env` means "decide from this machine", and answering
509
+ // no-project on a machine whose GOOGLE_CLOUD_PROJECT is right there would be
510
+ // a wrong answer that looks like a correct one. A caller with its own
511
+ // precedence ladder (flags > env > saved config) passes the settled value.
512
+ env = process.env, project = env.GOOGLE_CLOUD_PROJECT ?? null,
513
+ voice = null, dataDir = null, lang = null,
514
+ hasBin = binOnPath, exists = existsSync, detect = detectLocalVoice,
515
+ } = {}) {
516
+ const no = (reason, detail) => ({ name, ready: false, reason, ...detail });
517
+ if (!ENGINES.includes(name)) return no('unknown');
518
+
519
+ if (name === 'piper') {
520
+ if (!hasBin('piper', env)) return no('no-binary');
521
+ const v = voice ?? PIPER_DEFAULT_VOICE;
522
+ const models = dataDir ?? piperModelDir(env);
523
+ if (!exists(piperModelPath(v, models))) return no('no-model', { voice: v, dataDir: models });
524
+ return { name, ready: true, reason: 'ok' };
525
+ }
526
+ if (NATIVE_ENGINES.includes(name)) {
527
+ // A system voice needs no setup at all — but the wrong OS has none, and
528
+ // `say` on a machine with no configured voices is a silent bridge.
529
+ const d = detect({ lang });
530
+ if (d?.engine !== name || !d?.voices?.length) return no('no-native-voice', { why: d?.why });
531
+ return { name, ready: true, reason: 'ok' };
532
+ }
533
+ if (name === 'elevenlabs') {
534
+ return elevenLabsKey(env)?.trim() ? { name, ready: true, reason: 'ok' } : no('no-key');
535
+ }
536
+ // gemini and chirp
537
+ if (!project) return no('no-project');
538
+ if (!validProjectId(project)) return no('bad-project', { project });
539
+ return { name, ready: true, reason: 'ok' };
540
+ }
541
+
542
+ /**
543
+ * A blocker in two short sentences: what is missing, and what fixes it.
544
+ *
545
+ * These are the PICKER's words — one line each, because they are drawn under a
546
+ * greyed row in a deck. `decklight author` phrases the same codes at length
547
+ * (it has a terminal, and it is the place a presenter is still setting up).
548
+ * Both read the same `reason`, so they can be worded for their audience
549
+ * without being able to disagree about the facts.
550
+ *
551
+ * Every fix is something you do in a TERMINAL, and that is deliberate: the
552
+ * deck lists what is missing and never collects it. A key or a project id
553
+ * typed into a web page — even one on loopback — is a different thing from one
554
+ * exported in a shell, and a presented deck is reachable from a phone.
555
+ */
556
+ export function engineBlocker(status, { env = process.env } = {}) {
557
+ const { reason } = status ?? {};
558
+ if (!reason || reason === 'ok') return null;
559
+ switch (reason) {
560
+ case 'no-binary':
561
+ return { why: 'not installed', fix: 'uv tool install piper-tts' };
562
+ case 'no-model':
563
+ return {
564
+ why: `the voice ${status.voice} is not downloaded (~120 MB, one time)`,
565
+ fix: piperDownloadLine(piperDownloadCmd(status.voice, status.dataDir,
566
+ { hasBin: (b) => binOnPath(b, env) })),
567
+ };
568
+ case 'no-key':
569
+ return { why: `needs $${ELEVENLABS_KEY_ENV}`, fix: 'export it, then restart decklight author' };
570
+ case 'no-project':
571
+ return {
572
+ why: 'needs a Google Cloud project',
573
+ fix: 'export GOOGLE_CLOUD_PROJECT=<id>, then restart decklight author',
574
+ };
575
+ case 'bad-project':
576
+ // Named rather than generic: this one is nearly always a copy-paste that
577
+ // brought punctuation with it, and seeing the value is the whole fix.
578
+ return { why: `not a GCP project id: ${JSON.stringify(status.project)}`, fix: 'stray punctuation from a copy-paste?' };
579
+ case 'no-native-voice':
580
+ return { why: status.why ?? 'no system voice on this machine', fix: null };
581
+ default:
582
+ return { why: `unknown engine — use ${ENGINES.join(', ')}`, fix: null };
583
+ }
584
+ }
585
+
586
+ /**
587
+ * What a presenter could switch to, with the price note and the blocker.
588
+ *
589
+ * Order is a RECOMMENDATION and deliberately not `ENGINES` order (which keeps
590
+ * gemini first for history): free and already-on-this-machine first, then the
591
+ * ones with a bill. The native engine is folded to whichever of say/sapi this
592
+ * OS actually has, because "sapi" on a Mac is not a choice, it is noise.
593
+ *
594
+ * `cost` comes from the engine itself where it can be built, so the picker
595
+ * quotes the same sentence the bridge's startup line does rather than a second
596
+ * copy of it. An engine that cannot be built has no cost to quote — it has a
597
+ * blocker, which is what the row shows instead.
598
+ */
599
+ export function engineMenu(opts = {}) {
600
+ // Settled once, and shared with the construction below: `createEngine` for a
601
+ // cloud engine REFUSES a missing project, so a menu that probed readiness
602
+ // with the environment's project but built with `undefined` would quietly
603
+ // drop the price note off every row it had just called ready.
604
+ const env = opts.env ?? process.env;
605
+ const settled = { ...opts, env, project: opts.project ?? env.GOOGLE_CLOUD_PROJECT ?? null };
606
+ const native = NATIVE_ENGINES.includes(process.platform === 'win32' ? 'sapi' : 'say')
607
+ ? (process.platform === 'win32' ? 'sapi' : 'say') : null;
608
+ const order = [native, 'piper', 'chirp', 'gemini', 'elevenlabs'].filter(Boolean);
609
+ return order.map((name) => {
610
+ const status = engineStatus(name, settled);
611
+ let cost;
612
+ // Building it is the only way to learn the price note, and it is cheap —
613
+ // no network, no process. It can still throw (a native engine with no
614
+ // voices), which is not an error here: the row already carries the blocker.
615
+ try { cost = createEngine({ ...settled, engine: name }).cost; } catch { cost = undefined; }
616
+ return { ...status, cost, ...(engineBlocker(status, settled) ?? {}) };
617
+ });
618
+ }
619
+
443
620
  /**
444
621
  * The engine for `name`, whether decklight ships it or the machine installed
445
622
  * it (SPEC `ENGINE_UNITS`).
@@ -21,6 +21,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node
21
21
  import { homedir, tmpdir } from 'node:os';
22
22
  import { delimiter, dirname, join } from 'node:path';
23
23
  import {
24
+ binOnPath,
24
25
  createEngine, ENGINES, PIPER_DEFAULT_VOICE, piperModelDir,
25
26
  piperDownloadCmd, piperDownloadLine,
26
27
  } from './tts-engines.mjs';
@@ -50,14 +51,6 @@ export function saveTtsConfig(config, env = process.env) {
50
51
  return file;
51
52
  }
52
53
 
53
- // cli/agents.mjs has the full onPath (explicit paths too); tools/ cannot
54
- // import from cli/, and the wizard only ever probes bare names.
55
- function binOnPath(bin, env = process.env) {
56
- const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
57
- return (env.PATH || '').split(delimiter)
58
- .some((dir) => dir && exts.some((ext) => existsSync(join(dir, bin + ext))));
59
- }
60
-
61
54
  /** The project gcloud is configured with — the prefill when $GOOGLE_CLOUD_PROJECT is unset. */
62
55
  export function gcloudConfigProject() {
63
56
  try {
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,23 @@ export function extractHolds(html, defaultHold) {
103
108
  });
104
109
  }
105
110
 
111
+ /**
112
+ * Per-slide narration beat: data-narration-pause="2" on the section, else 0.
113
+ *
114
+ * The recorded mirror of the live rule (PRESENTING): src/core/narration.js
115
+ * holds that many seconds after a slide's last sentence before moving on, and
116
+ * an exported mp4 must breathe in the same places the deck does. Read off the
117
+ * raw open tag, like extractHolds, so the same attribute appearing in a
118
+ * slide's CONTENT cannot be mistaken for the slide's own.
119
+ */
120
+ export function extractPauses(html) {
121
+ return sectionBodies(html).map((sec) => {
122
+ const tag = sec.slice(0, sec.indexOf('>'));
123
+ const m = tag.match(/data-narration-pause="([\d.]+)"/);
124
+ return m ? Number(m[1]) : 0;
125
+ });
126
+ }
127
+
106
128
  /**
107
129
  * An oversized step: the engine clamps it to the slide's last build, so this
108
130
  * always renders a slide fully built however many steps it turns out to have.
@@ -145,10 +167,13 @@ const round = (s) => Math.round(s * 1000) / 1000;
145
167
  * @param {{from,to}} [range] 1-based inclusive slide range
146
168
  * @param {object} [opts] steps: per-slide build-step counts (null ⇒ one
147
169
  * 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
170
+ * build-up frame (null ⇒ the slide's own hold);
171
+ * pauses: per-slide data-narration-pause seconds
172
+ * added to a NARRATED slide's finished frame
173
+ * @returns {Array<{slide, step, audio, duration, pad}>} audio null ⇒ silent hold;
174
+ * `pad` is the silence ffmpeg appends to the audio
150
175
  */
151
- export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, onWarn = null } = {}) {
176
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, pauses = null, onWarn = null } = {}) {
152
177
  const from = range?.from ?? 1;
153
178
  const to = range?.to ?? holds.length;
154
179
  const plan = [];
@@ -165,6 +190,10 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
165
190
  // segmentation. This makes the recorded render the mirror of it.
166
191
  const segs = entry?.segments ?? null;
167
192
  const builds = steps?.[n - 1] ?? 0;
193
+ // The slide's own beat rides on the tail of its finished frame — the one
194
+ // place the live deck pauses too. A silent slide has no narration to pause
195
+ // after; --hold and data-video-hold are its knobs.
196
+ const tail = TAIL_SECONDS + (pauses?.[n - 1] ?? 0);
168
197
  if (Number.isFinite(dur) && segs?.length && builds) {
169
198
  const times = segs.map((sg) => durations?.[sg.file]);
170
199
  if (segs.length === builds + 1 && times.every((t) => Number.isFinite(t))) {
@@ -176,7 +205,8 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
176
205
  audio: sg.file,
177
206
  // Only the finished slide gets the breath. A build that paused for
178
207
  // it would read as hesitation rather than as a beat.
179
- duration: round(times[k] + (last ? TAIL_SECONDS : 0)),
208
+ duration: round(times[k] + (last ? tail : 0)),
209
+ pad: last ? tail : 0,
180
210
  });
181
211
  });
182
212
  continue;
@@ -191,7 +221,7 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
191
221
  }
192
222
 
193
223
  if (Number.isFinite(dur)) {
194
- plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + TAIL_SECONDS) });
224
+ plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + tail), pad: tail });
195
225
  continue;
196
226
  }
197
227
  const hold = holds[n - 1];
@@ -205,17 +235,18 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
205
235
 
206
236
  /**
207
237
  * 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
238
+ * audio. Narrated slides pad the audio with `pad` — the tail, plus whatever
239
+ * beat the slide asked for (`data-narration-pause`) — and stop there; silent
209
240
  * slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
210
241
  * carries an audio stream and the concat-demuxer's `-c copy` audio track never
211
242
  * goes discontinuous. -t bounds both the infinite loop and the infinite
212
243
  * anullsrc (-shortest can't end a segment whose streams are both endless).
213
244
  */
214
- export function segmentArgs({ frame, audio, duration, fps, out }) {
245
+ export function segmentArgs({ frame, audio, duration, fps, out, pad = TAIL_SECONDS }) {
215
246
  return [
216
247
  '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
217
248
  ...(audio
218
- ? ['-i', audio, '-af', `apad=pad_dur=${TAIL_SECONDS}`]
249
+ ? ['-i', audio, '-af', `apad=pad_dur=${pad}`]
219
250
  : ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
220
251
  '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
221
252
  '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
@@ -363,6 +394,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
363
394
 
364
395
  const html = readFileSync(deck, 'utf8');
365
396
  const holds = extractHolds(html, hold);
397
+ const pauses = extractPauses(html);
366
398
  if (!holds.length) throw new Error(`${basename(deck)} has no <section> slides`);
367
399
  const range = parseSlideRange(opt('--slides'), holds.length);
368
400
 
@@ -434,7 +466,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
434
466
  if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
435
467
 
436
468
  plan = planTimeline(narration?.slides ?? null, durations, holds, range,
437
- { steps, buildHold, onWarn: (w) => console.warn(` ${w}`) });
469
+ { steps, buildHold, pauses, onWarn: (w) => console.warn(` ${w}`) });
438
470
  const slideCount = new Set(plan.map((p) => p.slide)).size;
439
471
  log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
440
472
  + `${plan.filter((p) => p.audio).length} narrated`
@@ -459,7 +491,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
459
491
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
460
492
  const seg = join(work, `seg-${id}.mp4`);
461
493
  await exec('ffmpeg', segmentArgs({
462
- frame, duration: p.duration, fps, out: seg,
494
+ frame, duration: p.duration, pad: p.pad, fps, out: seg,
463
495
  audio: p.audio ? join(narration.dir, p.audio) : null,
464
496
  }));
465
497
  segments.push(seg);
@@ -38,7 +38,7 @@
38
38
  import { createServer } from 'node:http';
39
39
  import { createHash } from 'node:crypto';
40
40
  import { createInterface } from 'node:readline/promises';
41
- import { resolveEngine, ENGINES } from './tts-engines.mjs';
41
+ import { resolveEngine, engineBlocker, engineMenu, engineStatus, ENGINES } from './tts-engines.mjs';
42
42
  import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
43
43
  import { argReader, isMain } from './args.mjs';
44
44
  import { corsHeaders, readBody } from './bridge.mjs';
@@ -144,17 +144,44 @@ export async function ttsMain(args) {
144
144
  // made the name offerable, rather than in each engine — an engine that had to
145
145
  // know about the unit library would be an engine that could no longer be
146
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)`);
147
+ // Everything derived from the live engine, recomputed together — because the
148
+ // deck can now change which engine that is (SPEC `NARRATION`), and a roster
149
+ // or an id map left behind from the previous one would offer voices the
150
+ // current engine cannot say.
151
+ let refs = [];
152
+ let refIds = new Map();
153
+ const useEngine = (e) => {
154
+ engine = e;
155
+ refs = installedVoices(e.name);
156
+ refIds = new Map(refs.map((r) => [r.label, r.voiceId]));
157
+ if (refs.length) console.log(` voices: +${refs.length} installed (decklight voice list)`);
158
+ };
159
+ useEngine(engine);
150
160
 
151
161
  const voiceRoster = async () => [
152
162
  ...(engine.listVoices ? (await engine.listVoices()).map((v) => [v.name, v.flavor]) : engine.voices),
153
163
  ...refs.map((r) => [r.label, r.marketplace ?? 'installed']),
154
164
  ];
155
165
 
166
+ // The engine's NAME is part of every cache key, so a swap cannot serve one
167
+ // engine's audio under another's voice — the cache survives the switch, and
168
+ // switching back replays instantly rather than re-billing.
156
169
  const cache = new Map();
157
170
 
171
+ // What the bridge could become, and what stands in the way. The options the
172
+ // deck's picker draws (SPEC `NARRATION`).
173
+ //
174
+ // The blockers are all fixed in a TERMINAL and this route never collects
175
+ // one: a key or a project id typed into a web page — even one on loopback —
176
+ // is a different thing from one exported in a shell, and a deck under
177
+ // `--remote` is reachable from a phone. So the deck lists what is missing and
178
+ // says where to fix it; it never becomes the place you configure credentials.
179
+ const menuOpts = () => ({
180
+ env: process.env,
181
+ project: opt('--project') ?? process.env.GOOGLE_CLOUD_PROJECT ?? saved?.project,
182
+ voice: opt('--voice'), dataDir: opt('--data-dir'), lang: opt('--lang'),
183
+ });
184
+
158
185
  // the player reads the cost estimate for its debug window
159
186
  const CORS = corsHeaders('x-tts-cost, x-tts-tokens, x-tts-cached');
160
187
  let totalCost = 0;
@@ -178,6 +205,70 @@ export async function ttsMain(args) {
178
205
  voices, // piper speaks one voice, not the star roster
179
206
  }));
180
207
  }
208
+ // ── which engine is speaking, and what else could (SPEC `NARRATION`) ──
209
+ if (req.method === 'GET' && req.url === '/engines') {
210
+ // Ready or not, every engine is listed. Hiding the ones this machine
211
+ // cannot use would answer "where did ElevenLabs go?" with silence — the
212
+ // useful answer is that it is there and needs a key.
213
+ const opts = menuOpts();
214
+ const menu = engineMenu(opts).map((e) => ({ ...e, current: e.name === engine.name }));
215
+ // An engine the bridge was STARTED with is ready by definition — it is
216
+ // speaking. Detection can disagree (a marketplace engine is not one of
217
+ // the six, and a project passed by flag is invisible to a later probe),
218
+ // and a picker that greyed out the running engine would be absurd.
219
+ if (!menu.some((e) => e.current)) {
220
+ menu.unshift({ name: engine.name, ready: true, reason: 'ok', current: true, cost: engine.cost });
221
+ }
222
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
223
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, engines: menu }));
224
+ }
225
+ if (req.method === 'POST' && req.url === '/engine') {
226
+ let name;
227
+ try { ({ engine: name } = JSON.parse((await readBody(req)).toString())); }
228
+ catch { name = null; }
229
+ if (typeof name !== 'string' || !name) {
230
+ res.writeHead(400, { ...CORS, 'content-type': 'application/json' });
231
+ return res.end(JSON.stringify({ ok: false, error: 'name the engine' }));
232
+ }
233
+ if (name === engine.name) {
234
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
235
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, model: engine.model,
236
+ stylable: engine.stylable, voices: await voiceRoster().catch(() => []), changed: false }));
237
+ }
238
+ const opts = menuOpts();
239
+ // Checked BEFORE building, because two of the six build perfectly well
240
+ // and only fail on the first sentence — which mid-talk is a keypress into
241
+ // silence. A refusal here is recoverable; that one is not.
242
+ const status = engineStatus(name, opts);
243
+ if (ENGINES.includes(name) && !status.ready) {
244
+ // The blocker travels WITH the refusal. The deck's picker normally has
245
+ // it already (it came down with /engines), but a menu can be a minute
246
+ // stale — a key exported and un-exported, a model deleted — and a
247
+ // refusal the deck cannot put words to is a row that does nothing when
248
+ // clicked.
249
+ res.writeHead(409, { ...CORS, 'content-type': 'application/json' });
250
+ return res.end(JSON.stringify({
251
+ ok: false, error: status.reason, ...status, ...(engineBlocker(status, opts) ?? {}),
252
+ }));
253
+ }
254
+ let next;
255
+ try {
256
+ next = await resolveEngine({ ...opts, engine: name, model: undefined });
257
+ } catch (e) {
258
+ res.writeHead(409, { ...CORS, 'content-type': 'application/json' });
259
+ return res.end(JSON.stringify({ ok: false, error: String(e.message ?? e).slice(0, 200) }));
260
+ }
261
+ // Only now, once the new engine exists: a failed swap must leave the
262
+ // bridge speaking exactly as it was, not half-way between two engines.
263
+ const was = engine.name;
264
+ useEngine(next);
265
+ console.log(` engine: ${was} → ${engine.name} (asked for by the deck)`);
266
+ if (engine.caveat) console.log(` ${engine.caveat}`);
267
+ const voices = await voiceRoster().catch(() => []);
268
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
269
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, model: engine.model,
270
+ stylable: engine.stylable, cost: engine.cost, caveat: engine.caveat, voices, changed: true }));
271
+ }
181
272
  if (req.method === 'GET' && req.url === '/voices') {
182
273
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
183
274
  return res.end(JSON.stringify(await voiceRoster()));
@@ -49,7 +49,7 @@ 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
55
  const deckPath = args.find((a) => !a.startsWith('-'));
@@ -102,19 +102,13 @@ const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
102
102
  // ── extract per-slide narration text ─────────────────────────────────────────
103
103
  const html = readFileSync(deckPath, 'utf8');
104
104
  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
105
  const raw = sections.map((sec) => {
112
106
  const aside = sec.match(NOTES_ASIDE);
113
107
  if (aside) return aside[1];
114
108
  const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
115
109
  return md ? md[1] : '';
116
110
  });
117
- const slides = raw.map(clean);
111
+ const slides = raw.map(cleanNotes);
118
112
  /**
119
113
  * A slide's ⟨CLICK⟩ segments, or null when there is only one.
120
114
  *
@@ -126,10 +120,6 @@ const slides = raw.map(clean);
126
120
  * as silence — a ⟨CLICK⟩ at the very start or end of a note is punctuation,
127
121
  * not a beat.
128
122
  */
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
123
  // Segmenting needs ffmpeg specifically: the per-slide file is CONCATENATED from
134
124
  // the segments, and afconvert (Core Audio, macOS-only) has no concat demuxer.
135
125
  // Without it the slide is synthesised whole, exactly as before.