beatsheet 0.0.0-stage → 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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/bin/beatsheet.js +14 -0
  4. package/bin/register-fallback.mjs +23 -0
  5. package/bin/resolve-fallback.mjs +83 -0
  6. package/package.json +45 -4
  7. package/player/env.d.ts +5 -0
  8. package/player/gallery-audio.ts +147 -0
  9. package/player/gallery-css.ts +144 -0
  10. package/player/gallery-detail.ts +385 -0
  11. package/player/gallery-music.ts +257 -0
  12. package/player/gallery-pick-state.ts +167 -0
  13. package/player/gallery-pick.ts +749 -0
  14. package/player/gallery-sounds.ts +137 -0
  15. package/player/gallery-state.ts +457 -0
  16. package/player/gallery.ts +612 -0
  17. package/player/index.html +49 -0
  18. package/player/main.ts +83 -0
  19. package/skill/SKILL.md +658 -0
  20. package/skill/examples/library/assets/tour/avatar-mk.svg +1 -0
  21. package/skill/examples/library/assets/tour/dashboard-insights.svg +1 -0
  22. package/skill/examples/library/assets/tour/dashboard.svg +1 -0
  23. package/skill/examples/library/assets/tour/settings.svg +1 -0
  24. package/skill/examples/library/library-tour.plan.md +32 -0
  25. package/skill/examples/library/library-tour.video.json +268 -0
  26. package/skill/reference/scene-techniques.md +306 -0
  27. package/skill/scripts/beats.ts +34 -0
  28. package/skill/scripts/catalogue.ts +120 -0
  29. package/skill/scripts/frames.ts +105 -0
  30. package/src/args.ts +344 -0
  31. package/src/cli.ts +95 -0
  32. package/src/commands.ts +812 -0
  33. package/src/default-project.config.ts +9 -0
  34. package/src/index.ts +47 -0
  35. package/src/packages.ts +17 -0
  36. package/src/paths.ts +32 -0
  37. package/src/project.ts +200 -0
  38. package/src/render/browser.ts +185 -0
  39. package/src/render/capture.ts +320 -0
  40. package/src/render/ffmpeg.ts +229 -0
  41. package/src/render/gif-info.ts +61 -0
  42. package/src/render/render.ts +220 -0
  43. package/src/samples.ts +557 -0
  44. package/src/server/api.ts +494 -0
  45. package/src/server/jobs.ts +210 -0
  46. package/src/server/security.ts +47 -0
  47. package/src/server/server.ts +191 -0
  48. package/src/server/sse.ts +76 -0
  49. package/src/server/static.ts +127 -0
  50. package/src/server/vite.ts +100 -0
  51. package/src/skill.ts +111 -0
  52. package/src/snap.ts +212 -0
  53. package/src/speech.ts +689 -0
  54. package/src/svg-text.ts +136 -0
  55. package/src/voicefx.ts +311 -0
  56. package/studio/3rdpartylicenses.txt +287 -0
  57. package/studio/favicon.ico +0 -0
  58. package/studio/icons/apple-touch-icon.png +0 -0
  59. package/studio/icons/icon-192.png +0 -0
  60. package/studio/icons/icon-512.png +0 -0
  61. package/studio/icons/icon.svg +1 -0
  62. package/studio/icons/maskable-512.png +0 -0
  63. package/studio/index.html +18 -0
  64. package/studio/main-KMYDBWZH.js +15 -0
  65. package/studio/manifest.webmanifest +17 -0
  66. package/studio/offline.html +92 -0
  67. package/studio/styles-NJ2CULOW.css +1 -0
  68. package/studio/sw.js +71 -0
package/src/speech.ts ADDED
@@ -0,0 +1,689 @@
1
+ /**
2
+ * Voice-over in Node: the speech engine plugins, `beatsheet speak` (also the studio's Generate
3
+ * speech), the clip files, the render preflight and the clip lengths `check` needs.
4
+ *
5
+ * A narrated scene's line is spoken once into speech/<key>.wav next to the video file (16-bit PCM
6
+ * mono at the engine's rate, its silence trimmed to a 40 ms lead and an 80 ms tail, so a narration's
7
+ * offset is when the voice starts and the fit check measures what is said; with voiceFx 'studio' (opt-in;
8
+ * the default 'raw' stops at the trim) then high-passed, de-essed, compressed and given a short room tail, see voicefx.ts; speech/<key>.words.json
9
+ * when the engine gives word timings). Renders only read those files. Engines are plugin packages `@beatsheet/voice-<engine>`, resolved from the
10
+ * project folder and imported only here (never by renders): see projectSpeechPlugins.
11
+ */
12
+ import { randomUUID } from 'node:crypto';
13
+ import fs from 'node:fs/promises';
14
+ import { closeSync, existsSync, fstatSync, openSync, readSync } from 'node:fs';
15
+ import { createRequire } from 'node:module';
16
+ import path from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+ import {
19
+ SPEECH_ENGINES,
20
+ missingSpeechMessage,
21
+ narrationClips,
22
+ normaliseNarration,
23
+ parseVoice,
24
+ resolveTimeline,
25
+ resolveVoice,
26
+ speechEngineList,
27
+ type NarrationClip,
28
+ type SpeechEngine,
29
+ type SpeechEvent,
30
+ type SpeechJobRequest,
31
+ type SpeechResult,
32
+ type SpeechSceneStatus,
33
+ type SpeechStatus,
34
+ type SpeechVoice,
35
+ type VideoDoc,
36
+ type VoiceFx,
37
+ } from '@beatsheet/core';
38
+ import { errorMessage, VIDEO_SUFFIX, type ProjectContext } from './project';
39
+ import { studioVoice } from './voicefx';
40
+
41
+ type Log = (line: string) => void;
42
+
43
+ /** What the speech code needs of a video: its file, its doc, its project. */
44
+ export interface SpeechVideo {
45
+ /** Absolute path of the *.video.json. */
46
+ path: string;
47
+ doc: VideoDoc;
48
+ project: Pick<ProjectContext, 'config' | 'configPath' | 'root'>;
49
+ }
50
+
51
+ /** speech/<key>.wav and speech/<key>.words.json: the only names in a speech folder beatsheet reads, serves or prunes. */
52
+ export const SPEECH_FILE = /^[0-9a-f]{16}\.(wav|words\.json)$/;
53
+ export const SPEECH_DIR = 'speech';
54
+
55
+ /** The speech folder of a video: speech/ next to the video file. */
56
+ export function speechDir(videoPath: string): string {
57
+ return path.join(path.dirname(videoPath), SPEECH_DIR);
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Plugins
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /** The package of an engine's plugin: '@beatsheet/voice-kokoro'. */
65
+ export function pluginPackage(engine: string): string {
66
+ return `@beatsheet/voice-${engine}`;
67
+ }
68
+
69
+ /** One line on a plugin's licence, shown with "not installed". */
70
+ const PLUGIN_NOTES: Readonly<Record<string, string>> = {
71
+ kokoro: '@beatsheet/voice-kokoro is GPL-3.0-or-later (kokoro-js bundles eSpeak NG); beatsheet imports it only to speak, never to render. It is not on npm yet: it comes with a beatsheet checkout (packages/voice-kokoro).',
72
+ };
73
+
74
+ /** The speech engine plugins of a project. */
75
+ export interface SpeechPlugins {
76
+ /** True when the engine's plugin package resolves from the project folder (nothing is imported). */
77
+ installed(engine: string): boolean;
78
+ /** Imports the plugin and creates its engine, once per SpeechPlugins (then the same engine). */
79
+ load(engine: string): Promise<SpeechEngine>;
80
+ }
81
+
82
+ /** A SpeechEngine may offer load(): load its model now (otherwise its first synthesize() does). */
83
+ type LoadableEngine = SpeechEngine & { load?: () => Promise<void> };
84
+
85
+ /** The error when an engine's plugin is not installed: the npm command and the plugin's licence. */
86
+ export function pluginMissingMessage(engine: string, projectRoot?: string): string {
87
+ const where = projectRoot ? ` (in ${projectRoot})` : '';
88
+ const note = PLUGIN_NOTES[engine];
89
+ return `speech engine "${engine}" is not installed. Run: npm install ${pluginPackage(engine)}${where}${note ? `\n${note}` : ''}`;
90
+ }
91
+
92
+ /** Conditions of an import() in Node: an `exports` entry under another (require, browser, types) is not what it loads. */
93
+ const IMPORT_CONDITIONS = new Set(['node', 'import', 'module-sync', 'default']);
94
+
95
+ /** The target of a conditional `exports` entry for import(): the first key that matches, in the package's order. */
96
+ function importTarget(target: unknown): string | null {
97
+ if (typeof target === 'string') return target;
98
+ if (Array.isArray(target)) {
99
+ for (const t of target) {
100
+ const found = importTarget(t);
101
+ if (found !== null) return found;
102
+ }
103
+ return null;
104
+ }
105
+ if (typeof target !== 'object' || target === null) return null;
106
+ for (const [condition, value] of Object.entries(target)) {
107
+ if (!IMPORT_CONDITIONS.has(condition)) continue;
108
+ const found = importTarget(value);
109
+ if (found !== null) return found;
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /**
115
+ * The file import() loads of a package from its package.json: `exports` (its "." entry) under the
116
+ * conditions of an import, else `main`, else index.js. Null when `exports` has nothing for an import.
117
+ */
118
+ export function packageImportEntry(manifest: unknown): string | null {
119
+ const m = (typeof manifest === 'object' && manifest !== null ? manifest : {}) as { exports?: unknown; main?: unknown };
120
+ if (m.exports !== undefined && m.exports !== null) {
121
+ const subpaths = typeof m.exports === 'object' && !Array.isArray(m.exports) && Object.keys(m.exports).some((k) => k.startsWith('.'));
122
+ return importTarget(subpaths ? (m.exports as Record<string, unknown>)['.'] : m.exports);
123
+ }
124
+ return typeof m.main === 'string' && m.main ? m.main : 'index.js';
125
+ }
126
+
127
+ /**
128
+ * The plugins as the project sees them: `@beatsheet/voice-<engine>` found in the node_modules folders
129
+ * Node searches from the project root (its package.json), its entry for import()
130
+ * (packageImportEntry: an ESM-only package with only an "import" export works too) imported with a
131
+ * dynamic import(), its `createEngine()` (or default export) called once. The engine is kept: one
132
+ * model load per process.
133
+ */
134
+ export function projectSpeechPlugins(root: string, importer: (url: string) => Promise<unknown> = (url) => import(url)): SpeechPlugins {
135
+ const req = createRequire(path.join(path.resolve(root), 'package.json'));
136
+ const engines = new Map<string, Promise<SpeechEngine>>();
137
+ /** The plugin's package.json, or null when no node_modules folder has it. */
138
+ const manifest = (engine: string): string | null => {
139
+ const pkg = pluginPackage(engine);
140
+ for (const dir of req.resolve.paths(pkg) ?? []) {
141
+ const file = path.join(dir, pkg, 'package.json');
142
+ if (existsSync(file)) return file;
143
+ }
144
+ return null;
145
+ };
146
+ return {
147
+ installed: (engine) => manifest(engine) !== null,
148
+ load(engine): Promise<SpeechEngine> {
149
+ const known = engines.get(engine);
150
+ if (known) return known;
151
+ const loading = (async (): Promise<SpeechEngine> => {
152
+ const pkgJson = manifest(engine);
153
+ if (!pkgJson) throw new Error(pluginMissingMessage(engine, path.resolve(root)));
154
+ const pkg = pluginPackage(engine);
155
+ let entry: string | null;
156
+ try {
157
+ entry = packageImportEntry(JSON.parse(await fs.readFile(pkgJson, 'utf8')));
158
+ } catch (err) {
159
+ throw new Error(`could not load ${pkg}: ${pkgJson}: ${errorMessage(err)}`);
160
+ }
161
+ if (entry === null) throw new Error(`could not load ${pkg}: its package.json exports nothing for import() (${pkgJson})`);
162
+ const file = path.resolve(path.dirname(pkgJson), entry);
163
+ let mod: { createEngine?: unknown; default?: unknown };
164
+ try {
165
+ mod = (await importer(pathToFileURL(file).href)) as typeof mod;
166
+ } catch (err) {
167
+ throw new Error(`could not load ${pkg}: ${errorMessage(err)}`);
168
+ }
169
+ const create = typeof mod.createEngine === 'function' ? mod.createEngine : typeof mod.default === 'function' ? mod.default : null;
170
+ if (!create) throw new Error(`${pkg} exports no createEngine(): not a beatsheet speech engine`);
171
+ const created = (await (create as () => unknown)()) as Partial<SpeechEngine> | null;
172
+ if (!created || typeof created.synthesize !== 'function' || typeof created.voices !== 'function') {
173
+ throw new Error(`${pkg}: createEngine() returned no speech engine (synthesize, voices)`);
174
+ }
175
+ return created as SpeechEngine;
176
+ })();
177
+ engines.set(engine, loading);
178
+ loading.catch(() => {
179
+ if (engines.get(engine) === loading) engines.delete(engine);
180
+ });
181
+ return loading;
182
+ },
183
+ };
184
+ }
185
+
186
+ /**
187
+ * A loaded engine must be the one SPEECH_ENGINES names, with the model the keys were made for: a
188
+ * different model would put new audio under old keys.
189
+ */
190
+ export function checkEngine(engine: string, e: SpeechEngine): void {
191
+ const info = SPEECH_ENGINES[engine];
192
+ const pkg = pluginPackage(engine);
193
+ if (e.id !== engine) throw new Error(`${pkg} is the speech engine "${e.id}", not "${engine}"`);
194
+ if (info && e.model !== info.model) {
195
+ throw new Error(
196
+ `${pkg} speaks with model "${e.model}", but this beatsheet expects "${info.model}" (a clip's key includes its model). ` +
197
+ `Install the ${pkg} that matches this beatsheet, or upgrade beatsheet to one that expects "${e.model}" and re-speak after upgrading: every clip gets a new key.`,
198
+ );
199
+ }
200
+ }
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // Plan: which clips a video needs and which of them to speak
204
+ // ---------------------------------------------------------------------------
205
+
206
+ /** A narration clip with its file on disk. */
207
+ export interface PlannedClip extends NarrationClip {
208
+ /** Absolute path of speech/<key>.wav. */
209
+ wavPath: string;
210
+ /** The WAV's header reads (readClipInfo): a missing or truncated file is no clip. */
211
+ exists: boolean;
212
+ /** Seconds of audio from the header, when it exists. */
213
+ duration?: number;
214
+ }
215
+
216
+ export interface SpeechPlan {
217
+ /** 'kokoro:af_bella'; undefined when the video has no narration. */
218
+ voice?: string;
219
+ engine?: string;
220
+ /** The engine's own voice id ('af_bella'). */
221
+ engineVoice?: string;
222
+ /** Absolute speech/ folder of the video. */
223
+ dir: string;
224
+ /** Every narrated scene (only the selected ones with `scenes`), in scene order. */
225
+ clips: PlannedClip[];
226
+ /** What to speak: missing clips (all selected ones with force), one per key. */
227
+ todo: PlannedClip[];
228
+ }
229
+
230
+ /** An error in the video or the request, before any engine is involved; `path` points at its field. */
231
+ export class SpeechPlanError extends Error {
232
+ constructor(
233
+ message: string,
234
+ public readonly path: (string | number)[] = [],
235
+ ) {
236
+ super(message);
237
+ }
238
+ }
239
+
240
+ /** Indexes of the scenes with a narration text. */
241
+ function narratedScenes(doc: VideoDoc): number[] {
242
+ return doc.scenes.flatMap((s, i) => (s.narration && typeof s.narration.text === 'string' && normaliseNarration(s.narration.text) ? [i] : []));
243
+ }
244
+
245
+ /** Every narrated scene's clip (VideoDoc.voice, else the project's), with its file; [] without narration or voice. */
246
+ export function videoClips(v: SpeechVideo): PlannedClip[] {
247
+ const dir = speechDir(v.path);
248
+ return narrationClips(v.doc, resolveTimeline(v.doc, v.project.config), v.project.config).map((c) => {
249
+ const wavPath = path.join(dir, `${c.key}.wav`);
250
+ const info = readClipInfo(wavPath);
251
+ return { ...c, wavPath, exists: info !== null, ...(info ? { duration: info.duration } : {}) };
252
+ });
253
+ }
254
+
255
+ /**
256
+ * What `speak` does for a video: its voice, engine and clips, and which to speak. Throws
257
+ * SpeechPlanError for a narrated video without a voice, a voice that is not engine:voice, an engine
258
+ * beatsheet does not know, and `scenes` naming an unknown scene or one without narration.
259
+ */
260
+ export function planSpeech(v: SpeechVideo, opts: Pick<SpeechJobRequest, 'scenes' | 'force'> = {}): SpeechPlan {
261
+ const dir = speechDir(v.path);
262
+ const narrated = narratedScenes(v.doc);
263
+ if (opts.scenes) {
264
+ opts.scenes.forEach((id, i) => {
265
+ const index = v.doc.scenes.findIndex((s) => s.id === id);
266
+ if (index < 0) throw new SpeechPlanError(`unknown scene "${id}" (scenes: ${v.doc.scenes.map((s) => s.id).join(', ')})`, ['scenes', i]);
267
+ if (!narrated.includes(index)) throw new SpeechPlanError(`scene "${id}" has no narration`, ['scenes', i]);
268
+ });
269
+ }
270
+ if (narrated.length === 0) return { dir, clips: [], todo: [] };
271
+ const voice = resolveVoice(v.doc, v.project.config);
272
+ if (voice === undefined) {
273
+ throw new SpeechPlanError(
274
+ 'the video has narration but no voice: set "voice" (e.g. "kokoro:af_bella") in the video, or a default voice in beatsheet.config.ts',
275
+ ['voice'],
276
+ );
277
+ }
278
+ const where = v.doc.voice === voice ? '' : ' (the default voice in beatsheet.config.ts)';
279
+ const parsed = parseVoice(voice);
280
+ if (!parsed) throw new SpeechPlanError(`voice "${voice}"${where} is not "engine:voice" (e.g. "kokoro:af_bella")`, ['voice']);
281
+ if (!Object.prototype.hasOwnProperty.call(SPEECH_ENGINES, parsed.engine)) {
282
+ throw new SpeechPlanError(`unknown speech engine "${parsed.engine}" in voice "${voice}"${where} (engines: ${Object.keys(SPEECH_ENGINES).join(', ')})`, ['voice']);
283
+ }
284
+ const selected = opts.scenes ? new Set(opts.scenes) : null;
285
+ const clips = videoClips(v).filter((c) => !selected || selected.has(c.sceneId));
286
+ const seen = new Set<string>();
287
+ const todo = clips.filter((c) => {
288
+ if ((c.exists && !opts.force) || seen.has(c.key)) return false;
289
+ seen.add(c.key);
290
+ return true;
291
+ });
292
+ return { voice, engine: parsed.engine, engineVoice: parsed.voice, dir, clips, todo };
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // Speak
297
+ // ---------------------------------------------------------------------------
298
+
299
+ export interface SpeakOptions extends Pick<SpeechJobRequest, 'scenes' | 'force'> {
300
+ /** The video as the user names it, for messages. */
301
+ file?: string;
302
+ }
303
+
304
+ export interface SpeakDeps {
305
+ plugins: SpeechPlugins;
306
+ emit?: (e: SpeechEvent) => void;
307
+ log?: Log;
308
+ }
309
+
310
+ export interface SpokenClip {
311
+ sceneId: string;
312
+ key: string;
313
+ /** Absolute path of the WAV. */
314
+ wav: string;
315
+ /** Seconds of audio. */
316
+ seconds: number;
317
+ /** Seconds it took to speak. */
318
+ took: number;
319
+ }
320
+
321
+ export interface SpeakResult {
322
+ plan: SpeechPlan;
323
+ spoken: SpokenClip[];
324
+ /** Seconds the engine took to load its model (engines with load(), first use in this process). */
325
+ loadSeconds?: number;
326
+ }
327
+
328
+ /** Engines that have loaded (or spoken) in this process: no 'loading' event for them. */
329
+ const warm = new WeakSet<SpeechEngine>();
330
+
331
+ const secs = (x: number, digits = 2): string => x.toFixed(digits);
332
+
333
+ /**
334
+ * Speaks every planned clip (planSpeech) with the video's engine: one engine per plugins object,
335
+ * loaded once. Writes speech/<key>.wav (16-bit PCM mono at the engine's rate) and
336
+ * speech/<key>.words.json when the engine gives words, each to a temp file renamed when complete.
337
+ * Emits SpeechEvents ('loading', then 'progress' + 'clip' per clip; the caller emits 'done') and
338
+ * logs one line per clip: scene, seconds of audio, time taken.
339
+ */
340
+ export async function speakVideo(v: SpeechVideo, opts: SpeakOptions, deps: SpeakDeps): Promise<SpeakResult> {
341
+ const emit = deps.emit ?? ((): void => undefined);
342
+ const log = deps.log ?? ((): void => undefined);
343
+ const plan = planSpeech(v, opts);
344
+ const result: SpeakResult = { plan, spoken: [] };
345
+ if (plan.todo.length === 0) return result;
346
+ const engineId = plan.engine as string;
347
+ const engine = (await deps.plugins.load(engineId)) as LoadableEngine;
348
+ checkEngine(engineId, engine);
349
+ if (!warm.has(engine)) {
350
+ emit({ type: 'loading' });
351
+ if (typeof engine.load === 'function') {
352
+ const t0 = performance.now();
353
+ await engine.load();
354
+ result.loadSeconds = (performance.now() - t0) / 1000;
355
+ log(` loaded ${engineId} in ${secs(result.loadSeconds, 1)} s`);
356
+ }
357
+ }
358
+ await fs.mkdir(plan.dir, { recursive: true });
359
+ const width = Math.max(...plan.todo.map((c) => c.sceneId.length));
360
+ for (const [i, clip] of plan.todo.entries()) {
361
+ emit({ type: 'progress', sceneId: clip.sceneId, done: i, total: plan.todo.length });
362
+ const t0 = performance.now();
363
+ const out = await engine.synthesize({ text: clip.text, voice: plan.engineVoice as string, speed: clip.speed });
364
+ warm.add(engine);
365
+ const took = (performance.now() - t0) / 1000;
366
+ checkResult(engineId, clip, out);
367
+ // Engines pad their output (Kokoro: ~0.4 s before the voice, ~0.55 s after): the clip keeps a short lead and tail only.
368
+ const trimmed = processSpeech(out, clip.fx);
369
+ if (!trimmed) throw new Error(`${pluginPackage(engineId)} returned only silence for scene "${clip.sceneId}"`);
370
+ if (trimmed.words) await writeFileAtomic(path.join(plan.dir, `${clip.key}.words.json`), JSON.stringify(trimmed.words, null, 2) + '\n');
371
+ await writeFileAtomic(clip.wavPath, encodePcm16Wav(trimmed.samples, trimmed.sampleRate));
372
+ const seconds = trimmed.samples.length / trimmed.sampleRate;
373
+ result.spoken.push({ sceneId: clip.sceneId, key: clip.key, wav: clip.wavPath, seconds, took });
374
+ emit({ type: 'clip', sceneId: clip.sceneId, key: clip.key, duration: seconds });
375
+ log(` ${clip.sceneId.padEnd(width)} ${secs(seconds)} s of audio in ${secs(took)} s ${SPEECH_DIR}/${clip.key}.wav`);
376
+ }
377
+ return result;
378
+ }
379
+
380
+ function checkResult(engine: string, clip: PlannedClip, out: SpeechResult): void {
381
+ if (!out || !(out.samples instanceof Float32Array) || out.samples.length === 0 || !(Number.isFinite(out.sampleRate) && out.sampleRate > 0)) {
382
+ throw new Error(`${pluginPackage(engine)} returned no audio for scene "${clip.sceneId}"`);
383
+ }
384
+ }
385
+
386
+ // ---------------------------------------------------------------------------
387
+ // Trim
388
+ // ---------------------------------------------------------------------------
389
+
390
+ /** How speak trims an engine's clip (seconds and dB). */
391
+ export const SPEECH_TRIM = {
392
+ /** RMS window that decides speech or not. */
393
+ window: 0.01,
394
+ /** A window is speech when its RMS is at most this many dB under the clip's peak sample. */
395
+ belowPeak: 45,
396
+ /** Kept before the first speech window (the breath before a word). */
397
+ lead: 0.04,
398
+ /** Kept after the last speech window (a word's decay). */
399
+ tail: 0.08,
400
+ /** Linear fade at a cut edge (no click where the cut lands in breath or noise; silence stays silence). */
401
+ fade: 0.005,
402
+ /** A clip whose peak is under this (dBFS) has no speech at all. */
403
+ floor: -60,
404
+ } as const;
405
+
406
+ /**
407
+ * The span of speech in `samples`: windows of SPEECH_TRIM.window whose RMS is above the clip's peak
408
+ * minus SPEECH_TRIM.belowPeak dB, widened by the lead before the first and the tail after the last
409
+ * (within the clip). Null when nothing is speech: an empty clip, or a peak under SPEECH_TRIM.floor dBFS.
410
+ */
411
+ export function speechBounds(samples: Float32Array, sampleRate: number): { start: number; end: number } | null {
412
+ let peak = 0;
413
+ for (const x of samples) peak = Math.max(peak, Math.abs(x));
414
+ if (!(peak > 10 ** (SPEECH_TRIM.floor / 20))) return null;
415
+ const threshold = peak * 10 ** (-SPEECH_TRIM.belowPeak / 20);
416
+ const w = Math.max(1, Math.round(sampleRate * SPEECH_TRIM.window));
417
+ let first = -1;
418
+ let last = -1;
419
+ for (let at = 0; at < samples.length; at += w) {
420
+ const to = Math.min(samples.length, at + w);
421
+ let sum = 0;
422
+ for (let i = at; i < to; i++) sum += samples[i]! * samples[i]!;
423
+ if (Math.sqrt(sum / (to - at)) <= threshold) continue;
424
+ if (first < 0) first = at;
425
+ last = to;
426
+ }
427
+ if (first < 0) return null;
428
+ return {
429
+ start: Math.max(0, first - Math.round(sampleRate * SPEECH_TRIM.lead)),
430
+ end: Math.min(samples.length, last + Math.round(sampleRate * SPEECH_TRIM.tail)),
431
+ };
432
+ }
433
+
434
+ /**
435
+ * An engine's clip with its leading and trailing silence cut (speechBounds), a 5 ms linear fade at
436
+ * each cut edge (no click where the cut lands in breath or noise; where it lands in silence the fade
437
+ * changes nothing), and its word timings moved by the cut lead (clamped to the clip). Null when the
438
+ * clip has no speech.
439
+ */
440
+ export function trimSpeech(result: SpeechResult): SpeechResult | null {
441
+ const bounds = speechBounds(result.samples, result.sampleRate);
442
+ if (!bounds) return null;
443
+ const samples = result.samples.slice(bounds.start, bounds.end);
444
+ const fade = Math.min(samples.length, Math.max(1, Math.round(result.sampleRate * SPEECH_TRIM.fade)));
445
+ if (bounds.start > 0) for (let i = 0; i < fade; i++) samples[i]! *= i / fade;
446
+ if (bounds.end < result.samples.length) for (let i = 0; i < fade; i++) samples[samples.length - 1 - i]! *= i / fade;
447
+ const out: SpeechResult = { sampleRate: result.sampleRate, samples };
448
+ if (result.words) {
449
+ const shift = bounds.start / result.sampleRate;
450
+ const length = samples.length / result.sampleRate;
451
+ const clamp = (t: number): number => Math.min(length, Math.max(0, t - shift));
452
+ out.words = result.words.map((w) => ({ ...w, start: clamp(w.start), end: clamp(w.end) }));
453
+ }
454
+ return out;
455
+ }
456
+
457
+ /**
458
+ * What speak writes for an engine's clip: trimSpeech, then the clip's voice processing ('studio':
459
+ * studioVoice, which adds the reverb tail at the end; word timings keep their place). Null when the
460
+ * clip has no speech.
461
+ */
462
+ export function processSpeech(result: SpeechResult, fx: VoiceFx): SpeechResult | null {
463
+ const trimmed = trimSpeech(result);
464
+ if (!trimmed || fx === 'raw') return trimmed;
465
+ return { ...trimmed, samples: studioVoice(trimmed.samples, trimmed.sampleRate) };
466
+ }
467
+
468
+ // ---------------------------------------------------------------------------
469
+ // Prune
470
+ // ---------------------------------------------------------------------------
471
+
472
+ /**
473
+ * Clip files (speech/<key>.wav, .words.json) in `dir`'s speech/ folder that no *.video.json in `dir`
474
+ * uses. Every video's speech is planned (planSpeech) the way `speak` plans it. Throws, naming each
475
+ * video and why, when a video in the folder can't be read or its speech can't be planned (narration
476
+ * without a voice, a voice that is not engine:voice or of an unknown engine, a timeline that does not
477
+ * resolve): it would need no clips, so its clips can't be told from unused ones.
478
+ */
479
+ export async function unusedClips(dir: string, project: SpeechVideo['project'], parse: (json: unknown) => VideoDoc): Promise<string[]> {
480
+ const used = new Set<string>();
481
+ const problems: string[] = [];
482
+ for (const name of (await fs.readdir(dir)).filter((f) => f.endsWith(VIDEO_SUFFIX)).sort()) {
483
+ const file = path.join(dir, name);
484
+ let doc: VideoDoc;
485
+ try {
486
+ doc = parse(JSON.parse(await fs.readFile(file, 'utf8')));
487
+ } catch (err) {
488
+ problems.push(`${name} is not a valid video (${errorMessage(err)})`);
489
+ continue;
490
+ }
491
+ try {
492
+ for (const c of planSpeech({ path: file, doc, project }).clips) used.add(c.key);
493
+ } catch (err) {
494
+ problems.push(`${name}: ${errorMessage(err)}`);
495
+ }
496
+ }
497
+ if (problems.length === 1) throw new Error(`cannot prune: ${problems[0]}; fix it first, its clips can't be told from unused ones`);
498
+ if (problems.length > 1) {
499
+ throw new Error(`cannot prune: fix these videos first, their clips can't be told from unused ones:\n${problems.map((p) => ` ${p}`).join('\n')}`);
500
+ }
501
+ let entries: string[] = [];
502
+ try {
503
+ entries = await fs.readdir(path.join(dir, SPEECH_DIR));
504
+ } catch {
505
+ return [];
506
+ }
507
+ return entries
508
+ .filter((f) => SPEECH_FILE.test(f) && !used.has(f.slice(0, 16)))
509
+ .sort()
510
+ .map((f) => path.join(dir, SPEECH_DIR, f));
511
+ }
512
+
513
+ // ---------------------------------------------------------------------------
514
+ // Render preflight, check, status
515
+ // ---------------------------------------------------------------------------
516
+
517
+ /** The narrated scenes whose clip is missing, as missingSpeechMessage takes them. */
518
+ export function missingClips(v: SpeechVideo): { sceneId: string; clip: string }[] {
519
+ return videoClips(v)
520
+ .filter((c) => !c.exists)
521
+ .map((c) => ({ sceneId: c.sceneId, clip: c.file }));
522
+ }
523
+
524
+ /**
525
+ * The render preflight: the missing-speech error (scene ids, clip paths, `Run: beatsheet speak <file>`),
526
+ * or what keeps a narrated video from being spoken at all (no voice, unknown engine); null when
527
+ * every narrated scene has its clip.
528
+ */
529
+ export function speechPreflight(v: SpeechVideo, file: string): string | null {
530
+ try {
531
+ planSpeech(v);
532
+ } catch (err) {
533
+ if (err instanceof SpeechPlanError) return `${file}: ${err.message}`;
534
+ throw err;
535
+ }
536
+ const missing = missingClips(v);
537
+ return missing.length ? missingSpeechMessage(missing, resolveVoice(v.doc, v.project.config), file) : null;
538
+ }
539
+
540
+ /** Clip lengths in seconds by key, from the WAV headers of the clips that exist. */
541
+ export async function clipDurations(clips: readonly PlannedClip[]): Promise<Record<string, number>> {
542
+ const out: Record<string, number> = {};
543
+ for (const c of clips) {
544
+ if (!c.exists || c.duration === undefined || Object.prototype.hasOwnProperty.call(out, c.key)) continue;
545
+ out[c.key] = c.duration;
546
+ }
547
+ return out;
548
+ }
549
+
550
+ /**
551
+ * GET /api/speech/:file: the video's voice, the engines (`available`: plugin installed in the
552
+ * project; `voices`: those plugins' voices(), [] when one fails to load) and every narrated scene's
553
+ * clip with its state and length (from the WAV header).
554
+ */
555
+ export async function speechStatus(v: SpeechVideo, plugins: SpeechPlugins): Promise<SpeechStatus> {
556
+ const engines = speechEngineList();
557
+ const available = engines.filter((e) => plugins.installed(e.id)).map((e) => e.id);
558
+ const voices: Record<string, SpeechVoice[]> = {};
559
+ for (const id of available) {
560
+ try {
561
+ voices[id] = await (await plugins.load(id)).voices();
562
+ } catch {
563
+ voices[id] = [];
564
+ }
565
+ }
566
+ const clips = videoClips(v);
567
+ const durations = await clipDurations(clips);
568
+ const scenes: SpeechSceneStatus[] = clips.map((c) => {
569
+ const duration = durations[c.key];
570
+ return duration !== undefined
571
+ ? { sceneId: c.sceneId, key: c.key, clip: c.file, state: 'ready', duration }
572
+ : { sceneId: c.sceneId, key: c.key, clip: c.file, state: 'missing' };
573
+ });
574
+ return { voice: resolveVoice(v.doc, v.project.config) ?? null, engines, available, voices, scenes };
575
+ }
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // WAV files
579
+ // ---------------------------------------------------------------------------
580
+
581
+ /** 16-bit PCM mono WAV of `samples` (clamped to -1..1) at `sampleRate`. */
582
+ export function encodePcm16Wav(samples: Float32Array, sampleRate: number): Buffer {
583
+ const n = samples.length;
584
+ const buf = Buffer.alloc(44 + n * 2);
585
+ buf.write('RIFF', 0, 'ascii');
586
+ buf.writeUInt32LE(36 + n * 2, 4);
587
+ buf.write('WAVE', 8, 'ascii');
588
+ buf.write('fmt ', 12, 'ascii');
589
+ buf.writeUInt32LE(16, 16);
590
+ buf.writeUInt16LE(1, 20);
591
+ buf.writeUInt16LE(1, 22);
592
+ buf.writeUInt32LE(sampleRate, 24);
593
+ buf.writeUInt32LE(sampleRate * 2, 28);
594
+ buf.writeUInt16LE(2, 32);
595
+ buf.writeUInt16LE(16, 34);
596
+ buf.write('data', 36, 'ascii');
597
+ buf.writeUInt32LE(n * 2, 40);
598
+ for (let i = 0; i < n; i++) {
599
+ const s = Math.max(-1, Math.min(1, samples[i] ?? 0));
600
+ buf.writeInt16LE(Math.round(s * 32767), 44 + i * 2);
601
+ }
602
+ return buf;
603
+ }
604
+
605
+ export interface WavInfo {
606
+ /** 1 = PCM, 3 = float, 0xFFFE = extensible. */
607
+ format: number;
608
+ channels: number;
609
+ sampleRate: number;
610
+ bitsPerSample: number;
611
+ /** Bytes of sample data. */
612
+ dataBytes: number;
613
+ /** Seconds. */
614
+ duration: number;
615
+ }
616
+
617
+ /**
618
+ * The format and length of a RIFF/WAVE file from its header (the 'fmt ' and 'data' chunks, other
619
+ * chunks skipped). `fileSize` caps a data chunk that claims more than the file has (a streamed WAV).
620
+ * Null when it is not a WAV with both chunks.
621
+ */
622
+ export function parseWavHeader(bytes: Uint8Array, fileSize = bytes.length): WavInfo | null {
623
+ const b = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
624
+ if (b.length < 12 || b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WAVE') return null;
625
+ let fmt: Omit<WavInfo, 'dataBytes' | 'duration'> & { blockAlign: number } | null = null;
626
+ let dataBytes: number | null = null;
627
+ for (let at = 12; at + 8 <= b.length && (fmt === null || dataBytes === null); ) {
628
+ const id = b.toString('ascii', at, at + 4);
629
+ const size = b.readUInt32LE(at + 4);
630
+ if (id === 'fmt ' && at + 24 <= b.length) {
631
+ fmt = {
632
+ format: b.readUInt16LE(at + 8),
633
+ channels: b.readUInt16LE(at + 10),
634
+ sampleRate: b.readUInt32LE(at + 12),
635
+ blockAlign: b.readUInt16LE(at + 20),
636
+ bitsPerSample: b.readUInt16LE(at + 22),
637
+ };
638
+ } else if (id === 'data') {
639
+ dataBytes = Math.min(size, Math.max(0, fileSize - (at + 8)));
640
+ }
641
+ at += 8 + size + (size % 2);
642
+ }
643
+ if (!fmt || dataBytes === null || fmt.sampleRate <= 0 || fmt.channels <= 0) return null;
644
+ const frameBytes = fmt.blockAlign > 0 ? fmt.blockAlign : (fmt.channels * fmt.bitsPerSample) / 8;
645
+ if (!(frameBytes > 0)) return null;
646
+ const { blockAlign: _, ...info } = fmt;
647
+ return { ...info, dataBytes, duration: Math.floor(dataBytes / frameBytes) / fmt.sampleRate };
648
+ }
649
+
650
+ /**
651
+ * parseWavHeader of a file, reading only its first 64 KB; null when missing or not a WAV. The one
652
+ * test of whether a clip exists: speak, the render preflight, check and the studio's status all ask
653
+ * it (through videoClips), so a truncated clip is missing everywhere, never cached for one of them.
654
+ */
655
+ export function readClipInfo(file: string): WavInfo | null {
656
+ let fd: number;
657
+ try {
658
+ fd = openSync(file, 'r');
659
+ } catch {
660
+ return null;
661
+ }
662
+ try {
663
+ const { size } = fstatSync(fd);
664
+ const head = Buffer.alloc(Math.min(size, 64 * 1024));
665
+ readSync(fd, head, 0, head.length, 0);
666
+ return parseWavHeader(head, size);
667
+ } catch {
668
+ return null;
669
+ } finally {
670
+ closeSync(fd);
671
+ }
672
+ }
673
+
674
+ /** readClipInfo, as a promise. */
675
+ export async function readWavInfo(file: string): Promise<WavInfo | null> {
676
+ return readClipInfo(file);
677
+ }
678
+
679
+ /** Writes to a hidden temp file next to `file`, then renames it into place. */
680
+ export async function writeFileAtomic(file: string, bytes: Uint8Array | string): Promise<void> {
681
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}-${randomUUID().slice(0, 8)}.tmp`);
682
+ try {
683
+ await fs.writeFile(tmp, bytes);
684
+ await fs.rename(tmp, file);
685
+ } catch (err) {
686
+ await fs.rm(tmp, { force: true });
687
+ throw err;
688
+ }
689
+ }