decklight 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +20 -9
  2. package/SPEC.md +239 -17
  3. package/cli/agents.mjs +97 -2
  4. package/cli/banner.mjs +125 -0
  5. package/cli/bundle.mjs +14 -4
  6. package/cli/{rec.mjs → cast.mjs} +25 -8
  7. package/cli/comments.mjs +389 -0
  8. package/cli/commit-flow.mjs +157 -0
  9. package/cli/commit-message.mjs +475 -0
  10. package/cli/decklight.mjs +95 -25
  11. package/cli/dev.mjs +193 -25
  12. package/cli/edit.mjs +1055 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +370 -0
  15. package/cli/history.mjs +145 -0
  16. package/cli/init.mjs +199 -7
  17. package/cli/marketplace.mjs +123 -17
  18. package/cli/port-conflict.mjs +228 -22
  19. package/cli/present.mjs +297 -12
  20. package/cli/publish.mjs +15 -40
  21. package/cli/record.mjs +154 -0
  22. package/cli/restore.mjs +120 -4
  23. package/cli/review-remote.mjs +330 -0
  24. package/cli/review-store.mjs +107 -0
  25. package/cli/review-submit.mjs +292 -0
  26. package/cli/review.mjs +361 -0
  27. package/cli/serve.mjs +60 -1
  28. package/cli/skill-content.mjs +12 -1
  29. package/cli/theme.mjs +78 -11
  30. package/cli/units.mjs +2 -2
  31. package/cli/upstream.mjs +256 -0
  32. package/cli/util.mjs +59 -0
  33. package/dist/build-info.json +1 -0
  34. package/dist/decklight.css +534 -3
  35. package/dist/decklight.js +102 -76
  36. package/dist/decklight.js.map +4 -4
  37. package/docs/architecture.svg +7 -0
  38. package/package.json +2 -1
  39. package/tools/args.mjs +20 -0
  40. package/tools/deck-html.mjs +84 -0
  41. package/tools/elevenlabs-tts.mjs +1 -1
  42. package/tools/lipsync-server.mjs +64 -2
  43. package/tools/lipsync.mjs +40 -24
  44. package/tools/local-voice.mjs +170 -16
  45. package/tools/publish-voices.mjs +78 -18
  46. package/tools/recording-impact.mjs +110 -0
  47. package/tools/review-anchor.mjs +180 -0
  48. package/tools/test-impact.mjs +259 -0
  49. package/tools/tts-engines.mjs +211 -12
  50. package/tools/tts-setup.mjs +2 -9
  51. package/tools/video.mjs +56 -12
  52. package/tools/voiceover-server.mjs +262 -11
  53. package/tools/voiceover.mjs +32 -13
@@ -64,6 +64,13 @@
64
64
  </g>
65
65
 
66
66
  <!-- ── verification band ────────────────────────────────────────── -->
67
+ <!-- decklight review — a third localhost server, and the only one whose write
68
+ surface is a single sidecar file (SPEC REVIEW) -->
69
+ <rect x="710" y="356" width="180" height="86" rx="10" fill="#274035" stroke="#43695a" stroke-width="1.5"/>
70
+ <text x="800" y="382" text-anchor="middle" font-size="13" font-weight="700" fill="#e8eaf2">decklight review</text>
71
+ <text x="800" y="400" text-anchor="middle" font-size="10.5" fill="#aeb4c6">M leaves comments on a slide</text>
72
+ <text x="800" y="416" text-anchor="middle" font-size="10.5" fill="#aeb4c6">writes deck.review.jsonl only</text>
73
+ <text x="800" y="432" text-anchor="middle" font-size="10.5" fill="#aeb4c6">git carries it · no /edit/*</text>
67
74
  <rect x="40" y="470" width="850" height="60" rx="10" fill="#1c2620" stroke="#39584a" stroke-width="1.5"/>
68
75
  <text x="465" y="494" text-anchor="middle" font-size="12.5" font-weight="700" fill="#9fd6b4">verification — SPEC.md is the contract</text>
69
76
  <text x="465" y="514" text-anchor="middle" font-size="10.5" fill="#8fae9c">WCAG contrast gates · R1–R8 palette rules · headless render assertions · property tests across seeds · data-overflow guardrail</text>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.5.0",
3
+ "version": "0.7.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",
@@ -38,6 +38,7 @@
38
38
  "prepare": "npm run build",
39
39
  "test": "node test/run.mjs",
40
40
  "verify": "npm run build && node test/verify.mjs",
41
+ "test:impact": "node tools/test-impact.mjs",
41
42
  "soak": "node test/soak.mjs",
42
43
  "cross-engine": "node test/cross-engine.mjs"
43
44
  },
package/tools/args.mjs CHANGED
@@ -23,6 +23,26 @@ export function argReader(argv) {
23
23
  return { opt, opts };
24
24
  }
25
25
 
26
+ /**
27
+ * The first REAL positional — the first arg that neither starts with `-` nor
28
+ * is the value of a value-taking flag.
29
+ *
30
+ * `opt()` above reads a flag's value without consuming it, so a command that
31
+ * also does `args.find((a) => !a.startsWith('-'))` disagrees with its own flag
32
+ * reader: `--port 8790 deck.html` hands it "8790" as the deck, and the refusal
33
+ * says `no such deck: 8790`, which blames a file nobody named. Every dispatch
34
+ * that takes both flags-with-values and a positional goes through this, with
35
+ * the SAME flag list it reads values from.
36
+ *
37
+ * Deliberately not a file-extension test: `record` wants to SEE a `.yaml`
38
+ * positional so it can say "that is a cast, not a deck" — a filter that only
39
+ * passes `.html` would eat the very mistake the message exists for.
40
+ */
41
+ export function firstPositional(argv, valueFlags = []) {
42
+ const takesValue = new Set(valueFlags);
43
+ return argv.find((a, i) => !a.startsWith('-') && !takesValue.has(argv[i - 1]));
44
+ }
45
+
26
46
  /**
27
47
  * True when this module file was run directly (`node tools/x.mjs`), false when
28
48
  * imported. Path-resolved so it survives relative paths, symlinks and Windows —
@@ -21,6 +21,90 @@ 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
+ * A section body from `sectionBodies`, reduced to what is actually inside the
26
+ * section.
27
+ *
28
+ * `sectionBodies` splits on `<section` and keeps everything after it, so each
29
+ * piece begins with the REST OF THE OPEN TAG (` class="x">`) and ends with the
30
+ * closing tag and whatever follows. A DOM reader never sees either. Anything
31
+ * comparing the two — the review fingerprint does — has to drop them, or the
32
+ * file side hashes a stray `>` that the browser side cannot produce.
33
+ */
34
+ export const sectionInner = (body) => {
35
+ const s = String(body ?? '');
36
+ const open = s.indexOf('>');
37
+ const inner = open === -1 ? s : s.slice(open + 1);
38
+ const close = inner.toLowerCase().lastIndexOf('</section>');
39
+ return close === -1 ? inner : inner.slice(0, close);
40
+ };
41
+
42
+ /**
43
+ * A slide's own text, as the fingerprint that anchors review comments sees it
44
+ * (SPEC REVIEW) — the file-reading twin of `slideBody` in src/core/finder.js.
45
+ *
46
+ * Asides are dropped before anything else: a comment is about what the audience
47
+ * sees, so an author rewriting their own speaker notes must not orphan every
48
+ * comment on the slide. Scripts and styles go for the same reason the DOM side
49
+ * filters them — they are machinery, not content.
50
+ *
51
+ * The two sides do NOT have to agree about spacing, because `fingerprint`
52
+ * removes whitespace rather than collapsing it. They do have to agree about
53
+ * what counts as content, which is what this shares with its DOM twin.
54
+ */
55
+ export const slideText = (sectionBody) => String(sectionBody ?? '')
56
+ .replace(/<aside\b[\s\S]*?<\/aside>/gi, ' ')
57
+ .replace(/<script\b[\s\S]*?<\/script>/gi, ' ')
58
+ .replace(/<style\b[\s\S]*?<\/style>/gi, ' ')
59
+ .replace(/<[^>]+>/g, ' ')
60
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
61
+ .replace(/\s+/g, ' ')
62
+ .trim();
63
+
64
+ /**
65
+ * A slide's title as the finder and the comment list both name it: the first
66
+ * heading, else its opening words. The file-reading twin of `slideTitle`.
67
+ */
68
+ export const slideHeading = (sectionBody, i) => {
69
+ const h = /<h[1-3]\b[^>]*>([\s\S]*?)<\/h[1-3]>/i.exec(sectionBody);
70
+ const fromHeading = h ? slideText(h[1]) : '';
71
+ return fromHeading || slideText(sectionBody).slice(0, 60) || `slide ${i + 1}`;
72
+ };
73
+
74
+ /**
75
+ * Speaker-note HTML as plain text: tags out, entities back, whitespace flat.
76
+ *
77
+ * The runtime gets this for free from `textContent`; a tool reading the FILE
78
+ * has to do it, and has to do it the same way or the two disagree about what a
79
+ * segment says.
80
+ */
81
+ export const cleanNotes = (s) => String(s ?? '')
82
+ .replace(/⟨CLICK⟩/g, ' ')
83
+ .replace(/<[^>]+>/g, ' ')
84
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
85
+ .replace(/\s+/g, ' ')
86
+ .trim();
87
+
88
+ /**
89
+ * A slide's notes split into the ⟨CLICK⟩ segments that become FILES, or null
90
+ * when there are not enough to be worth segmenting.
91
+ *
92
+ * Lives here rather than in tools/voiceover.mjs — which cannot be imported at
93
+ * all, it arg-parses and exits at load — so the runtime's
94
+ * `segmentFileIndex` can be tested against the very function that names the
95
+ * files it is predicting. Those two disagreeing is a silent bug: the runtime
96
+ * keeps empty segments (segment k must line up with build step k) and this
97
+ * drops them (it is naming files), so a ⟨CLICK⟩ at the start of a note shifts
98
+ * every filename by one.
99
+ *
100
+ * An empty segment is dropped rather than recorded as silence — a ⟨CLICK⟩ at
101
+ * the very start or end of a note is punctuation, not a beat.
102
+ */
103
+ export const notesSegments = (notes) => {
104
+ const parts = String(notes ?? '').split('⟨CLICK⟩').map(cleanNotes).filter(Boolean);
105
+ return parts.length > 1 ? parts : null;
106
+ };
107
+
24
108
  /**
25
109
  * Locate slide `n` (1-based) for a round-trip rewrite. Returns the capturing
26
110
  * split (`[preamble, '<section', body1, '<section', body2, …]`) and the index
@@ -5,7 +5,7 @@
5
5
  //
6
6
  // The other three engines offer a fixed roster: Google's thirty star names, or
7
7
  // whichever piper model is on disk. ElevenLabs is the one whose roster is your
8
- // account's, so a voice you cloned shows up in the deck's N picker beside the
8
+ // account's, so a voice you cloned shows up in the deck's V picker beside the
9
9
  // stock ones. That is the whole reason it is here, and it is why this engine
10
10
  // alone fetches its voices instead of shipping them: they are not knowable
11
11
  // until someone's key is in hand.
@@ -31,6 +31,8 @@
31
31
  // and the player's 10-sentence lookahead only ever pays for new sentences.
32
32
 
33
33
  import { createServer } from 'node:http';
34
+ import { createInterface } from 'node:readline/promises';
35
+ import { canBind, resolvePortConflict } from '../cli/port-conflict.mjs';
34
36
  import { createHash } from 'node:crypto';
35
37
  import { execFile } from 'node:child_process';
36
38
  import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, copyFileSync } from 'node:fs';
@@ -41,6 +43,7 @@ import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
41
43
  import { argReader, isMain } from './args.mjs';
42
44
  import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
43
45
  import { corsHeaders, readBody } from './bridge.mjs';
46
+ import { readyLine } from '../cli/banner.mjs';
44
47
 
45
48
  const run = promisify(execFile);
46
49
 
@@ -58,6 +61,30 @@ function makeQueue(width) {
58
61
  return (fn) => new Promise((res, rej) => { waiting.push({ fn, res, rej }); next(); });
59
62
  }
60
63
 
64
+ /** One line from the terminal, for the taken-port question. Closed straight after. */
65
+ async function askLine(prompt) {
66
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
67
+ // EOF ANSWERS THE SAFE WAY. `rl.question` never settles if the input closes
68
+ // first (a Ctrl-D, a terminal whose stdin is a spent pipe), and an unsettled
69
+ // promise here aborted the bridge through the top-level handler — reported to
70
+ // the user as "this one is a bug, please report it", over a question about a
71
+ // port. An empty answer is the declining answer everywhere it is read.
72
+ try {
73
+ return await new Promise((resolve) => {
74
+ // `line` is registered FIRST and readline emits it before `close`, so a
75
+ // key that was actually typed always beats the EOF that follows it. The
76
+ // two racing as promises did not: a piped `k\n` lost to the close and
77
+ // read as a decline, which is a terrible way to lose a keystroke.
78
+ let answered = false;
79
+ const done = (v) => { if (!answered) { answered = true; resolve(v); } };
80
+ rl.once('line', done);
81
+ rl.once('close', () => done(''));
82
+ rl.setPrompt(prompt);
83
+ rl.prompt();
84
+ });
85
+ } finally { rl.close(); }
86
+ }
87
+
61
88
  export async function lipsyncMain(args) {
62
89
  if (args.includes('--help')) {
63
90
  console.log(`usage: decklight lipsync [--port 8789] [--rhubarb <bin>]
@@ -275,9 +302,44 @@ photo puts the face lower in Veo's 9:16 frame — chin off the bottom. Nudge
275
302
  res.end();
276
303
  });
277
304
 
278
- server.listen(port, '127.0.0.1', () => {
305
+ // A TAKEN PORT IS NOT A CRASH. Without this the bind threw EADDRINUSE as an
306
+ // unhandled 'error' event: a raw Node stack trace in the middle of author's
307
+ // startup output, which reads as decklight falling over when the truth is
308
+ // that something else has the port. The edit server has resolved conflicts
309
+ // for a long time (cli/port-conflict.mjs) — the bridges simply never called
310
+ // it, so they were the one place the deck could still look broken.
311
+ //
312
+ // On a TTY it names the occupant and offers a choice; anywhere else — and
313
+ // author spawns these with a piped stdin, so that is the usual case — it
314
+ // moves to the next free port and says so. The player finds the bridge by
315
+ // probing, so a moved port costs nothing.
316
+ // `canBind`, NOT `isPortOpen`: this file's own note says why, and getting it
317
+ // wrong the first time proved the point. `isPortOpen` CONNECTS, answering "is
318
+ // somebody there" — a listener that never accepts (backlog full, or a socket
319
+ // opened and ignored) refuses the connect and reads as free, and then the
320
+ // bind fails anyway. "May I have this port" is a different question and only
321
+ // a trial bind answers it.
322
+ //
323
+ // `--port 0` is "let the OS pick", which cannot conflict — resolving it would
324
+ // turn a deliberate 0 into port 1. Only a REAL port that is taken gets the
325
+ // question; everything else binds exactly as before.
326
+ const asked = port && !(await canBind(port))
327
+ ? await resolvePortConflict(port, {
328
+ kind: 'bridge',
329
+ ask: process.stdin.isTTY && process.stdout.isTTY ? askLine : undefined,
330
+ log: console.log,
331
+ })
332
+ : port;
333
+ // null is "stand down" — either a bridge is already serving this port, or
334
+ // somebody else holds it and this one cannot move (the deck only ever calls
335
+ // the one number). Exiting is the honest outcome: author prints "carrying on
336
+ // without it" and the deck degrades where you can see it, instead of a
337
+ // bridge running somewhere nothing will ever knock.
338
+ if (asked === null) process.exit(0);
339
+ server.listen(asked, '127.0.0.1', () => {
279
340
  const what = [visemeOk && 'visemes (rhubarb)', ...videoEngines.map((e) => `video (${e})`)].filter(Boolean).join(' · ');
280
- console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
341
+ if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key: 'lips', text: `${what} — on :${port}` }));
342
+ else console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
281
343
  if (veo) {
282
344
  console.log(`veo: ${veo.model} · ${veo.seconds}s — each portrait is animated ONCE (billed), `
283
345
  + 'then wav2lip re-syncs that clip locally for every sentence');
package/tools/lipsync.mjs CHANGED
@@ -81,12 +81,23 @@ if (doVideo) {
81
81
  }
82
82
  const ffmpegOk = have('ffmpeg', ['-version']);
83
83
 
84
- // every slide-NN with audio, wav preferred over m4a
85
- const slides = [...new Set(readdirSync(dir)
86
- .map((f) => f.match(/^slide-(\d+)\.(wav|m4a)$/)?.[1])
84
+ // Every stem with audio, wav preferred over m4a: slide-NN, and slide-NN-KK for
85
+ // a track whose ⟨CLICK⟩ beats were recorded separately.
86
+ //
87
+ // A beat needs its OWN sidecar. The player plays one beat's audio at a time on
88
+ // a beat-paced track (PRESENTING), so a timeline cut for the whole slide starts
89
+ // at zero against every one of them — right for the first beat and
90
+ // progressively wronger after it. Cutting one per beat is the fix, and it costs
91
+ // only Rhubarb passes: they are seconds each, and incremental like everything
92
+ // else here.
93
+ const stems = [...new Set(readdirSync(dir)
94
+ .map((f) => f.match(/^(slide-\d+(?:-\d+)?)\.(wav|m4a)$/)?.[1])
87
95
  .filter(Boolean))].sort();
88
- if (!slides.length) { console.error(`${dir}: no slide-NN.wav/.m4a files`); process.exit(1); }
89
- console.log(`${basename(dir)}: ${slides.length} slides with audio`);
96
+ const slides = stems.filter((st) => !/-\d+-\d+$/.test(st));
97
+ const beats = stems.filter((st) => /-\d+-\d+$/.test(st));
98
+ if (!stems.length) { console.error(`${dir}: no slide-NN.wav/.m4a files`); process.exit(1); }
99
+ console.log(`${basename(dir)}: ${slides.length} slides with audio`
100
+ + (beats.length ? ` · ${beats.length} ⟨CLICK⟩ beats` : ''));
90
101
 
91
102
  // incremental state — its own file so voiceover.mjs reruns can't clobber it
92
103
  const statePath = join(dir, 'lipsync.json');
@@ -99,11 +110,11 @@ const sha = (...parts) => {
99
110
  return h.digest('hex').slice(0, 16);
100
111
  };
101
112
 
102
- function toWav(nn) {
103
- const wav = join(dir, `slide-${nn}.wav`);
113
+ function toWav(stem) {
114
+ const wav = join(dir, `${stem}.wav`);
104
115
  if (existsSync(wav)) return { path: wav, tmp: false };
105
- const m4a = join(dir, `slide-${nn}.m4a`);
106
- const tmp = join(dir, `slide-${nn}.tmp.wav`);
116
+ const m4a = join(dir, `${stem}.m4a`);
117
+ const tmp = join(dir, `${stem}.tmp.wav`);
107
118
  if (ffmpegOk) execFileSync('ffmpeg', ['-y', '-i', m4a, tmp], { stdio: 'ignore' });
108
119
  else execFileSync('afconvert', ['-f', 'WAVE', '-d', 'LEI16', m4a, tmp]);
109
120
  return { path: tmp, tmp: true };
@@ -115,40 +126,45 @@ function toWav(nn) {
115
126
  const face = veo && engine === 'wav2lip' ? await veo.motionFor(portrait) : portrait;
116
127
 
117
128
  let made = 0, kept = 0;
118
- for (const nn of slides) {
119
- const audioFile = ['wav', 'm4a'].map((e) => join(dir, `slide-${nn}.${e}`)).find(existsSync);
129
+ for (const stem of stems) {
130
+ // A beat gets visemes only. A talking head is minutes of GPU time per clip,
131
+ // and the player's video element mirrors the audio's transport rather than
132
+ // seeking a timeline — so cutting video per beat would cost a great deal to
133
+ // fix a smaller error than the visemes had.
134
+ const isBeat = /-\d+-\d+$/.test(stem);
135
+ const audioFile = ['wav', 'm4a'].map((e) => join(dir, `${stem}.${e}`)).find(existsSync);
120
136
  const audioBytes = readFileSync(audioFile);
121
- const txtPath = join(dir, `slide-${nn}.txt`);
137
+ const txtPath = join(dir, `${stem}.txt`);
122
138
  const text = existsSync(txtPath) ? readFileSync(txtPath, 'utf8').trim() : '';
123
- const st = (state[nn] ??= {});
139
+ const st = (state[stem] ??= {});
124
140
  const jobs = [];
125
141
  if (doVisemes) jobs.push('visemes');
126
- if (doVideo) jobs.push('video');
142
+ if (doVideo && !isBeat) jobs.push('video');
127
143
 
128
144
  for (const job of jobs) {
129
- const outFile = join(dir, job === 'visemes' ? `slide-${nn}.visemes.json` : `slide-${nn}.mp4`);
145
+ const outFile = join(dir, job === 'visemes' ? `${stem}.visemes.json` : `${stem}.mp4`);
130
146
  const hash = job === 'visemes'
131
147
  ? sha('visemes|', text, '|', audioBytes)
132
148
  : sha('video|', engine, '|', readFileSync(face), '|', audioBytes); // `face`, so --veo re-renders
133
149
  if (st[job] === hash && existsSync(outFile)) {
134
150
  kept++;
135
- console.log(` slide ${nn}: ${job} unchanged — kept`);
151
+ console.log(` ${stem}: ${job} unchanged — kept`);
136
152
  continue;
137
153
  }
138
- const wav = toWav(nn);
154
+ const wav = toWav(stem);
139
155
  try {
140
156
  const t0 = Date.now();
141
157
  if (job === 'visemes') {
142
- const tmpOut = join(dir, `slide-${nn}.tmp.visemes.json`);
158
+ const tmpOut = join(dir, `${stem}.tmp.visemes.json`);
143
159
  let dialogFile;
144
- if (text) { dialogFile = join(dir, `slide-${nn}.tmp.txt`); writeFileSync(dialogFile, text); }
160
+ if (text) { dialogFile = join(dir, `${stem}.tmp.txt`); writeFileSync(dialogFile, text); }
145
161
  const tl = await runRhubarb(rhubarb, { wav: wav.path, dialogFile, out: tmpOut });
146
162
  writeFileSync(outFile, JSON.stringify(tl));
147
163
  rmSync(tmpOut, { force: true });
148
- rmSync(join(dir, `slide-${nn}.tmp.txt`), { force: true });
149
- console.log(` slide ${nn}: ${tl.cues.length} cues → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
164
+ rmSync(join(dir, `${stem}.tmp.txt`), { force: true });
165
+ console.log(` ${stem}: ${tl.cues.length} cues → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
150
166
  } else {
151
- const tmpMp4 = join(dir, `slide-${nn}.tmp.mp4`);
167
+ const tmpMp4 = join(dir, `${stem}.tmp.mp4`);
152
168
  if (engine === 'wav2lip') {
153
169
  // a --veo clip is hundreds of frames to detect faces in, not one:
154
170
  // batch small or an 8GB card dies with "Image too big to run face
@@ -156,7 +172,7 @@ for (const nn of slides) {
156
172
  await runWav2lip(python, { dir: wav2lipDir, checkpoint: wav2lipCkpt, face,
157
173
  wav: wav.path, out: tmpMp4, smallBatches: face !== portrait, inherit: true });
158
174
  } else {
159
- const resDir = join(dir, `slide-${nn}.tmp.d`);
175
+ const resDir = join(dir, `${stem}.tmp.d`);
160
176
  await runSadtalker(python, { dir: sadtalkerDir, still: portrait,
161
177
  wav: wav.path, out: tmpMp4, resultDir: resDir, inherit: true });
162
178
  rmSync(resDir, { recursive: true, force: true });
@@ -166,7 +182,7 @@ for (const nn of slides) {
166
182
  await muteFaststart(tmpMp4, outFile);
167
183
  rmSync(tmpMp4, { force: true });
168
184
  } else renameSync(tmpMp4, outFile);
169
- console.log(` slide ${nn}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
185
+ console.log(` ${stem}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
170
186
  }
171
187
  st[job] = hash;
172
188
  made++;
@@ -40,51 +40,174 @@ export const SAPI_LIST = [
40
40
  + '| ForEach-Object { $_.VoiceInfo.Name }',
41
41
  ];
42
42
 
43
+ /**
44
+ * The novelty and 1990s-formant roster — the voices everybody calls "the
45
+ * robots". They ship on every Mac, they sort ALPHABETICALLY FIRST (Albert,
46
+ * Agnes, Bad News…), and modern `say -v '?'` no longer prints the (Premium)/
47
+ * (Enhanced) markers the old ranking leaned on — which is how Albert became
48
+ * the default narrator on a machine with a hundred better voices. Named
49
+ * explicitly so they land in "average" no matter what the listing says.
50
+ */
51
+ export const SAY_ROBOTS = new Set([
52
+ 'Agnes', 'Albert', 'Bad News', 'Bahh', 'Bells', 'Boing', 'Bubbles', 'Cellos',
53
+ // both spellings: modern macOS lists 'Trinoids', older docs say 'Trinoid' —
54
+ // the singular alone let the plural rank as a plain voice
55
+ 'Deranged', 'Fred', 'Good News', 'Hysterical', 'Jester', 'Junior', 'Kathy',
56
+ 'Organ', 'Pipe Organ', 'Princess', 'Ralph', 'Superstar', 'Trinoid', 'Trinoids',
57
+ 'Victoria', 'Whisper', 'Wobble', 'Zarvox',
58
+ ]);
59
+
60
+ /**
61
+ * The 2022-era character voices — two locales each, mediocre by design, and
62
+ * alphabetically ahead of every classic. They read as personas, not
63
+ * narrators, so they shelve with the novelty voices: on a real Mac they are
64
+ * most of what an alphabetical list shows first, which is how "which voice
65
+ * is good here" became unanswerable.
66
+ */
67
+ export const SAY_PERSONAS = new Set([
68
+ 'Eddy', 'Flo', 'Grandma', 'Grandpa', 'Reed', 'Rocko', 'Sandy', 'Shelley',
69
+ ]);
70
+
43
71
  /**
44
72
  * Rank a macOS voice by how good it is likely to sound.
45
73
  *
46
74
  * The roster mixes twenty years of engines — 1990s formant voices sit in the
47
- * same list as this year's neural ones — and picking the first alphabetically
48
- * means picking Agnes. The parenthesised tier is macOS's own label, and a
49
- * Personal Voice (the one the user recorded themselves, Apple's
50
- * accessibility/Apple-Intelligence-era feature) outranks everything.
75
+ * same list as this year's neural ones. Siri voices are the best `say` can do
76
+ * and rank with a Personal Voice (the one the user recorded themselves); on
77
+ * current macOS they are recognisable only by their SAMPLE sentence
78
+ * ("Hi, I'm Siri!"), the name markers having disappeared from the listing.
79
+ * The robots are pinned to "average" by name — see SAY_ROBOTS.
51
80
  */
52
- export function sayTier(name) {
81
+ export function sayTier(name, sample = '') {
53
82
  if (/\(Personal Voice\)/i.test(name)) return 0;
54
- if (/\(Premium\)/i.test(name)) return 1;
55
- if (/\(Neural\)|\(Siri\)/i.test(name)) return 1;
83
+ if (/^Siri\b|\(Siri\)/i.test(name) || /I[’']m Siri/i.test(sample)) return 0;
84
+ if (/\(Premium\)|\(Neural\)/i.test(name)) return 1;
56
85
  if (/\(Enhanced\)/i.test(name)) return 2;
86
+ const bare = name.replace(/\s*\(.*\)$/, '').trim();
87
+ if (SAY_ROBOTS.has(bare) || SAY_PERSONAS.has(bare)) return 4;
57
88
  return 3;
58
89
  }
59
90
 
60
- const TIER_LABEL = ['personal voice', 'premium', 'enhanced', 'built-in'];
91
+ /**
92
+ * What each tier is CALLED where a person is choosing: the categories, not
93
+ * the engine trivia. Two tiers share "good" and two share "average" — the
94
+ * ranking stays finer than the vocabulary so the sort still puts an Enhanced
95
+ * voice above a plain one and a plain one above a robot.
96
+ */
97
+ export const TIER_LABEL = ['best', 'good', 'good', 'average', 'novelty'];
61
98
 
62
99
  /**
63
100
  * Parse `say -v '?'`.
64
101
  *
65
102
  * A voice NAME may contain spaces and a parenthesised tier, so the locale — the
66
103
  * one token that always looks like `en_US` and always precedes the `#` — is the
67
- * anchor, not a column position.
104
+ * anchor, not a column position. The sample sentence after the `#` rides along:
105
+ * on current macOS it is the only place a Siri voice says what it is.
106
+ *
107
+ * A Siri row that shares its display NAME with a non-Siri row is DROPPED:
108
+ * `say -v` addresses voices by name, so the Siri variant behind a duplicate
109
+ * name cannot actually be selected, and a picker row that plays a different
110
+ * voice than it names would be a lie. A Siri voice under its own name
111
+ * ("Siri Voice 4") is kept, and is the best thing in the list.
68
112
  */
69
113
  export function parseSayVoices(stdout, { lang } = {}) {
70
114
  const out = [];
71
115
  for (const line of String(stdout ?? '').split('\n')) {
72
- const m = /^(.*?)\s{2,}([a-z]{2}(?:[-_][A-Za-z0-9]{2,8})*)\s*#/.exec(line)
73
- ?? /^(.*?)\s+([a-z]{2}[-_][A-Z]{2})\s+#/.exec(line);
116
+ const m = /^(.*?)\s{2,}([a-z]{2}(?:[-_][A-Za-z0-9]{2,8})*)\s*#\s*(.*)$/.exec(line)
117
+ ?? /^(.*?)\s+([a-z]{2}[-_][A-Z]{2})\s+#\s*(.*)$/.exec(line);
74
118
  if (!m) continue;
75
119
  const name = m[1].trim();
76
120
  if (!name) continue;
77
- out.push({ name, locale: m[2].replace('-', '_'), tier: sayTier(name) });
121
+ const sample = (m[3] ?? '').trim();
122
+ out.push({ name, locale: m[2].replace('-', '_'), tier: sayTier(name, sample), sample });
78
123
  }
124
+ // the unaddressable Siri duplicates (see above), and the `((null))`
125
+ // artifacts an undownloaded Siri stub can leave in the listing — both are
126
+ // rows `say -v` cannot actually select, so neither may be offered
127
+ const names = new Map();
128
+ for (const v of out) names.set(v.name, (names.get(v.name) ?? 0) + 1);
129
+ const kept = out.filter((v) => !v.name.includes('((null))')
130
+ && !(names.get(v.name) > 1 && /I[’']m Siri/i.test(v.sample)));
79
131
  const want = (lang ?? 'en').slice(0, 2).toLowerCase();
80
132
  // English (or the asked-for language) first, then by tier: a machine whose
81
133
  // best voice speaks Italian should not narrate an English deck with it
82
- return out.sort((a, b) =>
134
+ return kept.sort((a, b) =>
83
135
  (a.locale.startsWith(want) ? 0 : 1) - (b.locale.startsWith(want) ? 0 : 1)
84
136
  || a.tier - b.tier
85
137
  || a.name.localeCompare(b.name));
86
138
  }
87
139
 
140
+ /**
141
+ * The WinRT speech stack — where Windows' NATURAL voices live.
142
+ *
143
+ * `System.Speech` (SAPI_LIST above) is the 2006 API: it sees David, Zira and
144
+ * Mark, and it cannot see the neural voices Narrator and Edge use (Aria,
145
+ * Jenny, Guy — the ones that sound like a person). Those are exposed through
146
+ * `Windows.Media.SpeechSynthesis`, which Windows PowerShell 5.1 can reach by
147
+ * projecting the WinRT type. So the roster is asked for HERE first, and
148
+ * System.Speech is the fallback for a PowerShell that cannot project (pwsh 7
149
+ * without the SDK assemblies, or an old Windows).
150
+ *
151
+ * One voice per line: DisplayName, Language, Id — tab-separated, because a
152
+ * display name has spaces and parentheses in it.
153
+ */
154
+ export const WINRT_LIST = [
155
+ '-NoProfile', '-NonInteractive', '-Command',
156
+ '$null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media.SpeechSynthesis, ContentType=WindowsRuntime]; '
157
+ + '[Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices '
158
+ + '| ForEach-Object { $_.DisplayName + "`t" + $_.Language + "`t" + $_.Id }',
159
+ ];
160
+
161
+ /** Rank a WinRT voice: the neural ones are the best Windows can do. */
162
+ export function winrtTier(name, id = '') {
163
+ return /\bNatural\b/i.test(name) || /Natural|Neural/i.test(id) ? 0 : 3;
164
+ }
165
+
166
+ /** Parse WINRT_LIST's output — `name<TAB>lang<TAB>id` per line. */
167
+ export function parseWinrtVoices(stdout, { lang } = {}) {
168
+ const out = [];
169
+ for (const line of String(stdout ?? '').split('\n')) {
170
+ const [name, language, id] = line.split('\t').map((x) => (x ?? '').trim());
171
+ if (!name || !language) continue;
172
+ out.push({ name, locale: language.replace('-', '_'), id: id || null, tier: winrtTier(name, id) });
173
+ }
174
+ const want = (lang ?? 'en').slice(0, 2).toLowerCase();
175
+ return out.sort((a, b) =>
176
+ (a.locale.toLowerCase().startsWith(want) ? 0 : 1) - (b.locale.toLowerCase().startsWith(want) ? 0 : 1)
177
+ || a.tier - b.tier
178
+ || a.name.localeCompare(b.name));
179
+ }
180
+
181
+ /**
182
+ * The PowerShell that makes the WinRT stack speak a line into a WAV file.
183
+ *
184
+ * `SynthesizeTextToStreamAsync` answers a WinRT stream that IS a RIFF/WAVE;
185
+ * it is bridged to a .NET stream and copied to the file whole. The one
186
+ * async hop is awaited through `AsTask` looked up by reflection — the
187
+ * projection has no `await` in PowerShell 5.1 — and a voice name this
188
+ * machine does not have THROWS rather than falling back to the default
189
+ * voice, the same rule `say` needed enforcing by hand.
190
+ */
191
+ export function winrtArgs(text, voice, file) {
192
+ const q = (s) => `'${String(s).replace(/'/g, "''")}'`; // PowerShell escaping
193
+ return ['-NoProfile', '-NonInteractive', '-Command',
194
+ '$null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media.SpeechSynthesis, ContentType=WindowsRuntime]; '
195
+ + 'Add-Type -AssemblyName System.Runtime.WindowsRuntime; '
196
+ + '$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { '
197
+ + "$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and "
198
+ + "$_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]; "
199
+ + '$s = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer; '
200
+ + (voice
201
+ ? `$v = [Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices | Where-Object { $_.DisplayName -eq ${q(voice)} } | Select-Object -First 1; `
202
+ + `if (-not $v) { throw ('no voice named ' + ${q(voice)}) }; $s.Voice = $v; `
203
+ : '')
204
+ + `$op = $s.SynthesizeTextToStreamAsync(${q(text)}); `
205
+ + '$task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($op)); '
206
+ + '$task.Wait(); $stream = $task.Result; '
207
+ + '$in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream.GetInputStreamAt(0)); '
208
+ + `$out = [IO.File]::Create(${q(file)}); $in.CopyTo($out); $out.Dispose(); $in.Dispose(); $s.Dispose()`];
209
+ }
210
+
88
211
  /** Parse the PowerShell voice list — one name per line. */
89
212
  export function parseSapiVoices(stdout) {
90
213
  return String(stdout ?? '').split('\n').map((l) => l.trim()).filter(Boolean)
@@ -173,20 +296,51 @@ export function detectLocalVoice({
173
296
  if (voices.length) {
174
297
  return {
175
298
  engine: 'say', voices,
176
- label: `macOS ${TIER_LABEL[voices[0].tier]}: ${voices[0].name}`,
299
+ label: `macOS ${TIER_LABEL[voices[0].tier]} voice: ${voices[0].name}`,
300
+ // The one upgrade worth suggesting: Siri voices are the best thing
301
+ // `say` can produce and a free download away — but only a person can
302
+ // click through to them, so this rides the caveat channel (the
303
+ // bridge's startup line, the picker's toast) rather than pretending
304
+ // to be automatable.
305
+ ...(voices.some((v) => v.tier === 0) ? {} : {
306
+ caveat: 'the best voices here are Siri’s, a free download: System Settings '
307
+ + '→ Accessibility → Spoken Content → System Voice → Manage Voices… '
308
+ + '(open it with: open "x-apple.systempreferences:com.apple.preference.universalaccess") '
309
+ + '— then restart decklight tts',
310
+ }),
177
311
  };
178
312
  }
179
313
  return { engine: null, why: 'macOS `say` is installed but reported no voices', suggest: PIPER_SUGGEST };
180
314
  }
181
315
 
182
316
  if (platform === 'win32') {
183
- const shell = ['powershell.exe', 'pwsh.exe'].find((b) => hasBin(b));
317
+ // Windows PowerShell first: it is the one that projects WinRT types, and
318
+ // WinRT is where the natural voices are. pwsh (7+) cannot without the SDK
319
+ // assemblies, so it is the fallback shell — and System.Speech, which sees
320
+ // only the 2006 voices, the fallback API.
321
+ const shells = ['powershell.exe', 'pwsh.exe'].filter((b) => hasBin(b));
322
+ for (const shell of shells) {
323
+ let voices = [];
324
+ try { voices = parseWinrtVoices(exec(shell, WINRT_LIST), { lang }); } catch { /* not projectable here */ }
325
+ if (voices.length) {
326
+ return {
327
+ engine: 'sapi', api: 'winrt', shell, voices,
328
+ label: `Windows ${TIER_LABEL[voices[0].tier]} voice: ${voices[0].name}`,
329
+ ...(voices.some((v) => v.tier === 0) ? {} : {
330
+ caveat: 'the best voices here are Windows’ natural ones, a free download: Settings '
331
+ + '→ Accessibility → Narrator → Add natural voices '
332
+ + '(open it with: start ms-settings:easeofaccess-narrator) — then restart decklight tts',
333
+ }),
334
+ };
335
+ }
336
+ }
337
+ const shell = shells[0];
184
338
  if (shell) {
185
339
  let voices = [];
186
340
  try { voices = parseSapiVoices(exec(shell, SAPI_LIST)); } catch { /* treated as none */ }
187
341
  if (voices.length) {
188
342
  return {
189
- engine: 'sapi', shell, voices,
343
+ engine: 'sapi', api: 'sapi', shell, voices,
190
344
  label: `Windows ${voices[0].tier === 1 ? 'natural' : 'built-in'} voice: ${voices[0].name}`,
191
345
  };
192
346
  }