decklight 0.8.1 → 0.10.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 (138) hide show
  1. package/PLATFORM.md +707 -0
  2. package/README.md +226 -150
  3. package/SPEC.md +803 -888
  4. package/cli/agent-review.mjs +246 -0
  5. package/cli/agents.mjs +35 -9
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +190 -0
  10. package/cli/bundle-module.mjs +95 -0
  11. package/cli/bundle.mjs +439 -35
  12. package/cli/cast.mjs +48 -12
  13. package/cli/check-fixes.mjs +186 -0
  14. package/cli/check.mjs +988 -0
  15. package/cli/clone-deck.mjs +179 -0
  16. package/cli/commands.mjs +345 -0
  17. package/cli/comments.mjs +64 -18
  18. package/cli/commit-flow.mjs +51 -22
  19. package/cli/commit-message.mjs +51 -74
  20. package/cli/commit-split.mjs +601 -0
  21. package/cli/deck-refs.mjs +64 -0
  22. package/cli/deck-routes.mjs +67 -0
  23. package/cli/deckfile.mjs +3 -5
  24. package/cli/decklight.mjs +68 -289
  25. package/cli/design-system-deps.mjs +209 -0
  26. package/cli/design-system-edit.mjs +194 -0
  27. package/cli/design-system-refs.mjs +666 -0
  28. package/cli/design-system.mjs +497 -0
  29. package/cli/doctor.mjs +115 -0
  30. package/cli/edit-git.mjs +353 -0
  31. package/cli/edit-handover.mjs +551 -0
  32. package/cli/edit-look.mjs +631 -0
  33. package/cli/edit-slides.mjs +683 -0
  34. package/cli/edit.mjs +2585 -855
  35. package/cli/enhance.mjs +485 -0
  36. package/cli/extension.mjs +10 -10
  37. package/cli/font-refs.mjs +273 -0
  38. package/cli/font.mjs +246 -0
  39. package/cli/git-tree.mjs +1 -1
  40. package/cli/git.mjs +78 -11
  41. package/cli/import.mjs +56 -10
  42. package/cli/init.mjs +407 -236
  43. package/cli/library.mjs +127 -0
  44. package/cli/loader.mjs +3 -1
  45. package/cli/marketplace-autocheck.mjs +200 -0
  46. package/cli/marketplace.mjs +460 -29
  47. package/cli/narrate.mjs +251 -0
  48. package/cli/open-browser.mjs +63 -0
  49. package/cli/open.mjs +961 -0
  50. package/cli/pdf.mjs +64 -17
  51. package/cli/pkg.mjs +44 -2
  52. package/cli/plugin.mjs +43 -41
  53. package/cli/port-conflict.mjs +53 -23
  54. package/cli/pptx-export.mjs +63 -27
  55. package/cli/publish.mjs +8 -4
  56. package/cli/qr.mjs +1 -1
  57. package/cli/record.mjs +85 -23
  58. package/cli/remote.mjs +43 -17
  59. package/cli/restore.mjs +11 -4
  60. package/cli/review-ref.mjs +125 -0
  61. package/cli/review-remote.mjs +92 -48
  62. package/cli/review-routes.mjs +254 -0
  63. package/cli/review-store.mjs +47 -7
  64. package/cli/review-submit.mjs +47 -57
  65. package/cli/runtime-link.mjs +560 -0
  66. package/cli/serve.mjs +236 -45
  67. package/cli/setup.mjs +112 -0
  68. package/cli/sign.mjs +1 -1
  69. package/cli/skill-content.mjs +229 -35
  70. package/cli/skills.mjs +353 -26
  71. package/cli/start.mjs +110 -0
  72. package/cli/supervise.mjs +6 -6
  73. package/cli/theme-refs.mjs +527 -0
  74. package/cli/theme.mjs +181 -137
  75. package/cli/trust.mjs +83 -0
  76. package/cli/units.mjs +112 -47
  77. package/cli/update-check.mjs +1 -5
  78. package/cli/upgrade.mjs +194 -28
  79. package/cli/upstream.mjs +4 -3
  80. package/cli/util.mjs +4 -4
  81. package/cli/wizard.mjs +6 -6
  82. package/dist/build-info.json +1 -1
  83. package/dist/decklight.css +1533 -59
  84. package/dist/decklight.js +258 -115
  85. package/dist/decklight.js.map +4 -4
  86. package/docs/GLOSSARY.md +141 -0
  87. package/docs/architecture.svg +17 -17
  88. package/package.json +4 -2
  89. package/themes/README.md +9 -8
  90. package/themes/reveal-solarized.css +10 -0
  91. package/tools/args.mjs +20 -0
  92. package/tools/atomic-write.mjs +48 -0
  93. package/tools/brand-palette.mjs +717 -0
  94. package/tools/bridge.mjs +1 -1
  95. package/tools/build-groups.mjs +42 -0
  96. package/tools/color.mjs +48 -0
  97. package/tools/deck-html.mjs +396 -11
  98. package/tools/design-system-format.mjs +778 -0
  99. package/tools/design-system-migrations.mjs +207 -0
  100. package/tools/elevenlabs-tts.mjs +110 -17
  101. package/tools/exec.mjs +11 -3
  102. package/tools/extension-check.mjs +31 -7
  103. package/tools/font-format.mjs +190 -0
  104. package/tools/font-stacks.mjs +24 -0
  105. package/tools/gemini-tts.mjs +3 -0
  106. package/tools/lipsync-config.mjs +103 -0
  107. package/tools/lipsync-engines.mjs +205 -2
  108. package/tools/lipsync-server.mjs +264 -41
  109. package/tools/lipsync.mjs +37 -18
  110. package/tools/local-voice.mjs +32 -42
  111. package/tools/narration-manifest.mjs +270 -0
  112. package/tools/narration-synth.mjs +416 -0
  113. package/tools/pptx.mjs +776 -19
  114. package/tools/publish-targets.mjs +1 -1
  115. package/tools/publish-voices.mjs +3 -3
  116. package/tools/recording-impact.mjs +7 -3
  117. package/tools/render-theme.mjs +33 -0
  118. package/tools/review-anchor.mjs +28 -12
  119. package/tools/semver.mjs +40 -0
  120. package/tools/sentences.mjs +180 -0
  121. package/tools/shot.mjs +14 -7
  122. package/tools/site-clip.mjs +114 -0
  123. package/tools/site-voices.mjs +232 -0
  124. package/tools/template-theme.mjs +1 -1
  125. package/tools/test-impact.mjs +17 -10
  126. package/tools/theme-check.mjs +30 -3
  127. package/tools/tts-cache.mjs +4 -3
  128. package/tools/tts-engines.mjs +38 -20
  129. package/tools/tts-setup.mjs +7 -7
  130. package/tools/video-options.mjs +34 -0
  131. package/tools/video.mjs +530 -54
  132. package/tools/voiceover-server.mjs +185 -104
  133. package/tools/voiceover.mjs +119 -261
  134. package/tools/zip.mjs +1 -1
  135. package/cli/dev.mjs +0 -623
  136. package/cli/present.mjs +0 -853
  137. package/cli/review.mjs +0 -361
  138. package/tools/publish-site-voices.mjs +0 -75
@@ -0,0 +1,190 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The font package format, and the rules it is held to (SPEC FONTS). A font
5
+ // is what a theme NAMES and cannot carry: a theme's --font-body is a list of
6
+ // family names, and the files behind a name that is not on the machine come
7
+ // from somewhere else — a Google Fonts @import that needs the network, or
8
+ // nothing. A font package carries the faces themselves, by reference from a
9
+ // marketplace, so a deck (and its bundle) has them wherever it is opened.
10
+ //
11
+ // <name>/
12
+ // font.json apiVersion, name, version, title, family, fallback,
13
+ // license, faces [{ file, weight, style }] (+ description, role)
14
+ // *.woff2 the faces — woff2 or woff, nothing else that runs or loads
15
+ // OFL.txt … the licence the manifest names: a hand-over redistributes
16
+ // the font, so a package without one is refused
17
+ //
18
+ // PURE: texts and a file list in, never a path. `decklight font gate` is a
19
+ // thin main over it, and the same rules run again wherever a package is
20
+ // served — and `fontFaceCss` is the one place an @font-face rule is written,
21
+ // for the servers and for bundle alike.
22
+
23
+ import { SEMVER_RE } from './semver.mjs';
24
+ import { NAME_RE, packagePathProblem } from './design-system-format.mjs';
25
+
26
+ /** The font-package contract's own version — additive only, like DESIGN_SYSTEM_API_VERSION. */
27
+ export const FONT_API_VERSION = 1;
28
+
29
+ /** What a face may be. The magic bytes are checked too: an extension is a claim. */
30
+ export const FACE_EXTENSIONS = ['woff2', 'woff'];
31
+ const MAGIC = { woff2: 'wOF2', woff: 'wOFF' };
32
+
33
+ /** Past this, a face is a warning — every deck that uses it, and every bundle, carries it. */
34
+ export const FACE_WARN_BYTES = 512 * 1024;
35
+
36
+ /** A family name as a stylesheet will quote it: letters, digits, spaces, _ and -. */
37
+ export const FAMILY_RE = /^[A-Za-z0-9][A-Za-z0-9 _-]{0,63}$/;
38
+ /** A fallback stack: family names (quoted or not), commas, spaces — nothing that could close a rule. */
39
+ const FALLBACK_RE = /^[A-Za-z0-9 ,'"_-]{1,200}$/;
40
+ const GENERIC = /(^|,)\s*(serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|ui-rounded|math|emoji)\s*$/;
41
+ export const ROLES = ['body', 'heading', 'mono', 'any'];
42
+
43
+ const lineAt = (text, index) => text.slice(0, index).split('\n').length;
44
+ const keyLine = (raw, key) => {
45
+ const i = raw.indexOf(`"${key}"`);
46
+ return i < 0 ? 1 : lineAt(raw, i);
47
+ };
48
+ const ext = (path) => (/\.([A-Za-z0-9]+)$/.exec(path)?.[1] ?? '').toLowerCase();
49
+ /** Top-level papers that are part of a package without being faces. */
50
+ const isPapers = (p) => /^(readme|license|licence|changelog|notice|ofl|authors|fontlog)([._-][\w.-]*)?(\.(md|txt))?$/i.test(p);
51
+
52
+ /** A weight as CSS takes it: a number 1–1000, or a variable font's "lo hi" range. */
53
+ function weightProblem(w) {
54
+ if (Number.isInteger(w)) return w >= 1 && w <= 1000 ? null : 'is outside 1–1000';
55
+ if (typeof w === 'string' && /^\d{1,4} \d{1,4}$/.test(w)) {
56
+ const [lo, hi] = w.split(' ').map(Number);
57
+ return lo >= 1 && hi <= 1000 && lo < hi ? null : 'must be "lo hi" with 1 ≤ lo < hi ≤ 1000';
58
+ }
59
+ return 'must be a number (400) or a variable font\'s range ("100 900")';
60
+ }
61
+
62
+ /**
63
+ * `font.json`, parsed and shaped: `{ manifest, problems }`, `manifest` null
64
+ * when the JSON itself does not parse.
65
+ */
66
+ export function readFontManifest(raw) {
67
+ const problems = [];
68
+ const file = 'font.json';
69
+ const at = (rule, key, msg) => problems.push({ file, line: keyLine(raw, key), rule, msg });
70
+ let m;
71
+ try { m = JSON.parse(raw); } catch (e) {
72
+ const pos = /position (\d+)/.exec(e.message)?.[1];
73
+ problems.push({ file, line: pos ? lineAt(raw, Number(pos)) : 1, rule: 'manifest-json', msg: `not valid JSON — ${e.message}` });
74
+ return { manifest: null, problems };
75
+ }
76
+ if (!m || typeof m !== 'object' || Array.isArray(m)) {
77
+ problems.push({ file, line: 1, rule: 'manifest-json', msg: 'must be a JSON object' });
78
+ return { manifest: null, problems };
79
+ }
80
+ if (!Number.isInteger(m.apiVersion) || m.apiVersion < 1) at('manifest-field', 'apiVersion', 'apiVersion must be a positive integer — the font format version this package needs');
81
+ else if (m.apiVersion > FONT_API_VERSION) at('api-too-new', 'apiVersion', `apiVersion ${m.apiVersion} needs a newer decklight — this one reads fonts up to ${FONT_API_VERSION}`);
82
+ if (typeof m.name !== 'string' || !NAME_RE.test(m.name)) at('manifest-field', 'name', `name ${JSON.stringify(m.name)} — a lowercase word: letters, digits and -, starting with a letter`);
83
+ if (typeof m.version !== 'string' || !SEMVER_RE.test(m.version)) at('manifest-field', 'version', `version ${JSON.stringify(m.version)} — a semver version, major.minor.patch (e.g. "4.1.0"), no leading v`);
84
+ if (typeof m.title !== 'string' || !m.title.trim()) at('manifest-field', 'title', 'title must be the font\'s human name, e.g. "Inter"');
85
+ if (typeof m.family !== 'string' || !FAMILY_RE.test(m.family)) {
86
+ at('manifest-field', 'family', `family ${JSON.stringify(m.family)} — the CSS family name a theme writes in --font-body: letters, digits, spaces, _ and -`);
87
+ }
88
+ if (typeof m.fallback !== 'string' || !FALLBACK_RE.test(m.fallback)) {
89
+ at('manifest-field', 'fallback', `fallback ${JSON.stringify(m.fallback)} — the stack used until the face loads, e.g. "system-ui, sans-serif": names, commas and quotes only`);
90
+ } else if (!GENERIC.test(m.fallback)) {
91
+ at('manifest-field', 'fallback', `fallback "${m.fallback}" must end in a generic family (sans-serif, serif, monospace, system-ui, …) — the one name every machine has`);
92
+ }
93
+ if (typeof m.license !== 'string') at('manifest-field', 'license', 'license must name the licence file in the package, e.g. "OFL.txt" — a font is licensed, and a deck that carries it redistributes it');
94
+ else {
95
+ const why = packagePathProblem(m.license);
96
+ if (why) at('file-outside', 'license', `license "${m.license}" ${why}`);
97
+ }
98
+ if (m.description !== undefined && typeof m.description !== 'string') at('manifest-field', 'description', 'description must be a string');
99
+ if (m.role !== undefined && !ROLES.includes(m.role)) at('manifest-field', 'role', `role must be one of ${ROLES.join(', ')} — what the font is drawn for`);
100
+ if (!Array.isArray(m.faces) || !m.faces.length) at('manifest-field', 'faces', 'faces must be a non-empty array of { file, weight, style }');
101
+ else {
102
+ const seen = new Set();
103
+ m.faces.forEach((f, i) => {
104
+ if (!f || typeof f !== 'object') { at('manifest-field', 'faces', `faces[${i}] must be { file, weight, style }`); return; }
105
+ if (typeof f.file !== 'string') at('manifest-field', 'faces', `faces[${i}].file must name a .woff2 or .woff in the package`);
106
+ else {
107
+ const why = packagePathProblem(f.file);
108
+ if (why) at('file-outside', 'faces', `faces[${i}].file "${f.file}" ${why}`);
109
+ else if (!FACE_EXTENSIONS.includes(ext(f.file))) at('face-extension', 'faces', `faces[${i}].file "${f.file}" — a face is ${FACE_EXTENSIONS.join(' or ')}`);
110
+ }
111
+ const wp = weightProblem(f.weight ?? 400);
112
+ if (wp) at('manifest-field', 'faces', `faces[${i}].weight ${JSON.stringify(f.weight)} ${wp}`);
113
+ const style = f.style ?? 'normal';
114
+ if (!['normal', 'italic'].includes(style)) at('manifest-field', 'faces', `faces[${i}].style must be "normal" or "italic"`);
115
+ const key = `${f.weight ?? 400}/${style}`;
116
+ if (seen.has(key)) at('face-twice', 'faces', `faces[${i}] is weight ${f.weight ?? 400} ${style} again — one file per weight and style`);
117
+ seen.add(key);
118
+ });
119
+ }
120
+ return { manifest: m, problems };
121
+ }
122
+
123
+ /**
124
+ * The admission gate over a package in memory: `{ manifest, files: Map<path,
125
+ * { size, head?, text? }> }` — `head` the first bytes as a latin1 string, for
126
+ * the magic check. Returns `{ ok, problems, warnings, summary }`.
127
+ */
128
+ export function checkFontPackage(pkg) {
129
+ const files = pkg.files ?? new Map();
130
+ const { manifest, problems } = readFontManifest(String(pkg.manifest ?? ''));
131
+ const warnings = [];
132
+ const summary = {};
133
+ if (!manifest) return { ok: false, problems, warnings, summary };
134
+ Object.assign(summary, {
135
+ name: manifest.name, version: manifest.version, apiVersion: manifest.apiVersion, title: manifest.title,
136
+ family: manifest.family, fallback: manifest.fallback, role: manifest.role ?? 'any', license: manifest.license,
137
+ });
138
+ if (typeof manifest.license === 'string' && !packagePathProblem(manifest.license)) {
139
+ const lic = files.get(manifest.license);
140
+ if (!lic) problems.push({ file: 'font.json', line: keyLine(String(pkg.manifest), 'license'), rule: 'license-missing', msg: `license names ${manifest.license}, which is not in the package — a font travels with its licence or not at all` });
141
+ else if (!lic.size) problems.push({ file: manifest.license, rule: 'license-missing', msg: 'the licence file is empty' });
142
+ }
143
+ const faces = [];
144
+ const named = new Set();
145
+ for (const [i, f] of (Array.isArray(manifest.faces) ? manifest.faces : []).entries()) {
146
+ if (!f || typeof f.file !== 'string' || packagePathProblem(f.file) || !FACE_EXTENSIONS.includes(ext(f.file))) continue;
147
+ named.add(f.file);
148
+ const got = files.get(f.file);
149
+ if (!got) { problems.push({ file: 'font.json', line: keyLine(String(pkg.manifest), 'faces'), rule: 'file-missing', msg: `faces[${i}].file ${f.file} is not in the package` }); continue; }
150
+ if (typeof got.head === 'string' && !got.head.startsWith(MAGIC[ext(f.file)])) {
151
+ problems.push({ file: f.file, rule: 'face-not-a-font', msg: `${f.file} is not a ${ext(f.file)} file — its first bytes are not "${MAGIC[ext(f.file)]}"` });
152
+ }
153
+ if ((got.size ?? 0) > FACE_WARN_BYTES) {
154
+ warnings.push({ file: f.file, rule: 'face-size', msg: `${Math.round(got.size / 1024)} KB — over the ${FACE_WARN_BYTES / 1024} KB a face should weigh; every deck and bundle that uses it carries it (subset it, or ship woff2)` });
155
+ }
156
+ faces.push({ file: f.file, weight: f.weight ?? 400, style: f.style ?? 'normal', size: got.size ?? 0 });
157
+ }
158
+ // anything else in the package: papers are fine, and so is nothing else
159
+ for (const path of files.keys()) {
160
+ if (path === 'font.json' || path === manifest.license || named.has(path)) continue;
161
+ if (path.split('/').some((seg) => seg.startsWith('.'))) continue;
162
+ if (!path.includes('/') && isPapers(path)) continue;
163
+ if (FACE_EXTENSIONS.includes(ext(path))) {
164
+ warnings.push({ file: path, rule: 'face-unused', msg: 'a face font.json does not list — it is never served' });
165
+ continue;
166
+ }
167
+ problems.push({ file: path, rule: 'file-kind', msg: `.${ext(path) || '(none)'} has no place in a font package — font.json, its faces (${FACE_EXTENSIONS.join(', ')}) and its licence` });
168
+ }
169
+ summary.faces = faces;
170
+ summary.bytes = faces.reduce((t, f) => t + f.size, 0);
171
+ return { ok: problems.length === 0, problems, warnings, summary };
172
+ }
173
+
174
+ /** The family and its fallback as a theme token would hold them: `'Inter', system-ui, sans-serif`. */
175
+ export const fontStack = (m) => `'${m.family}', ${m.fallback}`;
176
+
177
+ /**
178
+ * The @font-face rules for a package, one per face, each `src` from
179
+ * `urlFor(file, face)` — a served path, or a bundle's data: URI. The family
180
+ * and every value were held to the manifest's rules, so nothing here can
181
+ * close the rule it sits in. `font-display: swap`: the fallback shows at once
182
+ * and the face replaces it — a slide is never blank while a font loads.
183
+ */
184
+ export function fontFaceCss(manifest, urlFor) {
185
+ return (manifest.faces ?? []).map((f) => {
186
+ const format = ext(f.file) === 'woff2' ? 'woff2' : 'woff';
187
+ return `@font-face { font-family: '${manifest.family}'; src: url("${urlFor(f.file, f)}") format("${format}");`
188
+ + ` font-weight: ${f.weight ?? 400}; font-style: ${f.style ?? 'normal'}; font-display: swap; }`;
189
+ }).join('\n');
190
+ }
@@ -0,0 +1,24 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The font picker's stacks (SPEC PRESENTING, FONTS): families every machine
5
+ // already has, by kind. Here, not in src/core/fonts.js, because the CLI names
6
+ // them too — a design system may recommend `humanist`, and `design-system
7
+ // add` applies it — and cli/ never imports from src/.
8
+
9
+ /** The stacks, in cycle order. Their ORDER is the old pref's meaning (an index) — append, never reorder. */
10
+ export const STACKS = [
11
+ ['theme default', null],
12
+ ['system sans', "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"],
13
+ ['rounded', "ui-rounded, 'SF Pro Rounded', 'Hiragino Maru Gothic ProN', Quicksand, Comfortaa, 'Arial Rounded MT Bold', Calibri, sans-serif"],
14
+ ['humanist', "Seravek, 'Gill Sans Nova', Ubuntu, Calibri, 'DejaVu Sans', source-sans-pro, sans-serif"],
15
+ ['geometric', "'Avenir Next', Avenir, Montserrat, Corbel, 'URW Gothic', source-sans-pro, sans-serif"],
16
+ ['classical serif', "'Iowan Old Style', 'Palatino Linotype', Palatino, Georgia, serif"],
17
+ ['transitional serif', "Charter, 'Bitstream Charter', 'Sitka Text', Cambria, Georgia, serif"],
18
+ ['slab serif', "Rockwell, 'Rockwell Nova', 'Roboto Slab', 'DejaVu Serif', 'Sitka Small', serif"],
19
+ ['monospace', "'SF Mono', SFMono-Regular, ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace"],
20
+ ];
21
+
22
+
23
+ /** The stack labels — what a deck's `font` default or a recommendation may name. */
24
+ export const STACK_LABELS = STACKS.map(([label]) => label);
@@ -121,6 +121,9 @@ export function createSynth({ project, ttsModel, location } = {}) {
121
121
  const res = await fetch(url, {
122
122
  method: 'POST',
123
123
  headers: authHeaders(token, project),
124
+ // bounded like every other call the bridge makes: a request Vertex never
125
+ // answers used to leave the player's /speak pending for good
126
+ signal: AbortSignal.timeout(NETWORK_MS),
124
127
  body: JSON.stringify({
125
128
  contents: [{ role: 'user', parts: [{ text }] }],
126
129
  generationConfig: {
@@ -0,0 +1,103 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The talking-head setup, remembered (SPEC PRESENTING, character).
6
+ *
7
+ * Neural video needs four things decklight cannot find on its own: a Wav2Lip
8
+ * (or SadTalker) checkout, its checkpoint, the Python that has its packages,
9
+ * and a portrait. Passing them as flags to every `decklight <deck>` is how
10
+ * nobody ends up using the feature — so `decklight setup face …` writes
11
+ * them here once, the way the voice setup lives in `tts.json`, and the
12
+ * lip-sync bridge, `open` and `doctor` all read the same file.
13
+ *
14
+ * `~/.config/decklight/lipsync.json` ($XDG_CONFIG_HOME honored):
15
+ * { wav2lipDir, wav2lipCkpt, sadtalkerDir, python, portraits: ["name=path", …] }
16
+ */
17
+
18
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
19
+ import { homedir } from 'node:os';
20
+ import { basename, dirname, extname, join, resolve } from 'node:path';
21
+
22
+ export function lipsyncConfigPath(env = process.env) {
23
+ const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config');
24
+ return join(base, 'decklight', 'lipsync.json');
25
+ }
26
+
27
+ /** Where a portrait filmed from the deck is kept, beside lipsync.json. */
28
+ export function portraitsDir(env = process.env) {
29
+ return join(dirname(lipsyncConfigPath(env)), 'portraits');
30
+ }
31
+
32
+ /**
33
+ * `config` with portrait `name` pointing at `file` — replacing one of that
34
+ * name, else added — and the bridge's own `setup` (Wav2Lip, its checkpoint,
35
+ * its Python) filled in where the saved file has none, so a portrait filmed
36
+ * on a bridge started with flags still works on the next plain `open`. Pure.
37
+ */
38
+ export function withPortrait(config, name, file, setup = {}) {
39
+ const next = { ...(config ?? {}) };
40
+ for (const k of ['wav2lipDir', 'wav2lipCkpt', 'sadtalkerDir', 'python']) {
41
+ if (next[k] == null && setup[k] != null) next[k] = setup[k];
42
+ }
43
+ const kept = (next.portraits ?? []).filter((spec) => parsePortrait(spec)[0] !== name);
44
+ next.portraits = [...kept, `${name}=${file}`];
45
+ return next;
46
+ }
47
+
48
+ /** The saved setup, or null — a missing or unreadable file is "not set up", not an error. */
49
+ export function loadLipsyncConfig(env = process.env) {
50
+ try { return JSON.parse(readFileSync(lipsyncConfigPath(env), 'utf8')); }
51
+ catch { return null; }
52
+ }
53
+
54
+ export function saveLipsyncConfig(config, env = process.env) {
55
+ const file = lipsyncConfigPath(env);
56
+ mkdirSync(dirname(file), { recursive: true });
57
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
58
+ return file;
59
+ }
60
+
61
+ /** `alice=face.png` → ['alice', '/abs/face.png']; a bare path is named by its basename. */
62
+ export function parsePortrait(spec) {
63
+ const at = String(spec).indexOf('=');
64
+ const file = resolve(at > 0 ? spec.slice(at + 1) : spec);
65
+ const name = at > 0 ? spec.slice(0, at) : basename(file, extname(file));
66
+ return [name, file];
67
+ }
68
+
69
+ /**
70
+ * What neural video can use, and what stands in the way — ONE answer, so the
71
+ * bridge's startup line, the deck's character row and `doctor` never disagree.
72
+ * `setup` is the flags-over-saved view: `{ wav2lipDir, wav2lipCkpt,
73
+ * sadtalkerDir, python, portraits: [spec] }`. Returns
74
+ * `{ engines: ['wav2lip'?, 'sadtalker'?], problems: [sentence…] }`.
75
+ */
76
+ export function videoSetup(setup, { exists = existsSync } = {}) {
77
+ const engines = [];
78
+ const problems = [];
79
+ const portraits = (setup?.portraits ?? []).map(parsePortrait);
80
+ const missingPortraits = portraits.filter(([, f]) => !exists(f)).map(([n, f]) => `${n} (${f})`);
81
+ if (missingPortraits.length) problems.push(`portrait not found: ${missingPortraits.join(', ')}`);
82
+ const havePortrait = portraits.some(([, f]) => exists(f));
83
+ const { wav2lipDir, wav2lipCkpt, sadtalkerDir } = setup ?? {};
84
+ if (wav2lipDir) {
85
+ if (!exists(join(wav2lipDir, 'inference.py'))) problems.push(`no Wav2Lip checkout at ${wav2lipDir} (inference.py is missing)`);
86
+ else if (!wav2lipCkpt) problems.push('Wav2Lip needs its checkpoint: --wav2lip-ckpt <wav2lip_gan.pth>');
87
+ else if (!exists(wav2lipCkpt)) problems.push(`Wav2Lip checkpoint not found: ${wav2lipCkpt}`);
88
+ else if (havePortrait) engines.push('wav2lip');
89
+ }
90
+ if (sadtalkerDir) {
91
+ if (!exists(join(sadtalkerDir, 'inference.py'))) problems.push(`no SadTalker checkout at ${sadtalkerDir} (inference.py is missing)`);
92
+ else if (havePortrait) engines.push('sadtalker');
93
+ }
94
+ if ((wav2lipDir || sadtalkerDir) && !havePortrait && !missingPortraits.length) {
95
+ problems.push('no portrait — add one: --portrait me=photo.jpg (a head-and-shoulders photo, or a short video of you: me=clip.mp4)');
96
+ }
97
+ if (setup?.python && setup.python.includes('/') && !exists(setup.python)) problems.push(`python not found: ${setup.python}`);
98
+ return { engines, problems };
99
+ }
100
+
101
+ /** The one command that sets neural video up — said wherever it is missing. */
102
+ export const SETUP_HINT = 'decklight setup face --wav2lip-dir <Wav2Lip checkout> --wav2lip-ckpt <wav2lip_gan.pth>'
103
+ + ' --python <its venv python> --portrait me=<photo.jpg>';
@@ -21,6 +21,7 @@ import { execFile } from 'node:child_process';
21
21
  import { promisify } from 'node:util';
22
22
  import { readFileSync, writeFileSync, rmSync, mkdirSync, readdirSync, statSync, renameSync } from 'node:fs';
23
23
  import { resolve, join } from 'node:path';
24
+ import { createHash } from 'node:crypto';
24
25
  import { normalizeRhubarb } from './visemes.mjs';
25
26
 
26
27
  const run = promisify(execFile);
@@ -45,13 +46,215 @@ export async function runRhubarb(rhubarb, { wav, dialogFile, out, timeout } = {}
45
46
  * `smallBatches` when the face is a multi-frame clip — the default batch size
46
47
  * OOMs an 8 GB card ("Image too big to run face detection on GPU").
47
48
  */
48
- export async function runWav2lip(python, { dir, checkpoint, face, wav, out, smallBatches, inherit, timeout } = {}) {
49
+ export async function runWav2lip(python, { dir, checkpoint, face, wav, out, smallBatches, box, inherit, timeout } = {}) {
49
50
  const batches = smallBatches ? ['--face_det_batch_size', '4', '--wav2lip_batch_size', '32'] : [];
51
+ // A known face box (a still's, found once — `faceBox`) skips Wav2Lip's own
52
+ // per-clip detection; its order is top bottom left right.
53
+ const boxArgs = box ? ['--box', String(box.y1), String(box.y2), String(box.x1), String(box.x2)] : [];
50
54
  await run(python, ['inference.py', '--checkpoint_path', resolve(checkpoint),
51
- '--face', face, '--audio', wav, '--outfile', out, ...batches],
55
+ '--face', face, '--audio', wav, '--outfile', out, ...batches, ...boxArgs],
52
56
  { cwd: resolve(dir), ...bufOpts(timeout, inherit) });
53
57
  }
54
58
 
59
+ /** The longest side a portrait is handed to Wav2Lip at — S3FD misses faces in a phone photo at full size. */
60
+ export const STILL_MAX = 1024;
61
+
62
+ /**
63
+ * A portrait as Wav2Lip can use it: at most STILL_MAX tall (a 3088-pixel
64
+ * phone photo is a face S3FD does not find — measured: none at full size,
65
+ * found at half), JPEG, cached by content. Small enough already: the file itself.
66
+ */
67
+ export async function prepareStill(still, cacheDir, { timeout = 60000 } = {}) {
68
+ const { stdout } = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0',
69
+ '-show_entries', 'stream=width,height', '-of', 'csv=p=0', still], { timeout });
70
+ const [w, h] = String(stdout).trim().split(',').map(Number);
71
+ if (!(Math.max(w, h) > STILL_MAX)) return still;
72
+ const key = createHash('sha256').update(readFileSync(still)).digest('hex').slice(0, 24);
73
+ const out = join(cacheDir, `still-${key}.jpg`);
74
+ try { statSync(out); return out; } catch { /* not yet */ }
75
+ const scale = h >= w ? `scale=-2:${STILL_MAX}` : `scale=${STILL_MAX}:-2`;
76
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', still, '-vf', scale, '-q:v', '2', out], { timeout });
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * Where the face is in each of `files` (same-size frames), with Wav2Lip's own
82
+ * detector and the Python that has its packages: `{x1, y1, x2, y2}` or null
83
+ * per file. Padded 25 px below the chin (Wav2Lip's `--pads 0 10` leaves a
84
+ * seam across it).
85
+ */
86
+ async function detectFaces(python, { dir, files, timeout }) {
87
+ const code = [
88
+ 'import sys, json, cv2, numpy as np, face_detection',
89
+ "det = face_detection.FaceAlignment(face_detection.LandmarksType._2D, flip_input=False, device='cpu')",
90
+ 'out = []',
91
+ 'for f in sys.argv[1:]:',
92
+ ' r = det.get_detections_for_batch(np.array([cv2.imread(f)]))[0]',
93
+ ' out.append(None if r is None else [int(v) for v in r[:4]])',
94
+ 'print(json.dumps(out))',
95
+ ].join('\n');
96
+ const { stdout } = await run(python, ['-c', code, ...files.map((f) => resolve(f))],
97
+ { cwd: resolve(dir), timeout, maxBuffer: 16 * 1024 * 1024 });
98
+ const found = JSON.parse(String(stdout).trim().split('\n').pop() || '[]');
99
+ return found.map((r) => r && { x1: r[0], y1: r[1], x2: r[2], y2: r[3] + 25 });
100
+ }
101
+
102
+ /**
103
+ * Where the face is in a still — found ONCE and cached. Null when no face is
104
+ * found: Wav2Lip then detects per clip, and the composite is skipped.
105
+ */
106
+ export async function faceBox(python, { dir, still, cacheDir, timeout = 180000 } = {}) {
107
+ const key = createHash('sha256').update(readFileSync(still)).digest('hex').slice(0, 24);
108
+ const out = join(cacheDir, `box-${key}.json`);
109
+ try { return JSON.parse(readFileSync(out, 'utf8')); } catch { /* not yet */ }
110
+ const [box = null] = await detectFaces(python, { dir, files: [still], timeout });
111
+ writeFileSync(out, JSON.stringify(box));
112
+ return box;
113
+ }
114
+
115
+ /**
116
+ * The square a head is cropped to in a `width`×`height` frame: 1.7× the face,
117
+ * the face a little above centre, kept inside the frame. Pure.
118
+ */
119
+ export function squareAround(box, width, height) {
120
+ const fw = box.x2 - box.x1;
121
+ const fh = box.y2 - box.y1;
122
+ const side = Math.min(width, height, Math.round(1.7 * Math.max(fw, fh))) & ~1; // even, for yuv420p
123
+ const cx = (box.x1 + box.x2) / 2;
124
+ const cy = box.y1 + 0.45 * fh;
125
+ const x = Math.max(0, Math.min(width - side, Math.round(cx - side / 2)));
126
+ const y = Math.max(0, Math.min(height - side, Math.round(cy - side / 2)));
127
+ return { x, y, side };
128
+ }
129
+
130
+ /**
131
+ * The still cropped to a SQUARE around the head — what the deck's round
132
+ * overlay shows, so the face fills it instead of sitting small in a whole
133
+ * head-and-shoulders photo (and a smaller frame renders faster). The box comes
134
+ * back moved into the crop. Cached by content and box.
135
+ */
136
+ export async function headCrop(still, box, cacheDir, { width, height, timeout = 60000 } = {}) {
137
+ if (!width || !height) {
138
+ const { stdout } = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0',
139
+ '-show_entries', 'stream=width,height', '-of', 'csv=p=0', still], { timeout });
140
+ [width, height] = String(stdout).trim().split(',').map(Number);
141
+ }
142
+ const { x, y, side } = squareAround(box, width, height);
143
+ const key = createHash('sha256').update(readFileSync(still)).update(`${x},${y},${side}`).digest('hex').slice(0, 24);
144
+ const out = join(cacheDir, `head-${key}.jpg`);
145
+ try { statSync(out); } catch {
146
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', still, '-vf', `crop=${side}:${side}:${x}:${y}`, '-q:v', '2', out], { timeout });
147
+ }
148
+ return { file: out, box: { x1: box.x1 - x, y1: box.y1 - y, x2: box.x2 - x, y2: box.y2 - y } };
149
+ }
150
+
151
+ /**
152
+ * The mouth, and only the mouth, from Wav2Lip's clip, laid over the SHARP
153
+ * still. Wav2Lip redraws the whole face box at 96 px, so glasses, eyes and
154
+ * skin come back soft and blocky; a feathered ellipse over the mouth and chin
155
+ * — placed from the face box — keeps everything else the photograph.
156
+ * `still` may be a filmed portrait's loop (`prepareClip`) instead: Wav2Lip's
157
+ * frame i is the loop's frame i, both from 0 at 25 fps, so the loop replayed
158
+ * beside it lines up frame for frame.
159
+ */
160
+ export async function mouthComposite(still, talk, box, out, { timeout = 180000 } = {}) {
161
+ const w = box.x2 - box.x1;
162
+ const h = box.y2 - box.y1;
163
+ const cx = Math.round((box.x1 + box.x2) / 2);
164
+ const cy = Math.round(box.y1 + 0.74 * h);
165
+ const rx = Math.round(0.44 * w);
166
+ const ry = Math.round(0.26 * h);
167
+ const mask = `format=gray,geq=lum='if(lt(pow((X-${cx})/${rx},2)+pow((Y-${cy})/${ry},2),1),255,0)',gblur=sigma=18`;
168
+ const source = isClip(still) ? ['-stream_loop', '-1', '-i', still] : ['-loop', '1', '-i', still];
169
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', talk, ...source,
170
+ '-filter_complex',
171
+ `[0:v]format=yuv444p,split[talk][ref];[1:v]format=yuv444p[st];[st][ref]scale2ref[still][sz];[sz]${mask},format=yuv444p[m];`
172
+ // limited range, like every other clip: a JPEG still makes it yuvj420p
173
+ // (full range), which some players decode washed out or not at all
174
+ + '[still][talk][m]maskedmerge,scale=out_range=tv,format=yuv420p[v]',
175
+ '-map', '[v]', '-map', '0:a?', '-shortest', '-c:v', 'libx264', '-crf', '20', '-c:a', 'aac', out], { timeout });
176
+ }
177
+
178
+ /** A portrait given as a video — filmed, not photographed. */
179
+ export const isClip = (file) => /\.(mp4|mov|m4v|webm|mkv)$/i.test(String(file));
180
+
181
+ /** The longest stretch of a filmed portrait used — it plays forward, then back. */
182
+ export const CLIP_MAX_SECONDS = 10;
183
+ const CLIP_FPS = 25;
184
+
185
+ /**
186
+ * One box for a head across a filmed portrait's sampled frames: their union,
187
+ * and whether the head held STILL — every frame has a face, and its centre
188
+ * wanders less than `tol` of the face's width. A steady head's union box can
189
+ * be handed to Wav2Lip for every frame and the mouth composited over the
190
+ * film; a moving one cannot. Pure.
191
+ */
192
+ export function steadyBox(boxes, { tol = 0.1 } = {}) {
193
+ const found = boxes.filter(Boolean);
194
+ if (!found.length) return { box: null, steady: false, found: 0 };
195
+ const box = {
196
+ x1: Math.min(...found.map((b) => b.x1)), y1: Math.min(...found.map((b) => b.y1)),
197
+ x2: Math.max(...found.map((b) => b.x2)), y2: Math.max(...found.map((b) => b.y2)),
198
+ };
199
+ const cx = found.map((b) => (b.x1 + b.x2) / 2);
200
+ const cy = found.map((b) => (b.y1 + b.y2) / 2);
201
+ const width = Math.min(...found.map((b) => b.x2 - b.x1));
202
+ const wander = Math.max(Math.max(...cx) - Math.min(...cx), Math.max(...cy) - Math.min(...cy));
203
+ return { box, steady: found.length === boxes.length && wander <= tol * width, found: found.length };
204
+ }
205
+
206
+ /**
207
+ * A filmed portrait as Wav2Lip can use it, made ONCE and cached by content:
208
+ * - at most CLIP_MAX_SECONDS, 25 fps, no sound, at most STILL_MAX tall;
209
+ * - its face found in one frame a second (`steadyBox`);
210
+ * - cropped square around the head, like a photo;
211
+ * - played forward then backward, so the loop Wav2Lip makes of it for a
212
+ * long sentence never snaps the head back to the start;
213
+ * - its first frame kept as the still the deck shows under the video.
214
+ * Returns `{ loop, still, box, steady, seconds }` — `box` in the crop.
215
+ * Throws when no frame has a face: a film of the back of a head is not a
216
+ * portrait, and saying so beats a Wav2Lip traceback per sentence.
217
+ */
218
+ export async function prepareClip(python, { dir, clip, cacheDir, timeout = 600000 } = {}) {
219
+ const key = createHash('sha256').update('clip-v1|').update(readFileSync(clip)).digest('hex').slice(0, 24);
220
+ const meta = join(cacheDir, `clip-${key}.json`);
221
+ try { return JSON.parse(readFileSync(meta, 'utf8')); } catch { /* not yet */ }
222
+ const work = join(cacheDir, `clip-${key}.tmp.d`);
223
+ rmSync(work, { recursive: true, force: true });
224
+ mkdirSync(work, { recursive: true });
225
+ try {
226
+ const norm = join(work, 'norm.mp4');
227
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', clip, '-t', String(CLIP_MAX_SECONDS), '-an',
228
+ '-vf', `fps=${CLIP_FPS},scale=w='min(iw,${STILL_MAX})':h='min(ih,${STILL_MAX})':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2`,
229
+ '-c:v', 'libx264', '-crf', '16', '-pix_fmt', 'yuv420p', norm], { timeout });
230
+ const { stdout } = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0',
231
+ '-show_entries', 'stream=width,height:format=duration', '-of', 'json', norm], { timeout });
232
+ const probe = JSON.parse(String(stdout));
233
+ const { width, height } = probe.streams[0];
234
+ const seconds = Number(probe.format?.duration) || 0;
235
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', norm, '-vf', 'fps=1', '-q:v', '2', join(work, 'f-%03d.jpg')], { timeout });
236
+ const frames = readdirSync(work).filter((f) => /^f-\d+\.jpg$/.test(f)).sort().map((f) => join(work, f));
237
+ const { box, steady, found } = steadyBox(await detectFaces(python, { dir, files: frames, timeout }));
238
+ if (!box) throw new Error(`no face found in ${clip} — film the face toward the camera, evenly lit`);
239
+ const { x, y, side } = squareAround(box, width, height);
240
+ const loop = join(cacheDir, `clip-${key}.mp4`);
241
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', norm, '-filter_complex',
242
+ // the turn-around frame once, not twice — a held frame reads as a hitch
243
+ `[0:v]crop=${side}:${side}:${x}:${y},split[f][b];[b]reverse,trim=start_frame=1,setpts=PTS-STARTPTS[r];[f][r]concat=n=2:v=1:a=0,format=yuv420p[v]`,
244
+ '-map', '[v]', '-r', String(CLIP_FPS), '-c:v', 'libx264', '-crf', '16', '-movflags', '+faststart', loop], { timeout });
245
+ const still = join(cacheDir, `clip-${key}.jpg`);
246
+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-i', loop, '-frames:v', '1', '-q:v', '2', still], { timeout });
247
+ const prepared = {
248
+ loop, still, steady, seconds, faces: `${found}/${frames.length}`,
249
+ box: { x1: box.x1 - x, y1: box.y1 - y, x2: box.x2 - x, y2: box.y2 - y },
250
+ };
251
+ writeFileSync(meta, JSON.stringify(prepared));
252
+ return prepared;
253
+ } finally {
254
+ rmSync(work, { recursive: true, force: true });
255
+ }
256
+ }
257
+
55
258
  /**
56
259
  * SadTalker: `still` + `wav` → mp4 at `out`. It writes `<timestamp>/….mp4`
57
260
  * into `resultDir`; take the newest and move it to `out`. (SadTalker makes its