decklight 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "A presentation library designed to be authored by AI agents and humans alike: single-file decks, Keynote-style builds, theme-aware SVG diagrams, and truthful terminal recordings.",
5
5
  "type": "module",
6
6
  "main": "dist/decklight.js",
@@ -38,7 +38,8 @@
38
38
  "prepare": "npm run build",
39
39
  "test": "node test/run.mjs",
40
40
  "verify": "npm run build && node test/verify.mjs",
41
- "soak": "node test/soak.mjs"
41
+ "soak": "node test/soak.mjs",
42
+ "cross-engine": "node test/cross-engine.mjs"
42
43
  },
43
44
  "engines": {
44
45
  "node": ">=20"
@@ -51,7 +52,8 @@
51
52
  "optionalDependencies": {
52
53
  "js-yaml": "^4.3.0",
53
54
  "node-pty": "^1.1.0",
54
- "sigstore": "^5.0.0"
55
+ "sigstore": "^5.0.0",
56
+ "playwright": "^1.56.0"
55
57
  },
56
58
  "author": "Gilles Philippart <gilles.philippart@gmail.com>",
57
59
  "license": "Apache-2.0"
@@ -21,6 +21,40 @@ export const NOTES_ASIDE = /<aside class="notes">([\s\S]*?)<\/aside>/;
21
21
  */
22
22
  export const sectionBodies = (html) => html.split(/<section\b/).slice(1);
23
23
 
24
+ /**
25
+ * Speaker-note HTML as plain text: tags out, entities back, whitespace flat.
26
+ *
27
+ * The runtime gets this for free from `textContent`; a tool reading the FILE
28
+ * has to do it, and has to do it the same way or the two disagree about what a
29
+ * segment says.
30
+ */
31
+ export const cleanNotes = (s) => String(s ?? '')
32
+ .replace(/⟨CLICK⟩/g, ' ')
33
+ .replace(/<[^>]+>/g, ' ')
34
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
35
+ .replace(/\s+/g, ' ')
36
+ .trim();
37
+
38
+ /**
39
+ * A slide's notes split into the ⟨CLICK⟩ segments that become FILES, or null
40
+ * when there are not enough to be worth segmenting.
41
+ *
42
+ * Lives here rather than in tools/voiceover.mjs — which cannot be imported at
43
+ * all, it arg-parses and exits at load — so the runtime's
44
+ * `segmentFileIndex` can be tested against the very function that names the
45
+ * files it is predicting. Those two disagreeing is a silent bug: the runtime
46
+ * keeps empty segments (segment k must line up with build step k) and this
47
+ * drops them (it is naming files), so a ⟨CLICK⟩ at the start of a note shifts
48
+ * every filename by one.
49
+ *
50
+ * An empty segment is dropped rather than recorded as silence — a ⟨CLICK⟩ at
51
+ * the very start or end of a note is punctuation, not a beat.
52
+ */
53
+ export const notesSegments = (notes) => {
54
+ const parts = String(notes ?? '').split('⟨CLICK⟩').map(cleanNotes).filter(Boolean);
55
+ return parts.length > 1 ? parts : null;
56
+ };
57
+
24
58
  /**
25
59
  * Locate slide `n` (1-based) for a round-trip rewrite. Returns the capturing
26
60
  * split (`[preamble, '<section', body1, '<section', body2, …]`) and the index
@@ -1,6 +1,10 @@
1
1
  // Copyright 2026 Gilles Philippart
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
+ import { execFileSync } from 'node:child_process';
5
+ import { existsSync } from 'node:fs';
6
+ import { delimiter, join } from 'node:path';
7
+
4
8
  // What can this machine say out loud, without a credential and without a
5
9
  // download?
6
10
  //
@@ -120,10 +124,37 @@ export function sapiArgs(text, voice, file) {
120
124
  * reason THIS machine has none, which differs enough between an Android
121
125
  * device, a bare Linux box and a Mac with a broken `say` to be worth saying.
122
126
  */
127
+ /**
128
+ * Is `bin` runnable? The default for the probe below.
129
+ *
130
+ * This has to be a REAL answer, and that is the whole point of it existing:
131
+ * `hasBin` defaulted to `() => false`, so every caller that did not inject one
132
+ * — `tools/tts-engines.mjs` creating a `say`/`sapi` engine is the only one, and
133
+ * it is the one that matters — was told the machine had no synthesizer, on a
134
+ * Mac where `say -v '?'` lists forty voices. The seams here exist so the tests
135
+ * can drive every OS from one OS; a seam whose DEFAULT is "no" turns the
136
+ * production path into a stub that always refuses, and every test still passes
137
+ * because every test injects.
138
+ */
139
+ export function onPath(bin, env = process.env) {
140
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
141
+ for (const dir of String(env.PATH ?? '').split(delimiter)) {
142
+ if (!dir) continue;
143
+ for (const ext of exts) if (existsSync(join(dir, bin + ext))) return true;
144
+ }
145
+ return false;
146
+ }
147
+
148
+ /** Run a probe and return its stdout; anything at all going wrong is ''. */
149
+ export const probe = (bin, args) => {
150
+ try { return execFileSync(bin, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); }
151
+ catch { return ''; }
152
+ };
153
+
123
154
  export function detectLocalVoice({
124
155
  platform = process.platform,
125
- hasBin = () => false,
126
- exec = () => '',
156
+ hasBin = onPath,
157
+ exec = probe,
127
158
  lang,
128
159
  } = {}) {
129
160
  if (platform === 'android') {
@@ -43,12 +43,12 @@
43
43
  // registered reaches its own voice exactly as it always did.
44
44
 
45
45
  import { execFileSync, spawn } from 'node:child_process';
46
- import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
46
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
47
47
  import { homedir, tmpdir } from 'node:os';
48
- import { join } from 'node:path';
48
+ import { delimiter, join } from 'node:path';
49
49
  import { createSynth as createGemini, GEMINI_VOICES, gcloudToken, validProjectId, authHeaders } from './gemini-tts.mjs';
50
50
  import {
51
- createSynth as createElevenLabs, apiKey as elevenLabsKey,
51
+ createSynth as createElevenLabs, apiKey as elevenLabsKey, KEY_ENV as ELEVENLABS_KEY_ENV,
52
52
  DEFAULT_MODEL as ELEVENLABS_MODEL, V3_MODEL as ELEVENLABS_V3_MODEL,
53
53
  } from './elevenlabs-tts.mjs';
54
54
  import { detectLocalVoice, sayArgs, sapiArgs } from './local-voice.mjs';
@@ -333,10 +333,32 @@ function createPiper({ voice = PIPER_DEFAULT_VOICE, dataDir }) {
333
333
  * Neither takes a delivery instruction, so both are `stylable: false` and the
334
334
  * picker skips the tone step, exactly as it does for piper and ElevenLabs.
335
335
  */
336
- function createNative({ kind, voice, shell = 'powershell.exe' }) {
336
+ function createNative({ kind, voice, shell = 'powershell.exe', voices = [] }) {
337
337
  const bin = kind === 'say' ? 'say' : shell;
338
338
  const build = kind === 'say' ? sayArgs : sapiArgs;
339
- return async (text) => {
339
+ // The roster this machine actually has, for the guard below. Held as names
340
+ // because that is what the player sends and what `say -v` takes.
341
+ const known = new Set(voices.map((v) => v?.name ?? v).filter(Boolean));
342
+ /**
343
+ * `(text, { voice })` — the SECOND argument is the voice for THIS sentence,
344
+ * and it is the whole contract every other engine here implements.
345
+ *
346
+ * This used to be `async (text) =>`, closing over the voice chosen when the
347
+ * bridge started. So the picker offered 184 macOS voices, the log printed
348
+ * whichever one you picked, and all 184 played the same one — the failure was
349
+ * invisible in the logs because the log line quotes the REQUEST.
350
+ */
351
+ return async (text, { voice: asked } = {}) => {
352
+ const pick = asked || voice;
353
+ // A name this machine cannot say is an ERROR, not a shrug. `say -v Zephyr`
354
+ // exits 0 and quietly produces the SYSTEM DEFAULT voice — so a typo, a
355
+ // stale saved voice, or a roster from another engine all sound like
356
+ // success while giving you somebody else's voice. (PowerShell's
357
+ // SelectVoice already throws on an unknown name; this makes the two agree.)
358
+ if (kind === 'say' && known.size && pick && !known.has(pick)) {
359
+ throw new Error(`no ${kind} voice named ${JSON.stringify(pick)} on this machine`
360
+ + ` — this bridge speaks ${known.size} others (GET /voices)`);
361
+ }
340
362
  // one line: `say` treats newlines as pauses and PowerShell quoting gets
341
363
  // harder the moment a string spans lines
342
364
  const line = String(text).replace(/\s+/g, ' ').trim();
@@ -344,10 +366,20 @@ function createNative({ kind, voice, shell = 'powershell.exe' }) {
344
366
  const dir = mkdtempSync(join(tmpdir(), 'decklight-native-'));
345
367
  const file = join(dir, 'out.wav');
346
368
  try {
347
- execFileSync(bin, build(line, voice, file), { stdio: ['ignore', 'ignore', 'pipe'] });
369
+ execFileSync(bin, build(line, pick, file), { stdio: ['ignore', 'ignore', 'pipe'] });
348
370
  const wav = readFileSync(file);
349
371
  if (!wav.length) throw new Error(`${kind} produced no audio`);
350
- return wav;
372
+ // `{ wav, usage }`, like every other engine and like this file's own
373
+ // contract at the top. It returned a bare Buffer, so a caller that
374
+ // destructured `{ wav }` — tools/voiceover.mjs does — got undefined and
375
+ // wrote it to disk. Nobody had ever reached this line: detectLocalVoice's
376
+ // default probe answered "no synthesizer" first, so the shape was wrong
377
+ // behind a door that never opened.
378
+ return {
379
+ wav,
380
+ // the voice that SPOKE, not the one the bridge booted with
381
+ usage: { model: pick ?? kind, chars: line.length, cost: 0, note: `${line.length} chars · local` },
382
+ };
351
383
  } catch (e) {
352
384
  throw new Error(`${kind}: ${String(e.stderr ?? e.message).trim().split('\n')[0] || 'synthesis failed'}`);
353
385
  } finally {
@@ -358,6 +390,10 @@ function createNative({ kind, voice, shell = 'powershell.exe' }) {
358
390
 
359
391
  export function createEngine({
360
392
  engine = 'gemini', project, model, location, voice, dataDir, lang, format, stability, env = process.env,
393
+ // Injected like every other probe in this file, so a native engine can be
394
+ // built — and its voice handling asserted — on a machine that is not the one
395
+ // the test happens to run on.
396
+ detect = detectLocalVoice,
361
397
  } = {}) {
362
398
  if (!ENGINES.includes(engine)) {
363
399
  throw new Error(`unknown engine '${engine}' — use ${ENGINES.join(', ')},`
@@ -376,14 +412,16 @@ export function createEngine({
376
412
  };
377
413
  }
378
414
  if (engine === 'say' || engine === 'sapi') {
379
- const detected = detectLocalVoice({ lang });
415
+ const detected = detect({ lang });
380
416
  const pick = voice ?? detected.voices?.[0]?.name;
381
417
  if (!pick) throw new Error(detected.why ?? `no ${engine} voices on this machine`);
382
418
  return {
383
419
  name: engine, model: pick, needsProject: false, stylable: false,
384
420
  cost: 'free · offline · already on this machine',
385
421
  voices: (detected.voices ?? []).map((v) => [v.name, v.locale || 'system']),
386
- synth: createNative({ kind: engine, voice: pick, shell: detected.shell }),
422
+ synth: createNative({
423
+ kind: engine, voice: pick, shell: detected.shell, voices: detected.voices ?? [],
424
+ }),
387
425
  };
388
426
  }
389
427
  if (engine === 'elevenlabs') {
@@ -431,6 +469,154 @@ export function createEngine({
431
469
  };
432
470
  }
433
471
 
472
+ /**
473
+ * Is `bin` on PATH? The bare-name probe the readiness check needs.
474
+ *
475
+ * `cli/agents.mjs` has the full version (explicit paths, execute bits); this
476
+ * one is here rather than there because `tools/` cannot import from `cli/`,
477
+ * and `tools/tts-setup.mjs` shares it so the wizard and the readiness check
478
+ * cannot disagree about whether piper is installed.
479
+ */
480
+ export function binOnPath(bin, env = process.env) {
481
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
482
+ return (env.PATH || '').split(delimiter)
483
+ .some((dir) => dir && exts.some((ext) => existsSync(join(dir, bin + ext))));
484
+ }
485
+
486
+ /**
487
+ * Can this machine speak with `name` right now, and if not, what is missing?
488
+ *
489
+ * WHY THIS IS NOT `createEngine` THROWING. Two of the six build perfectly well
490
+ * and fail later: `gemini` and `chirp` construct a synth against a project id
491
+ * nobody has checked, so the bridge would come up looking healthy and only die
492
+ * on the first keypress — with a 403 naming a project the presenter never
493
+ * typed. Readiness is a question about the MACHINE (a binary, a model file, a
494
+ * key, a project), and it has to be asked before anything is constructed.
495
+ *
496
+ * WHY IT LIVES HERE. Two callers now ask it: `decklight author`, deciding
497
+ * whether to start the bridge at all, and the bridge itself, listing what the
498
+ * deck may switch to (SPEC `NARRATION`). They must not disagree — a picker
499
+ * offering an engine that `author` would have refused is a picker that lies.
500
+ * So the DECISION is shared and only the presentation differs: `reason` is a
501
+ * code the caller phrases for its own audience.
502
+ *
503
+ * Every probe is injected, so this is testable without a PATH, a filesystem,
504
+ * or a credential.
505
+ */
506
+ export function engineStatus(name, {
507
+ // `project` defaults from the environment rather than to null: a caller that
508
+ // passes only `env` means "decide from this machine", and answering
509
+ // no-project on a machine whose GOOGLE_CLOUD_PROJECT is right there would be
510
+ // a wrong answer that looks like a correct one. A caller with its own
511
+ // precedence ladder (flags > env > saved config) passes the settled value.
512
+ env = process.env, project = env.GOOGLE_CLOUD_PROJECT ?? null,
513
+ voice = null, dataDir = null, lang = null,
514
+ hasBin = binOnPath, exists = existsSync, detect = detectLocalVoice,
515
+ } = {}) {
516
+ const no = (reason, detail) => ({ name, ready: false, reason, ...detail });
517
+ if (!ENGINES.includes(name)) return no('unknown');
518
+
519
+ if (name === 'piper') {
520
+ if (!hasBin('piper', env)) return no('no-binary');
521
+ const v = voice ?? PIPER_DEFAULT_VOICE;
522
+ const models = dataDir ?? piperModelDir(env);
523
+ if (!exists(piperModelPath(v, models))) return no('no-model', { voice: v, dataDir: models });
524
+ return { name, ready: true, reason: 'ok' };
525
+ }
526
+ if (NATIVE_ENGINES.includes(name)) {
527
+ // A system voice needs no setup at all — but the wrong OS has none, and
528
+ // `say` on a machine with no configured voices is a silent bridge.
529
+ const d = detect({ lang });
530
+ if (d?.engine !== name || !d?.voices?.length) return no('no-native-voice', { why: d?.why });
531
+ return { name, ready: true, reason: 'ok' };
532
+ }
533
+ if (name === 'elevenlabs') {
534
+ return elevenLabsKey(env)?.trim() ? { name, ready: true, reason: 'ok' } : no('no-key');
535
+ }
536
+ // gemini and chirp
537
+ if (!project) return no('no-project');
538
+ if (!validProjectId(project)) return no('bad-project', { project });
539
+ return { name, ready: true, reason: 'ok' };
540
+ }
541
+
542
+ /**
543
+ * A blocker in two short sentences: what is missing, and what fixes it.
544
+ *
545
+ * These are the PICKER's words — one line each, because they are drawn under a
546
+ * greyed row in a deck. `decklight author` phrases the same codes at length
547
+ * (it has a terminal, and it is the place a presenter is still setting up).
548
+ * Both read the same `reason`, so they can be worded for their audience
549
+ * without being able to disagree about the facts.
550
+ *
551
+ * Every fix is something you do in a TERMINAL, and that is deliberate: the
552
+ * deck lists what is missing and never collects it. A key or a project id
553
+ * typed into a web page — even one on loopback — is a different thing from one
554
+ * exported in a shell, and a presented deck is reachable from a phone.
555
+ */
556
+ export function engineBlocker(status, { env = process.env } = {}) {
557
+ const { reason } = status ?? {};
558
+ if (!reason || reason === 'ok') return null;
559
+ switch (reason) {
560
+ case 'no-binary':
561
+ return { why: 'not installed', fix: 'uv tool install piper-tts' };
562
+ case 'no-model':
563
+ return {
564
+ why: `the voice ${status.voice} is not downloaded (~120 MB, one time)`,
565
+ fix: piperDownloadLine(piperDownloadCmd(status.voice, status.dataDir,
566
+ { hasBin: (b) => binOnPath(b, env) })),
567
+ };
568
+ case 'no-key':
569
+ return { why: `needs $${ELEVENLABS_KEY_ENV}`, fix: 'export it, then restart decklight author' };
570
+ case 'no-project':
571
+ return {
572
+ why: 'needs a Google Cloud project',
573
+ fix: 'export GOOGLE_CLOUD_PROJECT=<id>, then restart decklight author',
574
+ };
575
+ case 'bad-project':
576
+ // Named rather than generic: this one is nearly always a copy-paste that
577
+ // brought punctuation with it, and seeing the value is the whole fix.
578
+ return { why: `not a GCP project id: ${JSON.stringify(status.project)}`, fix: 'stray punctuation from a copy-paste?' };
579
+ case 'no-native-voice':
580
+ return { why: status.why ?? 'no system voice on this machine', fix: null };
581
+ default:
582
+ return { why: `unknown engine — use ${ENGINES.join(', ')}`, fix: null };
583
+ }
584
+ }
585
+
586
+ /**
587
+ * What a presenter could switch to, with the price note and the blocker.
588
+ *
589
+ * Order is a RECOMMENDATION and deliberately not `ENGINES` order (which keeps
590
+ * gemini first for history): free and already-on-this-machine first, then the
591
+ * ones with a bill. The native engine is folded to whichever of say/sapi this
592
+ * OS actually has, because "sapi" on a Mac is not a choice, it is noise.
593
+ *
594
+ * `cost` comes from the engine itself where it can be built, so the picker
595
+ * quotes the same sentence the bridge's startup line does rather than a second
596
+ * copy of it. An engine that cannot be built has no cost to quote — it has a
597
+ * blocker, which is what the row shows instead.
598
+ */
599
+ export function engineMenu(opts = {}) {
600
+ // Settled once, and shared with the construction below: `createEngine` for a
601
+ // cloud engine REFUSES a missing project, so a menu that probed readiness
602
+ // with the environment's project but built with `undefined` would quietly
603
+ // drop the price note off every row it had just called ready.
604
+ const env = opts.env ?? process.env;
605
+ const settled = { ...opts, env, project: opts.project ?? env.GOOGLE_CLOUD_PROJECT ?? null };
606
+ const native = NATIVE_ENGINES.includes(process.platform === 'win32' ? 'sapi' : 'say')
607
+ ? (process.platform === 'win32' ? 'sapi' : 'say') : null;
608
+ const order = [native, 'piper', 'chirp', 'gemini', 'elevenlabs'].filter(Boolean);
609
+ return order.map((name) => {
610
+ const status = engineStatus(name, settled);
611
+ let cost;
612
+ // Building it is the only way to learn the price note, and it is cheap —
613
+ // no network, no process. It can still throw (a native engine with no
614
+ // voices), which is not an error here: the row already carries the blocker.
615
+ try { cost = createEngine({ ...settled, engine: name }).cost; } catch { cost = undefined; }
616
+ return { ...status, cost, ...(engineBlocker(status, settled) ?? {}) };
617
+ });
618
+ }
619
+
434
620
  /**
435
621
  * The engine for `name`, whether decklight ships it or the machine installed
436
622
  * it (SPEC `ENGINE_UNITS`).
@@ -21,6 +21,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node
21
21
  import { homedir, tmpdir } from 'node:os';
22
22
  import { delimiter, dirname, join } from 'node:path';
23
23
  import {
24
+ binOnPath,
24
25
  createEngine, ENGINES, PIPER_DEFAULT_VOICE, piperModelDir,
25
26
  piperDownloadCmd, piperDownloadLine,
26
27
  } from './tts-engines.mjs';
@@ -50,14 +51,6 @@ export function saveTtsConfig(config, env = process.env) {
50
51
  return file;
51
52
  }
52
53
 
53
- // cli/agents.mjs has the full onPath (explicit paths too); tools/ cannot
54
- // import from cli/, and the wizard only ever probes bare names.
55
- function binOnPath(bin, env = process.env) {
56
- const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
57
- return (env.PATH || '').split(delimiter)
58
- .some((dir) => dir && exts.some((ext) => existsSync(join(dir, bin + ext))));
59
- }
60
-
61
54
  /** The project gcloud is configured with — the prefill when $GOOGLE_CLOUD_PROJECT is unset. */
62
55
  export function gcloudConfigProject() {
63
56
  try {
package/tools/video.mjs CHANGED
@@ -56,7 +56,10 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
56
56
  --size <WxH> frame size (default 1280x720; both must be even)
57
57
  --fps <n> video frame rate (default 30)
58
58
  --hold <s> seconds a slide without narration holds (default 5;
59
- per-slide override: data-video-hold="8" on the section)
59
+ per-slide override: data-video-hold="8" on the section).
60
+ A NARRATED slide holds for its audio instead — give that
61
+ one a beat with data-narration-pause="2", the same
62
+ attribute the live deck pauses on
60
63
  --build-hold <s> seconds each build-up frame holds on a silent slide
61
64
  (default: the slide's own hold, so builds move at the
62
65
  pace the deck does)
@@ -64,9 +67,14 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
64
67
  --slides <a-b> only this slide range (1-based, inclusive)
65
68
  --voiceover run the voiceover batch (tools/voiceover.mjs) first
66
69
 
67
- Slides with narration hold for the audio's real duration + ${TAIL_SECONDS}s and show
68
- fully built; slides without hold --hold seconds over silence and BUILD as they
69
- go, one frame per step, so the audio track stays continuous either way.
70
+ Every slide BUILDS, one frame per step. A narrated slide takes its timing from
71
+ its own audio: ⟨CLICK⟩ in the speaker notes splits the narration, and segment k
72
+ is spoken over build step k — the same rule the live player follows. Without
73
+ markers it holds fully built for the audio's real duration. A silent slide holds
74
+ --hold seconds, --build-hold per step. Either way the audio track is continuous
75
+ and the finished slide gets a ${TAIL_SECONDS}s breath before the cut — plus
76
+ whatever data-narration-pause="2" asks for, so the mp4 breathes where the
77
+ live deck does.
70
78
  Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
71
79
  `;
72
80
 
@@ -100,6 +108,23 @@ export function extractHolds(html, defaultHold) {
100
108
  });
101
109
  }
102
110
 
111
+ /**
112
+ * Per-slide narration beat: data-narration-pause="2" on the section, else 0.
113
+ *
114
+ * The recorded mirror of the live rule (PRESENTING): src/core/narration.js
115
+ * holds that many seconds after a slide's last sentence before moving on, and
116
+ * an exported mp4 must breathe in the same places the deck does. Read off the
117
+ * raw open tag, like extractHolds, so the same attribute appearing in a
118
+ * slide's CONTENT cannot be mistaken for the slide's own.
119
+ */
120
+ export function extractPauses(html) {
121
+ return sectionBodies(html).map((sec) => {
122
+ const tag = sec.slice(0, sec.indexOf('>'));
123
+ const m = tag.match(/data-narration-pause="([\d.]+)"/);
124
+ return m ? Number(m[1]) : 0;
125
+ });
126
+ }
127
+
103
128
  /**
104
129
  * An oversized step: the engine clamps it to the slide's last build, so this
105
130
  * always renders a slide fully built however many steps it turns out to have.
@@ -117,9 +142,13 @@ const round = (s) => Math.round(s * 1000) / 1000;
117
142
  * ONE ENTRY PER FRAME, not per slide. A silent slide with builds is a sequence
118
143
  * — the slide bare, then each build revealed — because a video of a built slide
119
144
  * that opens fully built has thrown away the thing the builds were for. A
120
- * NARRATED slide stays one fully-built still: splitting its audio across builds
121
- * needs the ⟨CLICK⟩ markers to map to real timestamps, which is its own
122
- * feature, and guessing at it would put words under the wrong build.
145
+ * A NARRATED slide follows its own notes: where those notes are segmented by
146
+ * ⟨CLICK⟩ and the segment count matches the build count, segment k narrates
147
+ * build step k and holds for that segment's REAL audio. Nothing is inferred —
148
+ * the markers are the author's, tools/voiceover.mjs synthesises one file per
149
+ * segment, and this reads their ffprobe'd durations. A narrated slide with no
150
+ * markers, or a count that does not line up, is one fully-built still for the
151
+ * length of its audio, as it always was.
123
152
  *
124
153
  * Timing, for a silent slide with `b` build steps (so `b + 1` frames): EVERY
125
154
  * frame holds for the slide's hold, so a build lands at the pace the rest of
@@ -138,22 +167,64 @@ const round = (s) => Math.round(s * 1000) / 1000;
138
167
  * @param {{from,to}} [range] 1-based inclusive slide range
139
168
  * @param {object} [opts] steps: per-slide build-step counts (null ⇒ one
140
169
  * frame per slide); buildHold: seconds per
141
- * build-up frame (null ⇒ the slide's own hold)
142
- * @returns {Array<{slide, step, audio, duration}>} audio null ⇒ silent hold
170
+ * build-up frame (null ⇒ the slide's own hold);
171
+ * pauses: per-slide data-narration-pause seconds
172
+ * added to a NARRATED slide's finished frame
173
+ * @returns {Array<{slide, step, audio, duration, pad}>} audio null ⇒ silent hold;
174
+ * `pad` is the silence ffmpeg appends to the audio
143
175
  */
144
- export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null } = {}) {
176
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null, pauses = null, onWarn = null } = {}) {
145
177
  const from = range?.from ?? 1;
146
178
  const to = range?.to ?? holds.length;
147
179
  const plan = [];
148
180
  for (let n = from; n <= to; n++) {
149
- const file = manifest?.[n - 1]?.file ?? null;
181
+ const entry = manifest?.[n - 1] ?? null;
182
+ const file = entry?.file ?? null;
150
183
  const dur = file ? durations?.[file] : null;
184
+
185
+ // A narrated slide whose notes are segmented by ⟨CLICK⟩ builds AS IT
186
+ // SPEAKS: segment k narrates build step k. That rule is not invented here —
187
+ // src/core/narration.js already speaks live narration that way ("exactly
188
+ // like a presenter reading the notes and clicking between segments"), and
189
+ // captions, rehearse mode and the notes editor all run on the same
190
+ // segmentation. This makes the recorded render the mirror of it.
191
+ const segs = entry?.segments ?? null;
192
+ const builds = steps?.[n - 1] ?? 0;
193
+ // The slide's own beat rides on the tail of its finished frame — the one
194
+ // place the live deck pauses too. A silent slide has no narration to pause
195
+ // after; --hold and data-video-hold are its knobs.
196
+ const tail = TAIL_SECONDS + (pauses?.[n - 1] ?? 0);
197
+ if (Number.isFinite(dur) && segs?.length && builds) {
198
+ const times = segs.map((sg) => durations?.[sg.file]);
199
+ if (segs.length === builds + 1 && times.every((t) => Number.isFinite(t))) {
200
+ segs.forEach((sg, k) => {
201
+ const last = k === segs.length - 1;
202
+ plan.push({
203
+ slide: n,
204
+ step: last ? LAST_STEP : k,
205
+ audio: sg.file,
206
+ // Only the finished slide gets the breath. A build that paused for
207
+ // it would read as hesitation rather than as a beat.
208
+ duration: round(times[k] + (last ? tail : 0)),
209
+ pad: last ? tail : 0,
210
+ });
211
+ });
212
+ continue;
213
+ }
214
+ // A marker count that does not match the build count is the author's to
215
+ // fix, and guessing which build a segment belongs to would bake a wrong
216
+ // sync into an mp4 — worse than no sync. Say which slide, and render it
217
+ // the way an unsegmented one renders.
218
+ onWarn?.(`slide ${n}: ${segs.length} narration segment${segs.length === 1 ? '' : 's'}`
219
+ + ` but ${builds + 1} frames (${builds} build${builds === 1 ? '' : 's'} + the finished slide)`
220
+ + ' — narrating the whole slide over one still instead');
221
+ }
222
+
151
223
  if (Number.isFinite(dur)) {
152
- plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + TAIL_SECONDS) });
224
+ plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + tail), pad: tail });
153
225
  continue;
154
226
  }
155
227
  const hold = holds[n - 1];
156
- const builds = steps?.[n - 1] ?? 0;
157
228
  if (!builds) { plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold }); continue; }
158
229
  const each = buildHold ?? hold;
159
230
  for (let k = 0; k < builds; k++) plan.push({ slide: n, step: k, audio: null, duration: each });
@@ -164,17 +235,18 @@ export function planTimeline(manifest, durations, holds, range = null, { steps =
164
235
 
165
236
  /**
166
237
  * ffmpeg argv for one slide's segment: the still looped at --fps under its
167
- * audio. Narrated slides pad the audio with the tail and stop there; silent
238
+ * audio. Narrated slides pad the audio with `pad` — the tail, plus whatever
239
+ * beat the slide asked for (`data-narration-pause`) — and stop there; silent
168
240
  * slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
169
241
  * carries an audio stream and the concat-demuxer's `-c copy` audio track never
170
242
  * goes discontinuous. -t bounds both the infinite loop and the infinite
171
243
  * anullsrc (-shortest can't end a segment whose streams are both endless).
172
244
  */
173
- export function segmentArgs({ frame, audio, duration, fps, out }) {
245
+ export function segmentArgs({ frame, audio, duration, fps, out, pad = TAIL_SECONDS }) {
174
246
  return [
175
247
  '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
176
248
  ...(audio
177
- ? ['-i', audio, '-af', `apad=pad_dur=${TAIL_SECONDS}`]
249
+ ? ['-i', audio, '-af', `apad=pad_dur=${pad}`]
178
250
  : ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
179
251
  '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
180
252
  '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
@@ -322,6 +394,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
322
394
 
323
395
  const html = readFileSync(deck, 'utf8');
324
396
  const holds = extractHolds(html, hold);
397
+ const pauses = extractPauses(html);
325
398
  if (!holds.length) throw new Error(`${basename(deck)} has no <section> slides`);
326
399
  const range = parseSlideRange(opt('--slides'), holds.length);
327
400
 
@@ -338,14 +411,21 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
338
411
  // real durations, not the manifest's word count: ffprobe each audio file
339
412
  const durations = {};
340
413
  for (let n = range.from; n <= range.to; n++) {
341
- const file = narration?.slides?.[n - 1]?.file;
342
- if (!file || durations[file] != null) continue;
343
- const path = join(narration.dir, file);
344
- if (!existsSync(path)) {
345
- console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk — holding ${holds[n - 1]}s of silence`);
346
- continue;
414
+ const entry = narration?.slides?.[n - 1];
415
+ // The slide's own audio AND its ⟨CLICK⟩ segments. Measured here rather
416
+ // than trusted from the manifest, for the reason the per-slide durations
417
+ // already are: what a file says it is worth is not what ffprobe says.
418
+ const files = [entry?.file, ...(entry?.segments ?? []).map((sg) => sg.file)].filter(Boolean);
419
+ for (const file of files) {
420
+ if (durations[file] != null) continue;
421
+ const path = join(narration.dir, file);
422
+ if (!existsSync(path)) {
423
+ console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk`
424
+ + `${file === entry?.file ? ` — holding ${holds[n - 1]}s of silence` : ' — narrating the whole slide instead'}`);
425
+ continue;
426
+ }
427
+ durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
347
428
  }
348
- durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
349
429
  }
350
430
 
351
431
 
@@ -385,7 +465,8 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
385
465
  probing = false;
386
466
  if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
387
467
 
388
- plan = planTimeline(narration?.slides ?? null, durations, holds, range, { steps, buildHold });
468
+ plan = planTimeline(narration?.slides ?? null, durations, holds, range,
469
+ { steps, buildHold, pauses, onWarn: (w) => console.warn(` ${w}`) });
389
470
  const slideCount = new Set(plan.map((p) => p.slide)).size;
390
471
  log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
391
472
  + `${plan.filter((p) => p.audio).length} narrated`
@@ -410,7 +491,7 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
410
491
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
411
492
  const seg = join(work, `seg-${id}.mp4`);
412
493
  await exec('ffmpeg', segmentArgs({
413
- frame, duration: p.duration, fps, out: seg,
494
+ frame, duration: p.duration, pad: p.pad, fps, out: seg,
414
495
  audio: p.audio ? join(narration.dir, p.audio) : null,
415
496
  }));
416
497
  segments.push(seg);