decklight 0.7.0 → 0.8.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.
@@ -47,11 +47,14 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
47
47
  import { homedir, tmpdir } from 'node:os';
48
48
  import { delimiter, join } from 'node:path';
49
49
  import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId, authHeaders } from './gemini-tts.mjs';
50
+ import { run, PROBE_MS } from './exec.mjs';
50
51
  import {
51
52
  createSynth as createElevenLabs, apiKey as elevenLabsKey, KEY_ENV as ELEVENLABS_KEY_ENV,
52
53
  DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL,
53
54
  } from './elevenlabs-tts.mjs';
54
- import { detectLocalVoice, sayArgs, sapiArgs, winrtArgs, TIER_LABEL } from './local-voice.mjs';
55
+ import {
56
+ detectLocalVoice, sayArgs, sapiArgs, winrtArgs, TIER_LABEL, withoutSupersededPlain,
57
+ } from './local-voice.mjs';
55
58
 
56
59
  export const ENGINES = ['gemini', 'chirp', 'piper', 'elevenlabs', 'say', 'sapi'];
57
60
  /** The two engines that are already on the machine — nothing to install. */
@@ -70,7 +73,7 @@ const onPath = (bin) => {
70
73
  } catch { return false; }
71
74
  };
72
75
  const canImportPiper = (py) => {
73
- try { execFileSync(py, ['-c', 'import piper.download_voices'], { stdio: 'ignore' }); return true; }
76
+ try { run(py, ['-c', 'import piper.download_voices'], { stdio: 'ignore', timeout: PROBE_MS }); return true; }
74
77
  catch { return false; }
75
78
  };
76
79
 
@@ -184,7 +187,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
184
187
  * request would silently become several utterances.
185
188
  */
186
189
  function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
187
- try { execFileSync('piper', ['--help'], { stdio: 'ignore' }); }
190
+ try { run('piper', ['--help'], { stdio: 'ignore', timeout: PROBE_MS }); }
188
191
  catch { throw new Error('piper not found — install with: uv tool install piper-tts'); }
189
192
  // A bare model NAME only resolves against a data dir — without one, piper
190
193
  // searches its own default and calls the voice missing even when it is
@@ -333,7 +336,21 @@ function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
333
336
  * Neither takes a delivery instruction, so both are `stylable: false` and the
334
337
  * picker skips the tone step, exactly as it does for piper and ElevenLabs.
335
338
  */
336
- function createNative({ kind, voice, shell = 'powershell.exe', voices = [], api = null }) {
339
+ /**
340
+ * How long one sentence may take before the synthesizer is declared wedged.
341
+ *
342
+ * `say -o` renders far faster than real time — a whole slide's notes is a few
343
+ * seconds — so this is not a budget, it is a tripwire. The failure it exists
344
+ * for: macOS's speech server (speechsynthesisd) can deadlock under concurrent
345
+ * `say` calls, and the child then sits forever with no CPU and no output.
346
+ * Unbounded, that hung `decklight voiceover` indefinitely with no message,
347
+ * and hung the unit suite for eight minutes before anyone looked.
348
+ */
349
+ export const NATIVE_TIMEOUT_MS = 60_000;
350
+
351
+ function createNative({
352
+ kind, voice, shell = 'powershell.exe', voices = [], api = null, timeoutMs = NATIVE_TIMEOUT_MS,
353
+ }) {
337
354
  const bin = kind === 'say' ? 'say' : shell;
338
355
  // on Windows the API decides the voices: WinRT sees the natural ones,
339
356
  // System.Speech only the 2006 roster — detectLocalVoice chose, and the
@@ -369,7 +386,11 @@ function createNative({ kind, voice, shell = 'powershell.exe', voices = [], api
369
386
  const dir = mkdtempSync(join(tmpdir(), 'decklight-native-'));
370
387
  const file = join(dir, 'out.wav');
371
388
  try {
372
- execFileSync(bin, build(line, pick, file), { stdio: ['ignore', 'ignore', 'pipe'] });
389
+ // SIGKILL, not the default SIGTERM: a wedged synthesizer is blocked in a
390
+ // syscall and a polite signal is exactly what it is not answering.
391
+ execFileSync(bin, build(line, pick, file), {
392
+ stdio: ['ignore', 'ignore', 'pipe'], timeout: timeoutMs, killSignal: 'SIGKILL',
393
+ });
373
394
  const wav = readFileSync(file);
374
395
  if (!wav.length) throw new Error(`${kind} produced no audio`);
375
396
  // `{ wav, usage }`, like every other engine and like this file's own
@@ -384,6 +405,15 @@ function createNative({ kind, voice, shell = 'powershell.exe', voices = [], api
384
405
  usage: { model: pick ?? kind, chars: line.length, cost: 0, note: `${line.length} chars · local` },
385
406
  };
386
407
  } catch (e) {
408
+ // A timeout is not "synthesis failed": the words were fine, the daemon
409
+ // is stuck, and the fix is a restart of IT — say so, or the next thing
410
+ // the person tries is rewording the sentence.
411
+ if (e.code === 'ETIMEDOUT' || e.signal === 'SIGKILL') {
412
+ throw new Error(`${kind} hung for ${Math.round(timeoutMs / 1000)}s and was killed — `
413
+ + (kind === 'say'
414
+ ? 'macOS\'s speech synthesizer can deadlock under concurrent calls; retry, or restart it: killall speechsynthesisd'
415
+ : 'the speech stack is not answering; retry'));
416
+ }
387
417
  throw new Error(`${kind}: ${String(e.stderr ?? e.message).trim().split('\n')[0] || 'synthesis failed'}`);
388
418
  } finally {
389
419
  rmSync(dir, { recursive: true, force: true });
@@ -397,6 +427,9 @@ export function createEngine({
397
427
  // built — and its voice handling asserted — on a machine that is not the one
398
428
  // the test happens to run on.
399
429
  detect = detectLocalVoice,
430
+ // The wedge tripwire (NATIVE_TIMEOUT_MS), injectable so a test can prove it
431
+ // fires without waiting a minute for it to.
432
+ nativeTimeoutMs,
400
433
  } = {}) {
401
434
  if (!ENGINES.includes(engine)) {
402
435
  throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')},`
@@ -409,6 +442,12 @@ export function createEngine({
409
442
  const m = voice ?? PIPER_DEFAULT_VOICE;
410
443
  return {
411
444
  name: 'piper', model: m, needsProject: false, stylable: false,
445
+ // piper's synth takes only text: the model is loaded once and a
446
+ // per-sentence voice request does nothing. The clip cache keys on the
447
+ // MODEL for this engine and ignores the asked-for voice, or two runs
448
+ // under different --voice models would collide on one key (SPEC
449
+ // `NARRATION`).
450
+ voiceIsFixed: true,
412
451
  cost: 'free · offline',
413
452
  voices: [[m, 'local']],
414
453
  synth: createPiper({ voice: m, dataDir }),
@@ -429,6 +468,12 @@ export function createEngine({
429
468
  : 'other languages');
430
469
  return {
431
470
  name: engine, model: pick, needsProject: false, stylable: false,
471
+ // `model` here is the voice this process BOOTED with, not a model — and
472
+ // createNative honours a different voice per sentence, so the boot voice
473
+ // says nothing about how a given clip sounds. The cache keys on the
474
+ // spoken voice alone; including this would file one sentence in one
475
+ // voice under as many names as there are bridges (SPEC `NARRATION`).
476
+ modelIsDefaultVoice: true,
432
477
  cost: 'free · offline · already on this machine',
433
478
  // [name, flavor, group]: the quality category travels as a STRUCTURED
434
479
  // third element (best · good · average) and the picker draws it as a
@@ -436,13 +481,23 @@ export function createEngine({
436
481
  // neural voices with 1990s robots under names that reveal nothing. The
437
482
  // flavor stays the locale alone; repeating the category on every row
438
483
  // was the suffix wallpaper the separators replace.
439
- voices: (detected.voices ?? []).map((v) => [v.name, v.locale || 'system', groupOf(v)]),
484
+ // One cut, and only one: `Daniel` goes when `Daniel (Enhanced)` is on
485
+ // the same list, because that is one voice offered twice and the worse
486
+ // row is not a choice. Everything else stays — the robots and personas
487
+ // because the picker already folds them to a single EXPANDABLE row, and
488
+ // a voice like Samantha because sharing a language with a Premium one
489
+ // does not make her a duplicate of it. `pick` survives regardless: it
490
+ // may have been named on the command line. The GUARD below keeps the
491
+ // FULL roster — hiding a voice must not turn saying it into an error.
492
+ voices: withoutSupersededPlain(detected.voices ?? [], { keep: pick })
493
+ .map((v) => [v.name, v.locale || 'system', groupOf(v)]),
440
494
  // "download a Siri voice" rides the same channel every engine caveat
441
495
  // does: the bridge's startup line and the deck's toast on switching
442
496
  ...(detected.caveat ? { caveat: detected.caveat } : {}),
443
497
  synth: createNative({
444
498
  kind: engine, voice: pick, shell: detected.shell, voices: detected.voices ?? [],
445
499
  api: detected.api ?? null,
500
+ ...(nativeTimeoutMs ? { timeoutMs: nativeTimeoutMs } : {}),
446
501
  }),
447
502
  };
448
503
  }
@@ -466,7 +521,7 @@ export function createEngine({
466
521
  caveat: isV3
467
522
  ? 'eleven_v3: higher latency, more variable consistency, and ElevenLabs '
468
523
  + 'recommends prompts over ~250 characters — a live decklight sentence is '
469
- + 'shorter than that, so delivery may vary more than a ⇧V recording.'
524
+ + 'shorter than that, so delivery may vary more than a recorded take (V → Record this deck…).'
470
525
  : undefined,
471
526
  // the real roster arrives from the account; until it does the picker has
472
527
  // nothing truthful to show, which is better than thirty names it cannot say
@@ -27,6 +27,7 @@ import {
27
27
  } from './tts-engines.mjs';
28
28
  import { gcloudToken, validProjectId } from './gemini-tts.mjs';
29
29
  import { KEY_ENV as ELEVENLABS_KEY_ENV, apiKey as elevenLabsKey } from './elevenlabs-tts.mjs';
30
+ import { run, NETWORK_MS } from './exec.mjs';
30
31
 
31
32
  // The picker's preview default (SPEC PRESENTING) — the wizard's proof is the same
32
33
  // audio the deck's V picker previews.
@@ -54,8 +55,8 @@ export function saveTtsConfig(config, env = process.env) {
54
55
  /** The project gcloud is configured with — the prefill when $GOOGLE_CLOUD_PROJECT is unset. */
55
56
  export function gcloudConfigProject() {
56
57
  try {
57
- const out = execFileSync('gcloud', ['config', 'get-value', 'project'],
58
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
58
+ const out = run('gcloud', ['config', 'get-value', 'project'],
59
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: NETWORK_MS }).trim();
59
60
  return out && !out.startsWith('(') ? out : null; // '(unset)' when none
60
61
  } catch { return null; }
61
62
  }
package/tools/video.mjs CHANGED
@@ -32,7 +32,7 @@
32
32
  // in one extra load, because the grouping is the runtime's and a second counter
33
33
  // written here would be a copy that drifts.
34
34
 
35
- import { execFile, execFileSync, spawnSync } from 'node:child_process';
35
+ import { execFile, spawnSync } from 'node:child_process';
36
36
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
37
  import { tmpdir } from 'node:os';
38
38
  import { basename, join, relative, resolve, sep } from 'node:path';
@@ -40,8 +40,9 @@ import { promisify } from 'node:util';
40
40
  import { fileURLToPath } from 'node:url';
41
41
  import { chromeBin, chromeArgs } from './chrome.mjs';
42
42
  import { argReader, isMain } from './args.mjs';
43
- import { injectBeforeBodyEnd, sectionBodies } from './deck-html.mjs';
43
+ import { injectBeforeBodyEnd, sectionBodies, isHiddenSection } from './deck-html.mjs';
44
44
  import { serveForRender } from '../cli/present.mjs';
45
+ import { run as runBounded, PROBE_MS } from './exec.mjs';
45
46
 
46
47
  const run = promisify(execFile);
47
48
 
@@ -309,7 +310,7 @@ export function resolveNarration(deckPath, narrationDir) {
309
310
  }
310
311
 
311
312
  const have = (bin) => {
312
- try { execFileSync(bin, ['-version'], { stdio: 'ignore' }); return true; }
313
+ try { runBounded(bin, ['-version'], { stdio: 'ignore', timeout: PROBE_MS }); return true; }
313
314
  catch (e) { return e?.code !== 'ENOENT'; }
314
315
  };
315
316
 
@@ -422,7 +423,9 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
422
423
 
423
424
  // real durations, not the manifest's word count: ffprobe each audio file
424
425
  const durations = {};
426
+ const hidden = sectionBodies(html).map(isHiddenSection);
425
427
  for (let n = range.from; n <= range.to; n++) {
428
+ if (hidden[n - 1]) continue; // a hidden slide keeps its number and gets no frame
426
429
  const entry = narration?.slides?.[n - 1];
427
430
  // The slide's own audio AND its ⟨CLICK⟩ segments. Measured here rather
428
431
  // than trusted from the manifest, for the reason the per-slide durations
@@ -32,16 +32,16 @@
32
32
  // first, so /ping and /voices await that lookup rather than guessing.
33
33
  //
34
34
  // CORS is wide open (decks run on file://, origin "null") — the server binds
35
- // 127.0.0.1 only. Responses are cached in memory by (text, voice, style), so
36
- // stepping back through slides replays instantly and costs nothing.
35
+ // 127.0.0.1 only. Responses are cached in memory AND on disk (tools/tts-cache.mjs)
36
+ // by (engine, model, format, voice, style, text), so stepping back through
37
+ // slides replays instantly, a restarted bridge replays for free, and
38
+ // `decklight voiceover` reuses whatever this bridge already said.
37
39
 
38
40
  import { createServer } from 'node:http';
39
41
  import { createInterface } from 'node:readline/promises';
40
42
  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
43
  import { execFile } from 'node:child_process';
44
+ import { cacheHome, clipKey, createTtsCache, extFor } from './tts-cache.mjs';
45
45
 
46
46
  /**
47
47
  * The one exec a deck may trigger: open macOS's voice-download pane.
@@ -63,7 +63,6 @@ export function openVoiceSettings(exec = execFile, platform = process.platform)
63
63
  }
64
64
  exec('open', [VOICE_SETTINGS_URI], () => { /* fire and forget — Settings owns the rest */ });
65
65
  }
66
- import { createHash } from 'node:crypto';
67
66
  import { resolveEngine, engineBlocker, engineMenu, engineStatus, ENGINES } from './tts-engines.mjs';
68
67
  import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
69
68
  import { argReader, isMain } from './args.mjs';
@@ -96,10 +95,18 @@ async function askLine(prompt) {
96
95
  }
97
96
 
98
97
  export async function ttsMain(args) {
98
+ // A clean exit on SIGTERM, not the default abrupt one. The difference is
99
+ // invisible in production and decisive under test: V8 writes a process's
100
+ // coverage only when it exits through process.exit, so a bridge the suite
101
+ // stops with SIGKILL — or with an unhandled SIGTERM — reports NOTHING, and
102
+ // the request handler that is this file's whole point read as 27% covered
103
+ // while thirty tests drove it. The edit and present servers already do this.
104
+ process.on('SIGTERM', () => process.exit(0));
99
105
  if (args.includes('--help')) {
100
106
  console.log(`usage: decklight tts [--port 8787] [--engine ${ENGINES.join('|')}|<installed>] [--project <id>]
101
107
  [--tts-model id] [--location global] [--voice name] [--data-dir dir] [--lang en-US]
102
108
  [--tts-format pcm|mp3] [--tts-stability creative|natural|robust] [--setup]
109
+ [--no-cache]
103
110
 
104
111
  gemini gemini-2.5-pro-tts (default) or --tts-model gemini-2.5-flash-tts — Vertex AI, best
105
112
  delivery, the only engine that honors a style instruction. No free tier.
@@ -114,13 +121,20 @@ export async function ttsMain(args) {
114
121
  the picker's tone step appears for.
115
122
  --tts-stability creative|natural|robust — how hard v3 follows a tag (v3 only;
116
123
  refused on any other model rather than silently doing nothing).
117
- --tts-format mp3 if your plan has no PCM output (costs you ⇧V and lip-sync).
124
+ --tts-format mp3 if your plan has no PCM output (costs you the panel's
125
+ Record this deck… and lip-sync, both of which read WAV).
118
126
 
119
127
  <installed> any engine from a marketplace (decklight engine add <name>) — --engine
120
128
  takes its name like any of the six above, and the picker treats it the same.
121
129
 
122
130
  project also read from $GOOGLE_CLOUD_PROJECT (gemini and chirp only)
123
131
 
132
+ cache every synthesis is kept in ${cacheHome()} under a key made of
133
+ (engine, model, format, voice, style, text), so a restarted bridge
134
+ replays for free and 'decklight voiceover' reuses what you already
135
+ previewed instead of paying for it twice. Oldest clips are dropped
136
+ past 400 MB. --no-cache re-synthesizes everything, for a fresh take.
137
+
124
138
  first run: with nothing configured on a terminal, tts asks a few guided
125
139
  questions (engine, prerequisites, one test synthesis) and saves the answers
126
140
  to ${ttsConfigPath()} — --setup re-runs them.
@@ -218,42 +232,16 @@ export async function ttsMain(args) {
218
232
  // engine's audio under another's voice — the cache survives the switch, and
219
233
  // switching back replays instantly rather than re-billing.
220
234
  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 */ }
235
+ // The DISK half (tools/tts-cache.mjs), for EVERY engine including the paid
236
+ // ones. Warming 184 say previews took ~6 minutes of background synthesis and
237
+ // should cost that once per machine rather than once per bridge — and an
238
+ // ElevenLabs sentence should be paid for once per sentence, not once per
239
+ // process, which is what a memory-only cache charged for a preview here and
240
+ // a batch recording ten minutes later. The MODEL is in the key, so a cloud
241
+ // engine changing its model underneath us is a miss rather than a stale clip.
242
+ // `--no-cache` opts out for a deliberate re-roll.
243
+ const disk = createTtsCache({ enabled: !args.includes('--no-cache') });
244
+ disk.prune();
257
245
 
258
246
  // What the bridge could become, and what stands in the way. The options the
259
247
  // deck's picker draws (SPEC `NARRATION`).
@@ -387,18 +375,16 @@ export async function ttsMain(args) {
387
375
  const { text, voice: picked, style } = JSON.parse((await readBody(req)).toString());
388
376
  if (!text?.trim()) { res.writeHead(400, CORS); return res.end('no text'); }
389
377
  const voice = refIds.get(picked) ?? picked;
390
- // NUL joins the fields so they cannot run together (a style ending in a
391
- // space and a text starting with one must not hash like their neighbours)
392
- // — but written as an ESCAPE, not a raw byte. This file used to carry
393
- // literal NULs, and git calls any file with one in its first 8 KB binary:
394
- // it silently became undiffable and unreviewable.
395
- const key = createHash('sha256')
396
- .update([engine.name, voice, style, text].join('\u0000')).digest('hex');
378
+ // The key is the SAME function `decklight voiceover` hashes with, and
379
+ // that is the point: a sentence previewed here and then batch-recorded
380
+ // is one synthesis, not two identical bills (SPEC `NARRATION`).
381
+ const ext = extFor(engine.synth.mimeType ?? 'audio/wav');
382
+ const key = clipKey(engine, { voice, style, text });
397
383
  let fresh = !cache.has(key);
398
384
  if (fresh) {
399
- const onDisk = diskRead(key);
400
- if (onDisk) {
401
- cache.set(key, onDisk);
385
+ const bytes = disk.read(key, ext);
386
+ if (bytes) {
387
+ cache.set(key, { wav: bytes, usage: { chars: 0, cost: 0, note: 'cached on disk' } });
402
388
  fresh = false;
403
389
  console.log(` ${engine.name} ${picked}: ${text.length} chars · cached on disk`);
404
390
  }
@@ -407,7 +393,7 @@ export async function ttsMain(args) {
407
393
  process.stdout.write(` ${engine.name} ${picked}: ${text.length} chars … `);
408
394
  const t0 = Date.now();
409
395
  cache.set(key, await engine.synth(text, { voice, style }));
410
- diskWrite(key, cache.get(key).wav);
396
+ disk.write(key, cache.get(key).wav, ext);
411
397
  const u = cache.get(key).usage;
412
398
  // `cost` is OPTIONAL, and an installed engine is why (SPEC
413
399
  // ENGINE_UNITS): the six built-ins all happen to report one, so
@@ -48,8 +48,10 @@ import { execFileSync } from 'node:child_process';
48
48
  import { resolve, join, basename } from 'node:path';
49
49
  import { homedir } from 'node:os';
50
50
  import { createEngine } from './tts-engines.mjs';
51
+ import { clipKey, createTtsCache, extFor } from './tts-cache.mjs';
51
52
  import { argReader } from './args.mjs';
52
- import { sectionBodies, NOTES_ASIDE, cleanNotes, notesSegments } from './deck-html.mjs';
53
+ import { sectionBodies, NOTES_ASIDE, cleanNotes, notesSegments, isHiddenSection } from './deck-html.mjs';
54
+ import { run, PROBE_MS, CODEC_MS } from './exec.mjs';
53
55
 
54
56
  const args = process.argv.slice(2);
55
57
 
@@ -58,8 +60,9 @@ const HELP = `decklight voiceover — batch-synthesize a deck's narration into a
58
60
  Usage:
59
61
  decklight voiceover <deck.html> [-o <dir>] [--engine piper|chirp|gemini|elevenlabs]
60
62
  [--voice <name>] [--no-llm] [--reuse-text] [--keep-wav]
63
+ [--no-cache]
61
64
 
62
- The headless counterpart of the deck's \u21e7V: it reads each slide's speaker
65
+ The headless counterpart of the deck's V \u2192 Record this deck\u2026: it reads each slide's speaker
63
66
  notes and writes one slide-NN.m4a per slide (plus a file per \u27e8CLICK\u27e9 beat)
64
67
  and a manifest.json into <dir>, so a deck can point at it with
65
68
  narration: { files: [{ label, dir, segments: true }] }.
@@ -72,6 +75,12 @@ narration: { files: [{ label, dir, segments: true }] }.
72
75
  --reuse-text re-voice the existing slide-NN.txt without re-rolling the text
73
76
  — switch voices or engines without a new narration pass
74
77
  --keep-wav keep the lossless WAVs (tools/lipsync.mjs consumes them)
78
+ --no-cache re-synthesize every slide, ignoring the shared clip cache
79
+
80
+ Synthesis is cached on disk (~/.cache/decklight/tts) under a key made of
81
+ (engine, model, format, voice, style, text) — the SAME key the live bridge
82
+ uses, so a sentence you previewed in the deck is recorded here for free
83
+ instead of being billed a second time.
75
84
 
76
85
  Cloud engines need --project or $GOOGLE_CLOUD_PROJECT and application-default
77
86
  credentials; elevenlabs needs $ELEVENLABS_API_KEY. Audio is a build artifact.`;
@@ -95,6 +104,7 @@ const model = opt('--model', 'qwen3:30b-a3b');
95
104
  const useLlm = !args.includes('--no-llm');
96
105
  const reuseText = args.includes('--reuse-text');
97
106
  const keepWav = args.includes('--keep-wav');
107
+ const useCache = !args.includes('--no-cache');
98
108
 
99
109
  // one factory, three engines — the same ones the live bridge speaks with
100
110
  let tts;
@@ -113,21 +123,22 @@ try {
113
123
  // macOS — probing in that order keeps this working off a Mac (as tools/lipsync.mjs
114
124
  // already does), and both engines' output goes through here.
115
125
  const have = (bin, flags = ['-version']) => {
116
- try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
126
+ try { run(bin, flags, { stdio: 'ignore', timeout: PROBE_MS }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
117
127
  };
118
128
  const encoder = have('ffmpeg') ? 'ffmpeg' : have('afconvert') ? 'afconvert' : null;
119
129
  if (!encoder) {
120
130
  console.error('no AAC encoder — install ffmpeg (apt install ffmpeg / brew install ffmpeg)');
121
131
  process.exit(1);
122
132
  }
123
- const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
133
+ const toAac = (wav, m4a) => run(encoder, encoder === 'ffmpeg'
124
134
  ? ['-y', '-i', wav, '-c:a', 'aac', '-b:a', '128k', m4a]
125
- : ['-f', 'm4af', '-d', 'aac', wav, m4a], { stdio: 'ignore' });
135
+ : ['-f', 'm4af', '-d', 'aac', wav, m4a], { stdio: 'ignore', timeout: CODEC_MS, why: 'the encoder is stuck on this file — check it plays, then retry' });
126
136
 
127
137
  // ── extract per-slide narration text ─────────────────────────────────────────
128
138
  const html = readFileSync(deckPath, 'utf8');
129
139
  const sections = sectionBodies(html);
130
140
  const raw = sections.map((sec) => {
141
+ if (isHiddenSection(sec)) return ''; // no file for a hidden slide; the numbering stays
131
142
  const aside = sec.match(NOTES_ASIDE);
132
143
  if (aside) return aside[1];
133
144
  const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
@@ -174,12 +185,71 @@ function narrate(text, slideNo) {
174
185
  }
175
186
 
176
187
  // ── synthesize ────────────────────────────────────────────────────────────────
177
- // Incremental: the manifest stores a hash of (engine, voice, style, text) per
178
- // slide, so a rerun only synthesizes slides whose narration actually changed.
188
+ // TWO layers of reuse, and they answer different questions.
189
+ //
190
+ // The MANIFEST answers "is this folder already correct?" — a hash per slide,
191
+ // so a rerun re-synthesizes only the slides whose narration actually changed
192
+ // and leaves the rest of the .m4a files alone.
193
+ //
194
+ // The CLIP CACHE (tools/tts-cache.mjs) answers "has anyone, ever, paid for
195
+ // these exact words?" — it is keyed by content rather than by folder, so it
196
+ // survives a different -o, a deleted manifest, and above all the process
197
+ // boundary: the live bridge fills the same cache while you preview the deck,
198
+ // and this run collects it. An ElevenLabs deck used to be billed twice for
199
+ // that, once in the browser and once here.
200
+ //
201
+ // Both keys carry the same fields, and the reason is one bug rather than two:
202
+ // anything that changes the AUDIO must change the key. `model` is in them
203
+ // because `--tts-model eleven_v3` is a different voice performance of the same
204
+ // words, and a hash without it skipped the slide and kept the old take. STYLE
205
+ // is in them only when the engine can act on it — every engine but gemini and
206
+ // ElevenLabs v3 ignores the instruction entirely, and letting a style the
207
+ // engine never read change the hash would miss the bridge's own clip for no
208
+ // audible reason.
179
209
  mkdirSync(outDir, { recursive: true });
180
210
  let totalCost = 0;
181
- const slideHash = (text) =>
182
- createHash('sha256').update(`${engine}|${voice}|${style}|${text}`).digest('hex').slice(0, 16);
211
+ const audioExt = extFor(tts.synth.mimeType ?? 'audio/wav');
212
+ const clips = createTtsCache({ enabled: useCache });
213
+ clips.prune();
214
+ // `--voice` omitted on ElevenLabs means "the first of your voices", and the
215
+ // deck's picker offers that same roster in that same order — so the name is
216
+ // resolved HERE, for the key. Left undefined it would hash differently from
217
+ // the identical sentence the bridge just synthesized, and the cross-process
218
+ // reuse this cache exists for would silently never hit.
219
+ let keyVoice = voice;
220
+ if (!keyVoice && tts.listVoices) {
221
+ try { keyVoice = (await tts.listVoices())[0]?.name; } catch { /* keep it undefined */ }
222
+ }
223
+
224
+ /** `tts.synth`, but a sentence anyone has already paid for is free. */
225
+ async function synth(text) {
226
+ const key = clipKey(tts, { voice: keyVoice, style, text });
227
+ const hit = clips.read(key, audioExt);
228
+ if (hit) return { wav: hit, usage: { chars: 0, cost: 0 }, cached: true };
229
+ const out = await tts.synth(text, { voice, style });
230
+ clips.write(key, out.wav, audioExt);
231
+ return { ...out, cached: false };
232
+ }
233
+ // The manifest hash is the CLIP KEY, shortened: one definition of "the same
234
+ // audio", so the folder-level skip and the content-level cache can never
235
+ // disagree about whether a slide changed.
236
+ const slideHash = (text) => clipKey(tts, { voice: keyVoice, style, text }).slice(0, 16);
237
+ // ONE-TIME MIGRATION. The hash above gained `model` and lost the style no
238
+ // engine reads, so every folder recorded before this change hashes differently
239
+ // — and a folder that hashes differently is re-synthesized in full. That audio
240
+ // is not stale; it is exactly what today's key describes, and re-rolling it
241
+ // would hand an ElevenLabs user a bill for clips already on their disk.
242
+ //
243
+ // So a slide matching the OLD formula is accepted once and re-stamped. The
244
+ // gate is `prev.model === undefined`: only a manifest written before this
245
+ // change lacks that field, so the allowance cannot be claimed twice, and a
246
+ // later `--tts-model` switch is a genuine miss again. The one case it lets
247
+ // through is changing the model in the SAME run as the upgrade — narrow, and
248
+ // `--no-cache` is the way out of it.
249
+ const legacyHash = (text) => createHash('sha256')
250
+ .update(`${engine}|${voice}|${style}|${text}`).digest('hex').slice(0, 16);
251
+ const preDatesModel = (m) => m && m.model === undefined
252
+ && m.engine === engine && m.voice === voice && m.style === style;
183
253
  let prev = null;
184
254
  try {
185
255
  const m = JSON.parse(readFileSync(join(outDir, 'manifest.json'), 'utf8'));
@@ -201,7 +271,8 @@ for (let i = 0; i < slides.length; i++) {
201
271
  writeFileSync(txt, text);
202
272
  const hash = slideHash(text);
203
273
  manifest.push({ file: `slide-${n}.m4a`, hash });
204
- if (prev?.slides?.[i]?.hash === hash && existsSync(m4a)) {
274
+ const stamped = prev?.slides?.[i]?.hash;
275
+ if ((stamped === hash || (preDatesModel(prev) && stamped === legacyHash(text))) && existsSync(m4a)) {
205
276
  // Carry the segments across, or an unchanged slide loses its build sync on
206
277
  // the next rerun: the audio is still on disk and the manifest is the only
207
278
  // thing that knows it is there.
@@ -218,13 +289,15 @@ for (let i = 0; i < slides.length; i++) {
218
289
  // path, since its prior text is one script rather than segments.
219
290
  const segs = prior ? null : segmented[i];
220
291
  let usage = { cost: 0 };
292
+ let cachedBeats = 0;
221
293
  if (segs) {
222
294
  const parts = [];
223
295
  for (let k = 0; k < segs.length; k++) {
224
296
  const kk = String(k + 1).padStart(2, '0');
225
297
  const sWav = join(outDir, `slide-${n}-${kk}.wav`);
226
298
  const sM4a = join(outDir, `slide-${n}-${kk}.m4a`);
227
- const out = await tts.synth(segs[k], { voice, style });
299
+ const out = await synth(segs[k]);
300
+ if (out.cached) cachedBeats++;
228
301
  writeFileSync(sWav, out.wav);
229
302
  // The beat's own words, beside its own audio — tools/lipsync.mjs hands
230
303
  // this to Rhubarb as the dialog hint, and a hint for the whole slide
@@ -237,12 +310,13 @@ for (let i = 0; i < slides.length; i++) {
237
310
  }
238
311
  const list = join(outDir, `slide-${n}.concat`);
239
312
  writeFileSync(list, `${parts.map((p) => `file '${p.path.replaceAll("'", "'\\''")}'`).join('\n')}\n`);
240
- execFileSync('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', m4a],
313
+ run('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', m4a],
241
314
  { stdio: 'ignore' });
242
315
  rmSync(list, { force: true });
243
316
  manifest[i].segments = parts.map((p) => ({ file: p.file }));
244
317
  } else {
245
- const out = await tts.synth(text, { voice, style });
318
+ const out = await synth(text);
319
+ if (out.cached) cachedBeats++;
246
320
  writeFileSync(wav, out.wav);
247
321
  usage = out.usage ?? { cost: 0 };
248
322
  toAac(wav, m4a);
@@ -250,15 +324,20 @@ for (let i = 0; i < slides.length; i++) {
250
324
  }
251
325
  totalCost += usage.cost ?? 0;
252
326
  const costNote = usage.cost ? ` · ~$${usage.cost.toFixed(4)}` : '';
327
+ // "cached" is worth a word: on a paid engine it is the difference between a
328
+ // rerun that costs nothing and one that quietly re-bills the whole deck
329
+ const cacheNote = cachedBeats
330
+ ? ` · ${segs ? `${cachedBeats}/${segs.length} ` : ''}cached`
331
+ : '';
253
332
  console.log(` slide ${n}: ${text.length} chars → ${basename(m4a)}`
254
- + `${segs ? ` (${segs.length} ⟨CLICK⟩ segments)` : ''}${costNote}`);
333
+ + `${segs ? ` (${segs.length} ⟨CLICK⟩ segments)` : ''}${cacheNote}${costNote}`);
255
334
  // crash-safe: persist progress after every slide so an interrupted run
256
335
  // resumes incrementally instead of re-synthesizing everything
257
336
  writeFileSync(join(outDir, 'manifest.json'),
258
- JSON.stringify({ engine, voice, style, slides: manifest }, null, 1));
337
+ JSON.stringify({ engine, model: tts.model ?? null, voice, style, slides: manifest }, null, 1));
259
338
  }
260
339
  writeFileSync(join(outDir, 'manifest.json'),
261
- JSON.stringify({ engine, voice, style, slides: manifest }, null, 1));
340
+ JSON.stringify({ engine, model: tts.model ?? null, voice, style, slides: manifest }, null, 1));
262
341
  // piper is held resident (§ createPiper) — without this the tool prints `done`
263
342
  // and then hangs on the live child process
264
343
  tts.synth.close?.();