decklight 0.1.0 → 0.2.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 (87) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +61 -177
  3. package/SPEC.md +20 -8
  4. package/cli/agents.mjs +102 -0
  5. package/cli/bundle.mjs +37 -0
  6. package/cli/decklight.mjs +18 -0
  7. package/cli/dev.mjs +266 -0
  8. package/cli/edit.mjs +230 -17
  9. package/cli/init.mjs +58 -19
  10. package/cli/rec.mjs +7 -0
  11. package/dist/decklight.css +241 -51
  12. package/dist/decklight.js +120 -76
  13. package/dist/decklight.js.map +4 -4
  14. package/package.json +6 -4
  15. package/themes/aliens.css +3 -0
  16. package/themes/apple2.css +3 -0
  17. package/themes/aurora.css +3 -0
  18. package/themes/berry.css +3 -0
  19. package/themes/blade-runner.css +3 -0
  20. package/themes/c64.css +3 -0
  21. package/themes/carbon.css +3 -0
  22. package/themes/citrus.css +3 -0
  23. package/themes/coastal.css +3 -0
  24. package/themes/cosmos.css +3 -0
  25. package/themes/dune.css +3 -0
  26. package/themes/eclipse.css +3 -0
  27. package/themes/ember.css +3 -0
  28. package/themes/fjord.css +3 -0
  29. package/themes/friends.css +3 -0
  30. package/themes/gameboy.css +3 -0
  31. package/themes/genesis.css +3 -0
  32. package/themes/glacier.css +3 -0
  33. package/themes/godfather.css +3 -0
  34. package/themes/graphite.css +3 -0
  35. package/themes/harvest.css +3 -0
  36. package/themes/ibm-modern.css +3 -0
  37. package/themes/ibm-oldschool.css +3 -0
  38. package/themes/ink.css +3 -0
  39. package/themes/latte.css +3 -0
  40. package/themes/linen.css +3 -0
  41. package/themes/meadow.css +3 -0
  42. package/themes/metropolis.css +3 -0
  43. package/themes/miami-vice.css +3 -0
  44. package/themes/midnight.css +3 -0
  45. package/themes/mint.css +3 -0
  46. package/themes/moss.css +3 -0
  47. package/themes/obsidian.css +3 -0
  48. package/themes/orchid.css +3 -0
  49. package/themes/packs.json +2 -1
  50. package/themes/paper.css +3 -0
  51. package/themes/peony.css +3 -0
  52. package/themes/porcelain.css +3 -0
  53. package/themes/pulp-fiction.css +3 -0
  54. package/themes/reveal-beige.css +3 -0
  55. package/themes/reveal-black.css +3 -0
  56. package/themes/reveal-blood.css +3 -0
  57. package/themes/reveal-dracula.css +3 -0
  58. package/themes/reveal-league.css +3 -0
  59. package/themes/reveal-moon.css +3 -0
  60. package/themes/reveal-night.css +3 -0
  61. package/themes/reveal-serif.css +3 -0
  62. package/themes/reveal-simple.css +3 -0
  63. package/themes/reveal-sky.css +3 -0
  64. package/themes/reveal-solarized.css +3 -0
  65. package/themes/reveal-white.css +3 -0
  66. package/themes/sepia.css +3 -0
  67. package/themes/seriph.css +3 -0
  68. package/themes/severance.css +3 -0
  69. package/themes/slate.css +3 -0
  70. package/themes/snes.css +3 -0
  71. package/themes/star-wars.css +3 -0
  72. package/themes/storm.css +3 -0
  73. package/themes/stranger-things.css +3 -0
  74. package/themes/synthwave.css +3 -0
  75. package/themes/terminator.css +3 -0
  76. package/themes/velvet.css +3 -0
  77. package/themes/yamabuki.css +120 -0
  78. package/tools/chrome.mjs +43 -0
  79. package/tools/gemini-tts.mjs +19 -1
  80. package/tools/lipsync-server.mjs +249 -0
  81. package/tools/lipsync.mjs +166 -0
  82. package/tools/publish-site-voices.mjs +3 -0
  83. package/tools/shot.mjs +85 -0
  84. package/tools/tts-engines.mjs +226 -0
  85. package/tools/visemes.mjs +26 -0
  86. package/tools/voiceover-server.mjs +0 -0
  87. package/tools/voiceover.mjs +51 -34
@@ -0,0 +1,120 @@
1
+ /* Copyright 2026 Gilles Philippart
2
+ SPDX-License-Identifier: Apache-2.0 */
3
+
4
+ /* ═══════════════════════════════════════════════════════════════
5
+ Decklight theme · yamabuki
6
+ dark · 山吹 — the Japanese golden-yellow, on cool ink
7
+ Named for 山吹色, the gold of the kerria flower. One warm accent on a
8
+ near-neutral cool ground; the red is reserved for things that fail.
9
+ Mono headings — the type is machine-set, like the subject.
10
+ Token contract: SPEC.md §5 — all values validated by test/contrast.mjs
11
+ ═══════════════════════════════════════════════════════════════ */
12
+
13
+ .decklight {
14
+ /* ── canvas ─────────────────────────────── */
15
+ --bg: #14171c;
16
+ --bg-accent: #1b1f26;
17
+ --fg: #edece7;
18
+ --muted: #a0a4ab;
19
+
20
+ /* ── type ───────────────────────────────── */
21
+ --font-body: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
22
+ --font-heading: "SF Mono", SFMono-Regular, ui-monospace, "Cascadia Code", Menlo, Consolas, monospace;
23
+ --font-mono: "SF Mono", SFMono-Regular, ui-monospace, "Cascadia Code", Menlo, Consolas, monospace;
24
+ --heading-color: #f2b32c;
25
+ --heading-weight: 600;
26
+ --link: #f5c25c;
27
+
28
+ /* ── accent ─────────────────────────────── */
29
+ /* 山吹 proper is #f2b32c, which is s88 — over R3's saturation cap of 75. It
30
+ stays as the *displayed* gold (headings, diagram accent, prompt, keyword),
31
+ none of which R3 gates. --accent drives chrome, so it sits three points
32
+ under the cap at s74: the same gold, dimmed just enough to obey the rule
33
+ rather than claim an exception from it. */
34
+ --accent: #e3b445;
35
+ --accent-contrast: #171309;
36
+
37
+ /* ── blocks ─────────────────────────────── */
38
+ --block-bg: #1b1f26;
39
+ --block-border: 1px solid #2c313a;
40
+ --block-radius: 2px;
41
+ --shadow: 0 10px 30px rgba(6, 8, 11, 0.7);
42
+
43
+ /* ── code ───────────────────────────────── */
44
+ --code-bg: #1a1d23;
45
+ --code-fg: #edece7;
46
+ --hl-keyword: #f2b32c;
47
+ --hl-string: #b9cc72;
48
+ --hl-number: #e8a45e;
49
+ --hl-comment: #7c828c;
50
+ --hl-function: #85b4e3;
51
+ --hl-type: #cb9ada;
52
+ --hl-punct: #a0a4ab;
53
+
54
+ /* ── diagram ────────────────────────────── */
55
+ /* The fills stay dark: --d-muted is the binding gate (2.6 against every one
56
+ of them), and a light box would fail it long before the canvas noticed. */
57
+ --d-stroke: #7f858f;
58
+ --d-text: #edece7;
59
+ --d-muted: #a0a4ab;
60
+ --d-accent: #f2b32c;
61
+ --d-fill-1: #232830;
62
+ --d-fill-2: #2b2519;
63
+ --d-fill-3: #1e2730;
64
+ --d-fill-4: #2a2430;
65
+ --d-fill-5: #1f2c28;
66
+ --d-fill-6: #302422;
67
+
68
+ /* ── terminal ───────────────────────────── */
69
+ --term-bg: #0f1216;
70
+ --term-fg: #e2e0da;
71
+ --term-prompt: #f2b32c;
72
+ --term-cursor: #f2b32c;
73
+ --term-selection: rgba(242, 179, 44, 0.28);
74
+ --ansi-black: #8a8e96;
75
+ --ansi-red: #e0574b;
76
+ --ansi-green: #9cc474;
77
+ --ansi-yellow: #f2b32c;
78
+ --ansi-blue: #7fa8d8;
79
+ --ansi-magenta: #c99ad6;
80
+ --ansi-cyan: #79c6c0;
81
+ --ansi-white: #e2e0da;
82
+ --ansi-bright-black: #a8acb4;
83
+ --ansi-bright-red: #ef7f74;
84
+ --ansi-bright-green: #b7d996;
85
+ --ansi-bright-yellow: #f8cc6a;
86
+ --ansi-bright-blue: #a3c3e8;
87
+ --ansi-bright-magenta: #dcb6e5;
88
+ --ansi-bright-cyan: #9adcd7;
89
+ --ansi-bright-white: #f4f2ed;
90
+
91
+ /* ── builds ─────────────────────────────── */
92
+ --dim-opacity: 0.3;
93
+ }
94
+
95
+ /* Uppercase, tightly tracked eyebrows are part of the identity; the mono
96
+ heading face carries it without needing a webfont. */
97
+ .decklight h1,
98
+ .decklight h2 {
99
+ letter-spacing: -0.01em;
100
+ }
101
+
102
+ /* The subject renders one scanline at a time, so the canvas does too — a
103
+ 1-in-3 line at ~2% opacity. Screen only, never in print, and it steps aside
104
+ for anyone who asked for less motion-and-texture. */
105
+ @media screen {
106
+ .decklight::after {
107
+ content: "";
108
+ position: absolute;
109
+ inset: 0;
110
+ pointer-events: none;
111
+ z-index: 3;
112
+ background: repeating-linear-gradient(
113
+ to bottom,
114
+ rgba(255, 255, 255, 0.022) 0px,
115
+ rgba(255, 255, 255, 0.022) 1px,
116
+ transparent 1px,
117
+ transparent 3px
118
+ );
119
+ }
120
+ }
@@ -0,0 +1,43 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // One place that knows how to start a headless Chrome. Four files were each
5
+ // carrying their own copy of this list, and each one was a chance to get it
6
+ // wrong — the character harness still had only the macOS path, so it could never
7
+ // have run in CI at all.
8
+
9
+ import { existsSync } from 'node:fs';
10
+
11
+ const CANDIDATES = [
12
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
13
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
14
+ '/usr/bin/chromium', '/usr/bin/chromium-browser',
15
+ '/snap/bin/chromium',
16
+ `${process.env.HOME}/.nix-profile/bin/chromium`,
17
+ ];
18
+
19
+ /** The browser to drive: $CHROME wins, else the first one installed. */
20
+ export function chromeBin(who = 'chrome') {
21
+ const bin = process.env.CHROME || process.env.DECKLIGHT_CHROME
22
+ || CANDIDATES.find((p) => existsSync(p));
23
+ if (!bin) {
24
+ console.error(`${who}: no Chrome found — install one, or point $CHROME at it`);
25
+ process.exit(1);
26
+ }
27
+ return bin;
28
+ }
29
+
30
+ /**
31
+ * Flags every headless run needs.
32
+ *
33
+ * --no-sandbox ONLY under CI: GitHub's Ubuntu runners restrict unprivileged user
34
+ * namespaces (AppArmor), so Chrome's zygote cannot start there and dies with
35
+ * "No usable sandbox!". The container is ephemeral and the pages are our own test
36
+ * files, so dropping it there is fine — but a developer's machine keeps its
37
+ * sandbox, because that is where a real browser would open a real page.
38
+ */
39
+ export const chromeArgs = (...extra) => [
40
+ '--headless', '--disable-gpu',
41
+ ...(process.env.CI ? ['--no-sandbox'] : []),
42
+ ...extra,
43
+ ];
@@ -1,3 +1,6 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
1
4
  // Shared Gemini TTS synthesis (Vertex AI) — used by tools/voiceover.mjs
2
5
  // (batch pre-render) and tools/voiceover-server.mjs (live bridge for the
3
6
  // player). generateContent with responseModalities AUDIO returns base64 raw
@@ -8,6 +11,15 @@
8
11
 
9
12
  import { execFileSync } from 'node:child_process';
10
13
 
14
+ /**
15
+ * GCP project ids: 6–30 chars, lowercase, leading letter, no trailing hyphen.
16
+ * Worth checking rather than letting Vertex answer, because `project` is
17
+ * interpolated straight into the request path — punctuation dragged in from a
18
+ * copy-paste comes back as an opaque 403 on a project that "doesn't exist",
19
+ * and a stray slash would rewrite the URL outright.
20
+ */
21
+ export const validProjectId = (id) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(id ?? '');
22
+
11
23
  // The prebuilt voice roster (docs' flavor words) — the player shows this
12
24
  // same list, keep the two in sync (engine.js GEMINI_VOICES).
13
25
  export const GEMINI_VOICES = [
@@ -23,7 +35,9 @@ export const GEMINI_VOICES = [
23
35
  ['Sadachbia', 'lively'], ['Sadaltager', 'knowledgeable'], ['Sulafat', 'warm'],
24
36
  ];
25
37
 
26
- function gcloudToken() {
38
+ // ADC, not `gcloud auth login` — a separate credential store, and the one every
39
+ // Google client library reads. Shared with the Chirp engine (tools/tts-engines.mjs).
40
+ export function gcloudToken() {
27
41
  return execFileSync('gcloud', ['auth', 'application-default', 'print-access-token'],
28
42
  { encoding: 'utf8' }).trim();
29
43
  }
@@ -79,6 +93,7 @@ export function styledPrompt(style, text) {
79
93
  */
80
94
  export function createSynth({ project, ttsModel, location } = {}) {
81
95
  if (!project) throw new Error('Gemini TTS needs a GCP project — pass { project } (CLI: --project <id> or set GOOGLE_CLOUD_PROJECT)');
96
+ if (!validProjectId(project)) throw new Error(`not a GCP project id: ${JSON.stringify(project)} — expected 6-30 chars, lowercase letters, digits and hyphens, starting with a letter (stray punctuation from a copy-paste?)`);
82
97
  let token = null;
83
98
  let route = null;
84
99
 
@@ -108,6 +123,9 @@ export function createSynth({ project, ttsModel, location } = {}) {
108
123
  model,
109
124
  promptTokens: um.promptTokenCount ?? 0,
110
125
  audioTokens: um.candidatesTokenCount ?? 0,
126
+ chars: text.length,
127
+ // every engine reports a `note`, so the bridge logs one line for all
128
+ note: `${um.promptTokenCount ?? 0}+${um.candidatesTokenCount ?? 0} tokens`,
111
129
  cost: estimateCost(model, um),
112
130
  },
113
131
  };
@@ -0,0 +1,249 @@
1
+ #!/usr/bin/env node
2
+ // Lip-sync bridge: a tiny local HTTP server the player calls to turn
3
+ // narration audio into lip-sync data for the character overlay (SPEC §8).
4
+ // Everything runs on THIS machine — Rhubarb Lip Sync for viseme timelines,
5
+ // Wav2Lip / SadTalker (local python repos, your GPU) for talking-head video.
6
+ // No cloud service is involved; the browser just can't spawn native
7
+ // processes, so this bridge does, exactly like `decklight tts` holds the
8
+ // Google credentials the browser can't.
9
+ //
10
+ // GET /ping → { ok, engines: { viseme, video: [names] }, portraits }
11
+ // POST /viseme?text=<transcript> (body: audio/wav)
12
+ // → viseme timeline JSON v1 (tools/visemes.mjs)
13
+ // POST /video?engine=wav2lip&portrait=<name> (body: audio/wav)
14
+ // → video/mp4 (muted talking head)
15
+ //
16
+ // decklight lipsync [--port 8789] [--rhubarb <bin>]
17
+ // [--portrait <name=img.png>]… (first one is 'default')
18
+ // [--wav2lip-dir <repo> --wav2lip-ckpt <pth>]
19
+ // [--sadtalker-dir <repo>] [--python <bin>]
20
+ // [--cache-dir ~/.cache/decklight/lipsync]
21
+ //
22
+ // Rhubarb: https://github.com/DanielSWolf/rhubarb-lip-sync — one static
23
+ // binary, ~0.1× real-time. The transcript (?text=) markedly improves cue
24
+ // accuracy, so the player always sends it. Wav2Lip suits LIVE mode (static
25
+ // pose → seamless per-sentence cuts, near real-time on a decent GPU);
26
+ // SadTalker suits BATCH clips (tools/lipsync.mjs) — minutes per clip.
27
+ //
28
+ // CORS is wide open (decks run on file://, origin "null") — the server binds
29
+ // 127.0.0.1 only. Results are cached ON DISK keyed by a hash of (audio,
30
+ // route, params): restarts keep the cache, so a replayed deck costs nothing
31
+ // and the player's 10-sentence lookahead only ever pays for new sentences.
32
+
33
+ import { createServer } from 'node:http';
34
+ import { createHash } from 'node:crypto';
35
+ import { execFile } from 'node:child_process';
36
+ import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, renameSync, readdirSync, statSync, copyFileSync } from 'node:fs';
37
+ import { join, resolve, basename } from 'node:path';
38
+ import { homedir } from 'node:os';
39
+ import { promisify } from 'node:util';
40
+ import { normalizeRhubarb } from './visemes.mjs';
41
+
42
+ const run = promisify(execFile);
43
+
44
+ // width-limited job queue: rhubarb gets 2 lanes, the GPU exactly 1 — a burst
45
+ // of lookahead prefetches must never launch parallel model runs
46
+ function makeQueue(width) {
47
+ let active = 0;
48
+ const waiting = [];
49
+ const next = () => {
50
+ if (active >= width || !waiting.length) return;
51
+ active++;
52
+ const { fn, res, rej } = waiting.shift();
53
+ fn().then(res, rej).finally(() => { active--; next(); });
54
+ };
55
+ return (fn) => new Promise((res, rej) => { waiting.push({ fn, res, rej }); next(); });
56
+ }
57
+
58
+ export async function lipsyncMain(args) {
59
+ if (args.includes('--help')) {
60
+ console.log(`usage: decklight lipsync [--port 8789] [--rhubarb <bin>]
61
+ [--portrait <name=img.png>]... portraits offered for video mode (first = default)
62
+ [--wav2lip-dir <repo> --wav2lip-ckpt <checkpoint.pth>]
63
+ [--sadtalker-dir <repo>] [--python python3]
64
+ [--cache-dir ~/.cache/decklight/lipsync]
65
+
66
+ Viseme timelines need rhubarb on PATH (or --rhubarb):
67
+ https://github.com/DanielSWolf/rhubarb-lip-sync
68
+ Talking-head video needs a local Wav2Lip and/or SadTalker checkout, a GPU,
69
+ and at least one --portrait. Everything runs offline on this machine.`);
70
+ return;
71
+ }
72
+ const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
73
+ const opts = (flag) => args.flatMap((a, i) => (a === flag ? [args[i + 1]] : []));
74
+ const port = Number(opt('--port', 8789));
75
+ const rhubarb = opt('--rhubarb', 'rhubarb');
76
+ const python = opt('--python', 'python3');
77
+ const wav2lipDir = opt('--wav2lip-dir');
78
+ const wav2lipCkpt = opt('--wav2lip-ckpt');
79
+ const sadtalkerDir = opt('--sadtalker-dir');
80
+ const cacheDir = resolve(opt('--cache-dir', join(homedir(), '.cache', 'decklight', 'lipsync')));
81
+ mkdirSync(cacheDir, { recursive: true });
82
+
83
+ // portraits: --portrait alice=face.png (or a bare path — named by basename)
84
+ const portraits = new Map();
85
+ for (const p of opts('--portrait')) {
86
+ if (!p) continue;
87
+ const eq = p.indexOf('=');
88
+ const name = eq > 0 ? p.slice(0, eq) : basename(p).replace(/\.[^.]+$/, '');
89
+ const file = resolve(eq > 0 ? p.slice(eq + 1) : p);
90
+ if (!existsSync(file)) { console.error(`portrait not found: ${file}`); process.exitCode = 1; return; }
91
+ if (!portraits.size) portraits.set('default', file); // first doubles as 'default'
92
+ portraits.set(name, file);
93
+ }
94
+
95
+ const has = async (bin, flags = ['--version']) => {
96
+ try { await run(bin, flags); return true; } catch (e) { return e?.code !== 'ENOENT'; }
97
+ };
98
+ const visemeOk = await has(rhubarb);
99
+ const ffmpegOk = await has('ffmpeg', ['-version']);
100
+ const videoEngines = [];
101
+ if (wav2lipDir && wav2lipCkpt && existsSync(join(wav2lipDir, 'inference.py')) && existsSync(wav2lipCkpt) && portraits.size) videoEngines.push('wav2lip');
102
+ if (sadtalkerDir && existsSync(join(sadtalkerDir, 'inference.py')) && portraits.size) videoEngines.push('sadtalker');
103
+ if (!visemeOk && !videoEngines.length) {
104
+ console.error(`neither engine is usable:
105
+ visemes — rhubarb not found (install it, or pass --rhubarb <bin>)
106
+ video — needs --wav2lip-dir/--wav2lip-ckpt or --sadtalker-dir, plus --portrait`);
107
+ process.exitCode = 1;
108
+ return;
109
+ }
110
+
111
+ const rhubarbQ = makeQueue(2);
112
+ const gpuQ = makeQueue(1);
113
+ const inflight = new Map(); // cache key → promise, dedups concurrent misses
114
+ const dedup = (key, fn) => {
115
+ if (!inflight.has(key)) {
116
+ const p = fn().finally(() => inflight.delete(key));
117
+ inflight.set(key, p);
118
+ }
119
+ return inflight.get(key);
120
+ };
121
+ const sha = (...parts) => {
122
+ const h = createHash('sha256');
123
+ for (const p of parts) h.update(p);
124
+ return h.digest('hex').slice(0, 32);
125
+ };
126
+
127
+ async function visemes(wav, text) {
128
+ const key = sha('viseme|', text, '|', wav);
129
+ const out = join(cacheDir, `${key}.json`);
130
+ if (existsSync(out)) return { body: readFileSync(out), cached: true };
131
+ await dedup(key, () => rhubarbQ(async () => {
132
+ if (existsSync(out)) return;
133
+ const tmpWav = join(cacheDir, `${key}.tmp.wav`);
134
+ const tmpTxt = join(cacheDir, `${key}.tmp.txt`);
135
+ const tmpOut = join(cacheDir, `${key}.tmp.json`);
136
+ writeFileSync(tmpWav, wav);
137
+ const dialog = text.trim() ? (writeFileSync(tmpTxt, text), ['--dialogFile', tmpTxt]) : [];
138
+ try {
139
+ const t0 = Date.now();
140
+ await run(rhubarb, ['-f', 'json', '-o', tmpOut, '--machineReadable', ...dialog, tmpWav], { timeout: 120000 });
141
+ const tl = normalizeRhubarb(JSON.parse(readFileSync(tmpOut, 'utf8')));
142
+ writeFileSync(out, JSON.stringify(tl));
143
+ console.log(` viseme: ${(wav.length / 1024).toFixed(0)} KB wav → ${tl.cues.length} cues · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
144
+ } finally {
145
+ for (const f of [tmpWav, tmpTxt, tmpOut]) rmSync(f, { force: true });
146
+ }
147
+ }));
148
+ return { body: readFileSync(out), cached: false };
149
+ }
150
+
151
+ async function video(wav, engine, portraitName) {
152
+ if (!videoEngines.includes(engine)) throw new Error(`engine '${engine}' not available`);
153
+ const face = portraits.get(portraitName);
154
+ if (!face) throw new Error(`unknown portrait '${portraitName}'`);
155
+ const key = sha('video|', engine, '|', readFileSync(face), '|', wav);
156
+ const out = join(cacheDir, `${key}.mp4`);
157
+ if (existsSync(out)) return { body: readFileSync(out), cached: true };
158
+ await dedup(key, () => gpuQ(async () => {
159
+ if (existsSync(out)) return;
160
+ const tmpWav = join(cacheDir, `${key}.tmp.wav`);
161
+ const tmpMp4 = join(cacheDir, `${key}.tmp.mp4`);
162
+ const tmpDir = join(cacheDir, `${key}.tmp.d`);
163
+ writeFileSync(tmpWav, wav);
164
+ try {
165
+ const t0 = Date.now();
166
+ process.stdout.write(` video ${engine} · ${portraitName}: ${(wav.length / 1024).toFixed(0)} KB wav … `);
167
+ if (engine === 'wav2lip') {
168
+ await run(python, ['inference.py', '--checkpoint_path', resolve(wav2lipCkpt),
169
+ '--face', face, '--audio', tmpWav, '--outfile', tmpMp4],
170
+ { cwd: resolve(wav2lipDir), timeout: 600000, maxBuffer: 64 * 1024 * 1024 });
171
+ } else {
172
+ mkdirSync(tmpDir, { recursive: true });
173
+ await run(python, ['inference.py', '--driven_audio', tmpWav,
174
+ '--source_image', face, '--result_dir', tmpDir],
175
+ { cwd: resolve(sadtalkerDir), timeout: 1800000, maxBuffer: 64 * 1024 * 1024 });
176
+ // SadTalker writes <timestamp>/….mp4 into result_dir — take the newest
177
+ const found = [];
178
+ const walk = (d) => { for (const f of readdirSync(d)) { const p = join(d, f); const s = statSync(p); if (s.isDirectory()) walk(p); else if (f.endsWith('.mp4')) found.push([s.mtimeMs, p]); } };
179
+ walk(tmpDir);
180
+ if (!found.length) throw new Error('sadtalker produced no mp4');
181
+ renameSync(found.sort((a, b) => b[0] - a[0])[0][1], tmpMp4);
182
+ }
183
+ // strip the audio track (playback is muted — narrAudio is the voice)
184
+ // and front-load the moov atom so the player can start instantly
185
+ if (ffmpegOk) await run('ffmpeg', ['-y', '-i', tmpMp4, '-an', '-movflags', '+faststart', '-c:v', 'copy', out], { timeout: 120000 });
186
+ else copyFileSync(tmpMp4, out);
187
+ console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s → ${(statSync(out).size / 1024).toFixed(0)} KB`);
188
+ } finally {
189
+ for (const f of [tmpWav, tmpMp4]) rmSync(f, { force: true });
190
+ rmSync(tmpDir, { recursive: true, force: true });
191
+ }
192
+ }));
193
+ return { body: readFileSync(out), cached: false };
194
+ }
195
+
196
+ const CORS = {
197
+ 'access-control-allow-origin': '*',
198
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
199
+ 'access-control-allow-headers': 'content-type',
200
+ 'access-control-expose-headers': 'x-lipsync-cached',
201
+ };
202
+
203
+ const server = createServer(async (req, res) => {
204
+ if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
205
+ const url = new URL(req.url, 'http://localhost');
206
+ if (req.method === 'GET' && url.pathname === '/ping') {
207
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
208
+ return res.end(JSON.stringify({
209
+ ok: true,
210
+ engines: { viseme: visemeOk, video: videoEngines },
211
+ portraits: [...portraits.keys()],
212
+ }));
213
+ }
214
+ if (req.method === 'POST' && (url.pathname === '/viseme' || url.pathname === '/video')) {
215
+ try {
216
+ // body read INSIDE the try: a client abort mid-request rejects the
217
+ // stream, and outside the try it would crash the whole bridge
218
+ const chunks = [];
219
+ for await (const c of req) chunks.push(c);
220
+ const wav = Buffer.concat(chunks);
221
+ if (wav.length < 44) { res.writeHead(400, CORS); return res.end('no audio'); }
222
+ const out = url.pathname === '/viseme'
223
+ ? await visemes(wav, url.searchParams.get('text') ?? '')
224
+ : await video(wav, url.searchParams.get('engine') ?? 'wav2lip', url.searchParams.get('portrait') ?? 'default');
225
+ res.writeHead(200, {
226
+ ...CORS,
227
+ 'content-type': url.pathname === '/viseme' ? 'application/json' : 'video/mp4',
228
+ 'x-lipsync-cached': out.cached ? '1' : '0',
229
+ });
230
+ return res.end(out.body);
231
+ } catch (e) {
232
+ console.error(` ${url.pathname.slice(1)} error: ${String(e).slice(0, 160)}`);
233
+ if (!res.headersSent) res.writeHead(502, CORS);
234
+ return res.end(String(e));
235
+ }
236
+ }
237
+ res.writeHead(404, CORS);
238
+ res.end();
239
+ });
240
+
241
+ server.listen(port, '127.0.0.1', () => {
242
+ const what = [visemeOk && 'visemes (rhubarb)', ...videoEngines.map((e) => `video (${e})`)].filter(Boolean).join(' · ');
243
+ console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
244
+ console.log(`cache: ${cacheDir}`);
245
+ });
246
+ return server;
247
+ }
248
+
249
+ if (import.meta.url === `file://${process.argv[1]}`) lipsyncMain(process.argv.slice(2));
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ // Lip-sync generator for RECORDED narration: sidecar files for every
3
+ // slide-NN audio clip in a voiceover directory (tools/voiceover.mjs or a
4
+ // ⇧V-recorded set), so a deck plays back with an animated character and no
5
+ // bridge running. Fully offline, like everything else here.
6
+ //
7
+ // node tools/lipsync.mjs <voiceover-dir> [--visemes] [--video]
8
+ // [--rhubarb <bin>]
9
+ // [--engine sadtalker|wav2lip] [--portrait <img>]
10
+ // [--wav2lip-dir <repo> --wav2lip-ckpt <pth>]
11
+ // [--sadtalker-dir <repo>] [--python python3]
12
+ //
13
+ // Outputs, next to the audio they belong to (config: narration.files dir):
14
+ // --visemes (default) — slide-NN.visemes.json (timeline v1, via Rhubarb)
15
+ // --video — slide-NN.mp4 (muted talking head)
16
+ //
17
+ // Rhubarb wants WAV: slide-NN.wav is used when present (voiceover.mjs
18
+ // --keep-wav, or a ⇧V set); otherwise the .m4a is decoded on the fly with
19
+ // ffmpeg (afconvert fallback on macOS). The transcript slide-NN.txt, when
20
+ // present, markedly improves cue accuracy. For batch video SadTalker is the
21
+ // default engine — per-slide clips are long enough that its natural head
22
+ // motion beats Wav2Lip's static pose (live mode is the reverse).
23
+ //
24
+ // Incremental like voiceover.mjs: lipsync.json stores a hash of
25
+ // (audio bytes, tool, engine, portrait) per slide, persisted after every
26
+ // slide, so a rerun only regenerates what actually changed.
27
+
28
+ import { readFileSync, writeFileSync, existsSync, readdirSync, rmSync, renameSync, mkdirSync, statSync } from 'node:fs';
29
+ import { createHash } from 'node:crypto';
30
+ import { execFileSync } from 'node:child_process';
31
+ import { resolve, join, basename } from 'node:path';
32
+ import { normalizeRhubarb } from './visemes.mjs';
33
+
34
+ const args = process.argv.slice(2);
35
+ const dirArg = args.find((a) => !a.startsWith('-'));
36
+ if (!dirArg || args.includes('--help')) {
37
+ console.error('usage: lipsync.mjs <voiceover-dir> [--visemes] [--video] [--rhubarb bin]\n'
38
+ + ' [--engine sadtalker|wav2lip] [--portrait img]\n'
39
+ + ' [--wav2lip-dir repo --wav2lip-ckpt pth] [--sadtalker-dir repo] [--python bin]');
40
+ process.exit(dirArg ? 0 : 1);
41
+ }
42
+ const dir = resolve(dirArg);
43
+ const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
44
+ const doVideo = args.includes('--video');
45
+ const doVisemes = args.includes('--visemes') || !doVideo; // visemes by default
46
+ const rhubarb = opt('--rhubarb', 'rhubarb');
47
+ const engine = opt('--engine', 'sadtalker');
48
+ const portrait = opt('--portrait') && resolve(opt('--portrait'));
49
+ const wav2lipDir = opt('--wav2lip-dir');
50
+ const wav2lipCkpt = opt('--wav2lip-ckpt');
51
+ const sadtalkerDir = opt('--sadtalker-dir');
52
+ const python = opt('--python', 'python3');
53
+
54
+ const have = (bin, flags = ['--version']) => {
55
+ try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
56
+ };
57
+ if (doVisemes && !have(rhubarb)) {
58
+ console.error(`rhubarb not found — install https://github.com/DanielSWolf/rhubarb-lip-sync or pass --rhubarb <bin>`);
59
+ process.exit(1);
60
+ }
61
+ if (doVideo) {
62
+ if (!portrait || !existsSync(portrait)) { console.error('--video needs --portrait <image>'); process.exit(1); }
63
+ if (engine === 'wav2lip' && !(wav2lipDir && wav2lipCkpt)) { console.error('--engine wav2lip needs --wav2lip-dir and --wav2lip-ckpt'); process.exit(1); }
64
+ if (engine === 'sadtalker' && !sadtalkerDir) { console.error('--engine sadtalker needs --sadtalker-dir'); process.exit(1); }
65
+ }
66
+ const ffmpegOk = have('ffmpeg', ['-version']);
67
+
68
+ // every slide-NN with audio, wav preferred over m4a
69
+ const slides = [...new Set(readdirSync(dir)
70
+ .map((f) => f.match(/^slide-(\d+)\.(wav|m4a)$/)?.[1])
71
+ .filter(Boolean))].sort();
72
+ if (!slides.length) { console.error(`${dir}: no slide-NN.wav/.m4a files`); process.exit(1); }
73
+ console.log(`${basename(dir)}: ${slides.length} slides with audio`);
74
+
75
+ // incremental state — its own file so voiceover.mjs reruns can't clobber it
76
+ const statePath = join(dir, 'lipsync.json');
77
+ let state = {};
78
+ try { state = JSON.parse(readFileSync(statePath, 'utf8')); } catch { /* first run */ }
79
+
80
+ const sha = (...parts) => {
81
+ const h = createHash('sha256');
82
+ for (const p of parts) h.update(p);
83
+ return h.digest('hex').slice(0, 16);
84
+ };
85
+
86
+ function toWav(nn) {
87
+ const wav = join(dir, `slide-${nn}.wav`);
88
+ if (existsSync(wav)) return { path: wav, tmp: false };
89
+ const m4a = join(dir, `slide-${nn}.m4a`);
90
+ const tmp = join(dir, `slide-${nn}.tmp.wav`);
91
+ if (ffmpegOk) execFileSync('ffmpeg', ['-y', '-i', m4a, tmp], { stdio: 'ignore' });
92
+ else execFileSync('afconvert', ['-f', 'WAVE', '-d', 'LEI16', m4a, tmp]);
93
+ return { path: tmp, tmp: true };
94
+ }
95
+
96
+ let made = 0, kept = 0;
97
+ for (const nn of slides) {
98
+ const audioFile = ['wav', 'm4a'].map((e) => join(dir, `slide-${nn}.${e}`)).find(existsSync);
99
+ const audioBytes = readFileSync(audioFile);
100
+ const txtPath = join(dir, `slide-${nn}.txt`);
101
+ const text = existsSync(txtPath) ? readFileSync(txtPath, 'utf8').trim() : '';
102
+ const st = (state[nn] ??= {});
103
+ const jobs = [];
104
+ if (doVisemes) jobs.push('visemes');
105
+ if (doVideo) jobs.push('video');
106
+
107
+ for (const job of jobs) {
108
+ const outFile = join(dir, job === 'visemes' ? `slide-${nn}.visemes.json` : `slide-${nn}.mp4`);
109
+ const hash = job === 'visemes'
110
+ ? sha('visemes|', text, '|', audioBytes)
111
+ : sha('video|', engine, '|', readFileSync(portrait), '|', audioBytes);
112
+ if (st[job] === hash && existsSync(outFile)) {
113
+ kept++;
114
+ console.log(` slide ${nn}: ${job} unchanged — kept`);
115
+ continue;
116
+ }
117
+ const wav = toWav(nn);
118
+ try {
119
+ const t0 = Date.now();
120
+ if (job === 'visemes') {
121
+ const tmpOut = join(dir, `slide-${nn}.tmp.visemes.json`);
122
+ const dialog = [];
123
+ if (text) { writeFileSync(join(dir, `slide-${nn}.tmp.txt`), text); dialog.push('--dialogFile', join(dir, `slide-${nn}.tmp.txt`)); }
124
+ execFileSync(rhubarb, ['-f', 'json', '-o', tmpOut, '--machineReadable', ...dialog, wav.path], { stdio: ['ignore', 'ignore', 'ignore'] });
125
+ const tl = normalizeRhubarb(JSON.parse(readFileSync(tmpOut, 'utf8')));
126
+ writeFileSync(outFile, JSON.stringify(tl));
127
+ rmSync(tmpOut, { force: true });
128
+ rmSync(join(dir, `slide-${nn}.tmp.txt`), { force: true });
129
+ console.log(` slide ${nn}: ${tl.cues.length} cues → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
130
+ } else {
131
+ const tmpMp4 = join(dir, `slide-${nn}.tmp.mp4`);
132
+ if (engine === 'wav2lip') {
133
+ execFileSync(python, ['inference.py', '--checkpoint_path', resolve(wav2lipCkpt),
134
+ '--face', portrait, '--audio', wav.path, '--outfile', tmpMp4],
135
+ { cwd: resolve(wav2lipDir), stdio: 'inherit' });
136
+ } else {
137
+ const resDir = join(dir, `slide-${nn}.tmp.d`);
138
+ mkdirSync(resDir, { recursive: true });
139
+ execFileSync(python, ['inference.py', '--driven_audio', wav.path,
140
+ '--source_image', portrait, '--result_dir', resDir],
141
+ { cwd: resolve(sadtalkerDir), stdio: 'inherit' });
142
+ const found = [];
143
+ const walk = (d) => { for (const f of readdirSync(d)) { const p = join(d, f); const s = statSync(p); if (s.isDirectory()) walk(p); else if (f.endsWith('.mp4')) found.push([s.mtimeMs, p]); } };
144
+ walk(resDir);
145
+ if (!found.length) throw new Error('sadtalker produced no mp4');
146
+ renameSync(found.sort((a, b) => b[0] - a[0])[0][1], tmpMp4);
147
+ rmSync(resDir, { recursive: true, force: true });
148
+ }
149
+ // mute + faststart: the player's audio always comes from narrAudio
150
+ if (ffmpegOk) {
151
+ execFileSync('ffmpeg', ['-y', '-i', tmpMp4, '-an', '-movflags', '+faststart', '-c:v', 'copy', outFile], { stdio: 'ignore' });
152
+ rmSync(tmpMp4, { force: true });
153
+ } else renameSync(tmpMp4, outFile);
154
+ console.log(` slide ${nn}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
155
+ }
156
+ st[job] = hash;
157
+ made++;
158
+ // crash-safe: persist progress after every slide (voiceover.mjs idiom)
159
+ writeFileSync(statePath, JSON.stringify(state, null, 1));
160
+ } finally {
161
+ if (wav.tmp) rmSync(wav.path, { force: true });
162
+ }
163
+ }
164
+ }
165
+ writeFileSync(statePath, JSON.stringify(state, null, 1));
166
+ console.log(`done → ${dir} (${made} generated${kept ? `, ${kept} unchanged` : ''})`);
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
2
5
  // Sync the locally generated voice tracks (demo/voiceover-site/<dir>/) to the
3
6
  // decklight.github.io repo under voices/<dir>/, in ONE commit via the Git
4
7
  // Data API. Only files whose git blob sha differs from the remote are