decklight 0.7.0 → 0.8.1

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.
@@ -0,0 +1,191 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The synthesis cache on disk — one clip per (engine, model, format, voice,
6
+ * style, text), shared by everything that speaks.
7
+ *
8
+ * It lived inside tools/voiceover-server.mjs and served only the free local
9
+ * engines, on the argument that a cloud engine's output drifts with the
10
+ * server's model and a stale clip is worse than re-billing one preview
11
+ * sentence. That argument was answering the wrong question: it treated the
12
+ * MODEL as invisible, so the only way to avoid serving audio from last
13
+ * quarter's model was to keep no audio at all. Put the model in the key and
14
+ * the drift is not a risk, it is a cache miss — a new model is new bytes under
15
+ * a new name, and yesterday's clip is unreachable rather than wrong.
16
+ *
17
+ * What that buys is the thing the memory cache never could: the live bridge
18
+ * and `decklight voiceover` are SEPARATE PROCESSES, so a deck previewed
19
+ * sentence by sentence in the browser and then batch-recorded paid ElevenLabs
20
+ * twice for identical text. They now meet here, because the key is derived
21
+ * from what was said and how — not from who is asking.
22
+ *
23
+ * The key deliberately does NOT include the deck, the slide number or the
24
+ * output directory. The same sentence in two decks is the same audio, and a
25
+ * second take into a different `-o` should cost nothing.
26
+ *
27
+ * Nothing here throws. A cache that cannot be read is a cache miss and a cache
28
+ * that cannot be written is a cache — read-only media, a full disk and a
29
+ * locked-down $HOME all degrade to "synthesize it again", never to a failed
30
+ * talk.
31
+ */
32
+
33
+ import { createHash } from 'node:crypto';
34
+ import { mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
35
+ import { homedir } from 'node:os';
36
+ import { join } from 'node:path';
37
+
38
+ /**
39
+ * How much audio is allowed to accumulate before the oldest is dropped.
40
+ *
41
+ * A per-sentence cache grows forever, and a silent 10 GB in ~/.cache is not a
42
+ * cache, it is a leak with a euphemism.
43
+ */
44
+ export const CACHE_LIMIT = 400 * 1024 * 1024;
45
+
46
+ /** Where clips live. `$XDG_CACHE_HOME` wins, so a test never touches the real one. */
47
+ export function cacheHome(env = process.env) {
48
+ return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'decklight', 'tts');
49
+ }
50
+
51
+ /**
52
+ * The file extension for what an engine returned.
53
+ *
54
+ * ElevenLabs' `--tts-format mp3` is the only path that is not a WAV, and
55
+ * filing an mp3 under `.wav` would make the cache dir a pile of lies — playable
56
+ * by nothing that trusts the name, prunable only by accident.
57
+ */
58
+ export function extFor(mime) {
59
+ return mime === 'audio/mpeg' ? 'mp3' : 'wav';
60
+ }
61
+
62
+ /** Every extension the cache is allowed to own, for pruning. */
63
+ export const CACHE_EXTS = ['.wav', '.mp3'];
64
+
65
+ /**
66
+ * The name a clip is filed under.
67
+ *
68
+ * Everything that changes the AUDIO is in here and nothing else is. `model` is
69
+ * the addition that lets cloud engines be cached at all; `format` is here
70
+ * because pcm and mp3 of one sentence are different bytes with the same words.
71
+ *
72
+ * NUL joins the fields so they cannot run together — a style ending in a space
73
+ * and a text starting with one must not hash like their neighbours — but
74
+ * written as an ESCAPE, not a raw byte: git calls any file with a NUL in its
75
+ * first 8 KB binary, and this file would silently become undiffable.
76
+ */
77
+ export function cacheKey({ engine, model, format, voice, style, text } = {}) {
78
+ return createHash('sha256')
79
+ .update([engine, model, format, voice, style, text].map((f) => f ?? '').join('\u0000'))
80
+ .digest('hex');
81
+ }
82
+
83
+ /**
84
+ * The key for one sentence on one ENGINE — the form both callers use.
85
+ *
86
+ * `cacheKey` above takes loose fields, which is what makes it testable; this
87
+ * takes the engine object and derives them, which is what makes the live
88
+ * bridge and `decklight voiceover` agree. They used to assemble the fields
89
+ * separately, and separately is how a cache that spans two processes quietly
90
+ * stops hitting: one of them starts sending a field the other does not, every
91
+ * lookup misses, and nothing fails — you just pay twice again.
92
+ *
93
+ * Two rules are worth naming, because both were bugs before they were rules.
94
+ *
95
+ * WHAT `model` MEANS DIFFERS BY ENGINE, and only gemini, chirp and ElevenLabs
96
+ * mean by it what the word says. For say and SAPI it is the voice the process
97
+ * booted with, while the voice that actually speaks arrives per sentence — so
98
+ * a bridge started without `--voice` and a recorder started with one hashed
99
+ * the same sentence, in the same voice, two different ways, and the batch
100
+ * recording missed every clip the browser had just filed. For piper it is the
101
+ * loaded model and the per-sentence voice is ignored entirely, which is the
102
+ * opposite mistake: keying on the request would let two runs under different
103
+ * `--voice` models collide on one key and serve the wrong voice. Each engine
104
+ * declares which it is (`modelIsDefaultVoice`, `voiceIsFixed`) rather than
105
+ * this file guessing from the name.
106
+ *
107
+ * STYLE only counts when the engine can act on it. Only gemini and ElevenLabs
108
+ * v3 read a delivery instruction; the rest are handed one and ignore it. The
109
+ * bridge gets its style from the deck (usually none) and the CLI defaults to a
110
+ * paragraph about a warm senior engineer — so keying on a style neither engine
111
+ * read would make identical audio hash two ways. `stylable` is the engine's
112
+ * own answer to "can this change the sound", and only then does it change the
113
+ * name.
114
+ */
115
+ export function clipKey(engine, { voice, style, text } = {}) {
116
+ // The voice that will SPEAK this sentence, and the model that will speak it
117
+ // — never the same axis twice, and never an axis the engine does not have.
118
+ const voiceId = engine?.voiceIsFixed ? engine?.model
119
+ : engine?.modelIsDefaultVoice ? (voice ?? engine?.model)
120
+ : voice;
121
+ const modelId = (engine?.voiceIsFixed || engine?.modelIsDefaultVoice) ? undefined : engine?.model;
122
+ return cacheKey({
123
+ engine: engine?.name,
124
+ model: modelId,
125
+ format: extFor(engine?.synth?.mimeType ?? 'audio/wav'),
126
+ voice: voiceId,
127
+ style: engine?.stylable ? style : undefined,
128
+ text,
129
+ });
130
+ }
131
+
132
+ /**
133
+ * A cache bound to a directory.
134
+ *
135
+ * `enabled: false` returns the same shape doing nothing, so a caller never
136
+ * grows an `if` around every read and write — `--no-cache` is one construction
137
+ * argument rather than a condition threaded through two files.
138
+ */
139
+ export function createTtsCache({ dir = cacheHome(), limit = CACHE_LIMIT, enabled = true } = {}) {
140
+ const path = (key, ext) => join(dir, `${key}.${ext}`);
141
+
142
+ /** The clip, or null. A miss and an unreadable file are the same answer. */
143
+ function read(key, ext = 'wav') {
144
+ if (!enabled) return null;
145
+ try {
146
+ const bytes = readFileSync(path(key, ext));
147
+ return bytes.length ? bytes : null;
148
+ } catch { return null; }
149
+ }
150
+
151
+ /** File a clip. Empty audio is never cached: it would poison the key forever. */
152
+ function write(key, bytes, ext = 'wav') {
153
+ if (!enabled || !bytes?.length) return false;
154
+ try {
155
+ mkdirSync(dir, { recursive: true });
156
+ writeFileSync(path(key, ext), bytes);
157
+ return true;
158
+ } catch { return false; }
159
+ }
160
+
161
+ /**
162
+ * Drop the oldest clips until the directory fits.
163
+ *
164
+ * Called once at startup rather than on every write: the bound is on what a
165
+ * machine keeps, not on what a single run may add, and stat-ing the whole
166
+ * directory per sentence would cost more than the synthesis it saves.
167
+ *
168
+ * Oldest-first by mtime also retires stale keys for free. Changing the key
169
+ * formula (adding `model`, say) orphans every clip filed under the old one;
170
+ * those are by definition never touched again, so they age to the front of
171
+ * this queue and leave on their own.
172
+ */
173
+ function prune() {
174
+ if (!enabled) return 0;
175
+ try {
176
+ const entries = readdirSync(dir)
177
+ .filter((f) => CACHE_EXTS.some((e) => f.endsWith(e)))
178
+ .map((f) => ({ f, ...statSync(join(dir, f)) }))
179
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
180
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
181
+ let dropped = 0;
182
+ for (const e of entries) {
183
+ if (total <= limit) break;
184
+ try { unlinkSync(join(dir, e.f)); total -= e.size; dropped++; } catch { break; }
185
+ }
186
+ return dropped;
187
+ } catch { return 0; }
188
+ }
189
+
190
+ return { dir, enabled, read, write, prune };
191
+ }
@@ -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