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
@@ -0,0 +1,812 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import {
5
+ FORMATS,
6
+ docSpans,
7
+ getFormat,
8
+ parseDoc,
9
+ resolveGifRender,
10
+ resolveTimeline,
11
+ resolveVoice,
12
+ rulesSummary,
13
+ speechFitIssues,
14
+ captionCues,
15
+ captionTimingIssues,
16
+ ignoredWarnings,
17
+ issueWarningId,
18
+ layoutWarningId,
19
+ layoutWarnings,
20
+ resolveCaptions,
21
+ secondsPerWord,
22
+ trackBpm,
23
+ validateDoc,
24
+ withoutIgnored,
25
+ type CaptionIssue,
26
+ type FormatId,
27
+ type GifOptions,
28
+ type GifRange,
29
+ type LayoutFinding,
30
+ type LayoutIssue,
31
+ type LoudnessReport,
32
+ type ResolvedGifSettings,
33
+ type ProjectConfig,
34
+ type ReadTimeIssue,
35
+ type ResolvedTimeline,
36
+ type SpeechIssue,
37
+ type ValidationIssue,
38
+ type ValidationResult,
39
+ type VideoDoc,
40
+ type WarningId,
41
+ } from '@beatsheet/core';
42
+ import type { Command, GifFlags } from './args';
43
+ import { checkDoc } from './server/api';
44
+ import { startServer, type RunningServer } from './server/server';
45
+ import { canonicalPath, describeProject, discoverProject, errorMessage, projectReloader, videoName, type ProjectContext } from './project';
46
+ import { launchBrowser } from './render/browser';
47
+ import { captureStills, collectCaptionIssues, collectLayoutIssues, collectReadTimeIssues } from './render/capture';
48
+ import { sheetArgs, startFfmpeg } from './render/ffmpeg';
49
+ import { checkTimes, createEventPrinter, openPlayer, renderVideo, stillTimes, transitionStills, type RenderOutput } from './render/render';
50
+ import { ASSET_PREFIX, PLAYER_BASE, userCwd } from './paths';
51
+ import { svgTextWarnings } from './svg-text';
52
+ import {
53
+ clipDurations,
54
+ planSpeech,
55
+ projectSpeechPlugins,
56
+ speakVideo,
57
+ speechPreflight,
58
+ unusedClips,
59
+ videoClips,
60
+ type SpeechPlugins,
61
+ type SpokenClip,
62
+ } from './speech';
63
+
64
+ export type Log = (line: string) => void;
65
+
66
+ export interface LoadedVideo {
67
+ /** Absolute path of the *.video.json. */
68
+ path: string;
69
+ file: string;
70
+ name: string;
71
+ doc: VideoDoc;
72
+ json: unknown;
73
+ project: ProjectContext;
74
+ }
75
+
76
+ export class CheckFailed extends Error {
77
+ constructor(public readonly issues: ValidationIssue[]) {
78
+ super(issues.map((i) => `${formatPath(i.path)}: ${i.message}`).join('\n'));
79
+ }
80
+ }
81
+
82
+ /** Reads + structurally parses a video file and loads its project. */
83
+ export async function loadVideo(file: string): Promise<LoadedVideo> {
84
+ // The on-disk spelling names the outputs (OCTOBER.video.json must not write OCTOBER-16x9.mp4 next to october-16x9.mp4).
85
+ const abs = await canonicalPath(path.resolve(file));
86
+ let text: string;
87
+ try {
88
+ text = await fs.readFile(abs, 'utf8');
89
+ } catch {
90
+ throw new Error(`Cannot read ${abs}`);
91
+ }
92
+ let json: unknown;
93
+ try {
94
+ json = JSON.parse(text);
95
+ } catch (err) {
96
+ throw new CheckFailed([{ path: [], message: `Invalid JSON: ${errorMessage(err)}`, severity: 'error' }]);
97
+ }
98
+ const checked = checkDoc(json);
99
+ if (!checked.ok) throw new CheckFailed(checked.issues);
100
+ const project = await discoverProject(abs);
101
+ return { path: abs, file: path.basename(abs), name: videoName(abs), doc: checked.doc, json, project };
102
+ }
103
+
104
+ /** Internal server for render/stills/check: serves the video's own folder as videosDir. */
105
+ export function videoServer(v: Pick<LoadedVideo, 'path' | 'project'>, opts: { onAsset?: (file: string) => void } = {}): Promise<RunningServer> {
106
+ return startServer({ project: v.project, mode: 'render', videosDir: path.dirname(v.path), onAsset: opts.onAsset });
107
+ }
108
+
109
+ export function formatPath(p: (string | number)[]): string {
110
+ if (p.length === 0) return '(document)';
111
+ return p.map((s, i) => (typeof s === 'number' ? `[${s}]` : i === 0 ? s : `.${s}`)).join('');
112
+ }
113
+
114
+ // ---------------------------------------------------------------------------
115
+
116
+ /**
117
+ * The GIF settings of a CLI render: the video's export.gif overridden by the flags, checked against
118
+ * its scenes. Errors name the flag (or export.gif when the stored settings are the problem).
119
+ */
120
+ export function gifFromFlags(doc: VideoDoc, flags: GifFlags, file: string): ResolvedGifSettings {
121
+ const spans = docSpans(doc);
122
+ const options: GifOptions = {};
123
+ if (flags.preset !== undefined) options.preset = flags.preset;
124
+ if (flags.fps !== undefined) options.fps = flags.fps;
125
+ if (flags.width !== undefined) options.width = flags.width;
126
+ if (flags.loop !== undefined) options.loop = flags.loop;
127
+ if (flags.scene !== undefined) options.range = { kind: 'scene', scene: flags.scene };
128
+ else if (flags.from !== undefined || flags.to !== undefined) {
129
+ if ((flags.from ?? 0) >= spans.duration) {
130
+ throw new Error(`--gif-from: the GIF range starts at or after the video end (from ${flags.from}s, the video is ${Math.round(spans.duration * 100) / 100}s)`);
131
+ }
132
+ options.range = { kind: 'time', from: flags.from ?? 0, to: flags.to ?? spans.duration };
133
+ }
134
+ const r = resolveGifRender(doc, options);
135
+ if (r.ok) return r.settings;
136
+ if (r.stored) {
137
+ const hint = r.field === 'range' ? ' (override it with --gif-scene or --gif-from/--gif-to)' : '';
138
+ throw new Error(`export.gif.${r.field} in ${file}: ${r.message}${hint}`);
139
+ }
140
+ const flag = r.field !== 'range' ? `--gif-${r.field}` : flags.scene !== undefined ? '--gif-scene' : flags.to !== undefined ? '--gif-to' : '--gif-from';
141
+ throw new Error(`${flag}: ${r.message}`);
142
+ }
143
+
144
+ /** 'whole video', 'scene "intro"', '1.5-4s'. */
145
+ export function describeGifRange(range: GifRange): string {
146
+ return range.kind === 'scene' ? `scene "${range.scene}"` : range.kind === 'time' ? `${range.from}-${range.to}s` : 'whole video';
147
+ }
148
+
149
+ export async function runRender(cmd: Extract<Command, { cmd: 'render' }>, log: Log): Promise<RenderOutput[]> {
150
+ const v = await loadVideo(cmd.file);
151
+ const formats = cmd.formats ?? v.doc.formats;
152
+ const outDir = cmd.out ? path.resolve(cmd.out) : v.project.outDir;
153
+ const gif = cmd.gif ? gifFromFlags(v.doc, cmd.gif, v.file) : undefined;
154
+ const mp4 = cmd.gif?.only !== true;
155
+ const what = gif
156
+ ? `; ${mp4 ? 'MP4 + ' : ''}GIF ${gif.fps} fps, ${gif.width} px, ${describeGifRange(gif.range)}, loop ${gif.loop}`
157
+ : '';
158
+ // Narration: an MP4 needs every clip (stop before the first frame); a GIF is silent.
159
+ const speech = speechPreflight(v, cmd.file);
160
+ if (speech && mp4) throw new Error(speech);
161
+ log(`render ${v.file} (${formats.join(', ')}${what}) -> ${outDir}`);
162
+ if (speech) log(`note: the GIF is silent, so the narration is not needed for it:\n${speech}`);
163
+ const print = createEventPrinter();
164
+ const server = await videoServer(v);
165
+ try {
166
+ const outputs = await renderVideo({
167
+ baseUrl: server.url,
168
+ file: v.file,
169
+ formats,
170
+ name: v.name,
171
+ outDir,
172
+ mp4,
173
+ gif,
174
+ emit: (e) => {
175
+ const line = print(e);
176
+ if (line) log(line);
177
+ },
178
+ });
179
+ for (const line of loudnessLines(outputs)) log(line);
180
+ log('done');
181
+ return outputs;
182
+ } finally {
183
+ await server.close();
184
+ }
185
+ }
186
+
187
+ /** A narrated mix's loudness: '-16.0 LUFS', or 'peak-capped: 1.3 dB under -16 LUFS' when the peak cap won. */
188
+ export function formatLoudness(l: LoudnessReport): string {
189
+ return l.peakCapped ? `peak-capped: ${l.shortfall.toFixed(1)} dB under ${l.target} LUFS` : `${l.result.toFixed(1)} LUFS`;
190
+ }
191
+
192
+ /** '[16:9] loudness -16.0 LUFS' per output of a narrated render (none without narration). */
193
+ export function loudnessLines(outputs: readonly RenderOutput[]): string[] {
194
+ return outputs.flatMap((o) => (o.audio?.loudness ? [`[${o.format}] loudness ${formatLoudness(o.audio.loudness)}`] : []));
195
+ }
196
+
197
+ // ---------------------------------------------------------------------------
198
+
199
+ export interface StillsResult {
200
+ format: FormatId;
201
+ dir: string;
202
+ files: string[];
203
+ sheet?: string;
204
+ }
205
+
206
+ export async function runStills(cmd: Extract<Command, { cmd: 'stills' }>, log: Log): Promise<StillsResult[]> {
207
+ const v = await loadVideo(cmd.file);
208
+ const formats = cmd.formats ?? v.doc.formats;
209
+ const outRoot = path.join(cmd.out ? path.resolve(cmd.out) : v.project.outDir, 'stills');
210
+ // Stills are silent: a missing clip is only a note.
211
+ const speech = speechPreflight(v, cmd.file);
212
+ if (speech) log(`note: stills are silent, so the narration is not needed for them:\n${speech}`);
213
+ const server = await videoServer(v);
214
+ const browser = await launchBrowser();
215
+ try {
216
+ return await Promise.all(
217
+ formats.map(async (format): Promise<StillsResult> => {
218
+ const bp = await openPlayer(browser, server.url, v.file, format);
219
+ try {
220
+ const times = stillTimes(bp.timeline, cmd);
221
+ const base = `${v.name}-${bp.format.slug}`;
222
+ const dir = path.join(outRoot, base);
223
+ // Earlier runs stay unless --clean asks, and --clean removes only what runs of this kind wrote:
224
+ // an --at run survives the --clean of a default run.
225
+ const kind = stillsRunKind(cmd);
226
+ const runs = await readStillsRuns(dir);
227
+ if (cmd.clean) {
228
+ await cleanStillsRun(dir, kind, runs);
229
+ await fs.rm(path.join(outRoot, stillsSheetName(base, cmd)), { force: true });
230
+ }
231
+ const files = await captureStills(bp, times, dir);
232
+ runs[kind] = [...new Set([...(runs[kind] ?? []), ...files.map((f) => path.basename(f))])].sort();
233
+ await writeStillsRuns(dir, runs);
234
+ const kept = (await fs.readdir(dir)).filter((f) => STILL_FILE.test(f) && !files.includes(path.join(dir, f))).length;
235
+ const keptNote = cmd.clean ? 'of other kinds of run kept' : 'from earlier runs kept; --clean removes those of this kind of run';
236
+ log(`[${format}] ${files.length} stills -> ${dir}${kept > 0 ? ` (${kept} ${keptNote})` : ''}`);
237
+ if (cmd.transitions) {
238
+ for (const s of transitionStills(bp.timeline)) log(`[${format}] t${s.t.toFixed(2)}.png ${s.kind} into "${s.scene}": ${TRANSITION_PART[s.part]}`);
239
+ }
240
+ const result: StillsResult = { format, dir, files };
241
+ if (cmd.sheet && files.length > 0) {
242
+ result.sheet = path.join(outRoot, stillsSheetName(base, cmd));
243
+ await buildSheet(files, result.sheet);
244
+ log(`[${format}] contact sheet ${result.sheet}`);
245
+ }
246
+ return result;
247
+ } finally {
248
+ await bp.close();
249
+ }
250
+ }),
251
+ );
252
+ } finally {
253
+ await browser.close();
254
+ await server.close();
255
+ }
256
+ }
257
+
258
+ /** A still of `stills <file>`: t<seconds>.png. */
259
+ const STILL_FILE = /^t[\d.]+\.png$/;
260
+
261
+ /** What a transition still shows, for the run's log. */
262
+ const TRANSITION_PART = { out: 'the scene before, leaving', in: 'the scene arriving', both: 'the edge half way, both scenes' } as const;
263
+
264
+ /**
265
+ * The contact sheet of a `stills` run, named after the kind of run, so runs of different kinds keep
266
+ * their sheets: <base>-sheet.png (one still per scene), -sheet-at, -sheet-beats, and each with
267
+ * -transitions (e.g. <base>-sheet-transitions.png, <base>-sheet-beats-transitions.png).
268
+ */
269
+ export function stillsSheetName(base: string, run: StillsRun): string {
270
+ const kind = stillsRunKind(run);
271
+ return `${[base, 'sheet', ...(kind === DEFAULT_STILLS_RUN ? [] : [kind])].join('-')}.png`;
272
+ }
273
+
274
+ type StillsRun = { at?: number[]; beats?: boolean; transitions?: boolean };
275
+
276
+ /** The kind of a run with neither --at, --beats nor --transitions: one still per scene. */
277
+ const DEFAULT_STILLS_RUN = 'default';
278
+
279
+ /** The kind of a `stills` run: default, at, beats, transitions, at-transitions or beats-transitions. */
280
+ export function stillsRunKind(run: StillsRun): string {
281
+ return [run.at ? 'at' : run.beats ? 'beats' : '', run.transitions ? 'transitions' : ''].filter(Boolean).join('-') || DEFAULT_STILLS_RUN;
282
+ }
283
+
284
+ /**
285
+ * The record of a stills folder, `.stills-runs.json` in it: which stills each kind of run wrote
286
+ * (`{ "version": 1, "runs": { "default": ["t0.10.png"], "at": ["t0.33.png"] } }`), since a still's
287
+ * name carries no kind. Only `stills --clean` reads it; a sheet is built from the run's own stills.
288
+ */
289
+ export const STILLS_RUNS_FILE = '.stills-runs.json';
290
+
291
+ type StillsRuns = Record<string, string[]>;
292
+
293
+ /** The record of `dir`; empty when there is none (a folder written before the record existed) or it cannot be read. */
294
+ async function readStillsRuns(dir: string): Promise<StillsRuns> {
295
+ try {
296
+ const parsed = JSON.parse(await fs.readFile(path.join(dir, STILLS_RUNS_FILE), 'utf8')) as { runs?: unknown };
297
+ const runs: StillsRuns = {};
298
+ if (parsed.runs && typeof parsed.runs === 'object') {
299
+ for (const [kind, names] of Object.entries(parsed.runs)) {
300
+ if (Array.isArray(names)) runs[kind] = names.filter((n): n is string => typeof n === 'string' && STILL_FILE.test(n));
301
+ }
302
+ }
303
+ return runs;
304
+ } catch {
305
+ return {};
306
+ }
307
+ }
308
+
309
+ async function writeStillsRuns(dir: string, runs: StillsRuns): Promise<void> {
310
+ await fs.mkdir(dir, { recursive: true });
311
+ await fs.writeFile(path.join(dir, STILLS_RUNS_FILE), `${JSON.stringify({ version: 1, runs }, null, 2)}\n`);
312
+ }
313
+
314
+ /**
315
+ * `stills --clean` for a run of `kind`: removes the stills earlier runs of this kind wrote and empties
316
+ * the kind's entry in `runs`. A still another kind wrote too stays until that kind is cleaned. The default
317
+ * kind also takes the stills no kind has on record (written before the record existed).
318
+ */
319
+ async function cleanStillsRun(dir: string, kind: string, runs: StillsRuns): Promise<void> {
320
+ const others = new Set(Object.entries(runs).flatMap(([k, names]) => (k === kind ? [] : names)));
321
+ let own = runs[kind] ?? [];
322
+ if (kind === DEFAULT_STILLS_RUN) {
323
+ try {
324
+ own = (await fs.readdir(dir)).filter((f) => STILL_FILE.test(f));
325
+ } catch {
326
+ own = [];
327
+ }
328
+ }
329
+ await Promise.all(own.filter((f) => !others.has(f)).map((f) => fs.rm(path.join(dir, f), { force: true })));
330
+ runs[kind] = [];
331
+ }
332
+
333
+ /** Removes stills (t*.png, or what `pattern` matches) of earlier runs (`stills --clean`), so the folder shows only this run. */
334
+ export async function clearStills(dir: string, pattern = STILL_FILE): Promise<void> {
335
+ let entries: string[] = [];
336
+ try {
337
+ entries = await fs.readdir(dir);
338
+ } catch {
339
+ return;
340
+ }
341
+ await Promise.all(entries.filter((f) => pattern.test(f)).map((f) => fs.rm(path.join(dir, f), { force: true })));
342
+ }
343
+
344
+ /** Contact sheet: every PNG scaled to 480 px wide, tiled 4 per row. */
345
+ export async function buildSheet(files: string[], out: string): Promise<void> {
346
+ const ff = startFfmpeg(sheetArgs({ count: files.length, out }));
347
+ try {
348
+ for (const f of files) await ff.write(await fs.readFile(f));
349
+ } catch (err) {
350
+ ff.kill();
351
+ throw err;
352
+ }
353
+ await ff.finish();
354
+ }
355
+
356
+ // ---------------------------------------------------------------------------
357
+
358
+ export interface CheckReport {
359
+ issues: ValidationIssue[];
360
+ timelineWarnings: string[];
361
+ layout: { format: FormatId; t: number; issue: LayoutIssue }[];
362
+ /** Scenes too short to read, one per scene: the format(s) missing the most (warnings). */
363
+ readTime: ReadTimeWarning[];
364
+ /** Narration: lines that do not fit their scene, run into the next, or are not spoken yet (warnings). */
365
+ speech: SpeechIssue[];
366
+ /** Captions (VideoDoc.captions): chunks shown too briefly to read, captions that cover a scene text (warnings). */
367
+ captions: CaptionIssue[];
368
+ errors: number;
369
+ /** The warnings printed: without the silenced ones. */
370
+ warnings: number;
371
+ /** Warnings left out by the ignore lists (rules.ignoreWarnings of the project, ignoreWarnings of the video). */
372
+ silenced: number;
373
+ /** The ids that left at least one warning out, in the order of the report. */
374
+ silencedIds: WarningId[];
375
+ }
376
+
377
+ /** What a check found, before the ignore lists are applied. */
378
+ export type CheckFindings = Pick<CheckReport, 'issues' | 'timelineWarnings' | 'layout' | 'readTime' | 'speech' | 'captions'>;
379
+
380
+ const speechId = (w: SpeechIssue): WarningId => `speech-${w.kind}`;
381
+ const captionId = (w: CaptionIssue): WarningId => `captions-${w.kind}`;
382
+
383
+ /**
384
+ * The report of what a check found: the warnings whose id is in `ignored` (ignoredWarnings) are left
385
+ * out and counted in `silenced`. Errors and layout issues are never left out, and neither is a
386
+ * warning without an id (a 'timeline' line: it repeats an error).
387
+ */
388
+ export function checkReport(found: CheckFindings, ignored: ReadonlySet<string> = new Set()): CheckReport {
389
+ const silencedIds: WarningId[] = [];
390
+ let silenced = 0;
391
+ // The filter itself is core's withoutIgnored: the studio's problem list applies the same one.
392
+ const keep = <T>(items: readonly T[], id: (item: T) => WarningId | undefined): T[] => {
393
+ const split = withoutIgnored(items, id, ignored);
394
+ silenced += split.silenced.length;
395
+ for (const code of split.ids) if (!silencedIds.includes(code)) silencedIds.push(code);
396
+ return split.kept;
397
+ };
398
+ const issues = keep(found.issues, issueWarningId);
399
+ const readTime = keep(found.readTime, () => 'read-time');
400
+ const speech = keep(found.speech, speechId);
401
+ const captions = keep(found.captions, captionId);
402
+ const errors = issues.filter((i) => i.severity === 'error').length + found.layout.length;
403
+ const warnings = issues.filter((i) => i.severity === 'warning').length + found.timelineWarnings.length + readTime.length + speech.length + captions.length;
404
+ return { issues, timelineWarnings: found.timelineWarnings, layout: found.layout, readTime, speech, captions, errors, warnings, silenced, silencedIds };
405
+ }
406
+
407
+ /** A read-time issue of the worst format; `formats` lists every format missing that much. */
408
+ export type ReadTimeWarning = ReadTimeIssue & { formats: FormatId[] };
409
+
410
+ /** One warning per scene from the issues of all formats: the largest shortfall, in doc order. */
411
+ export function worstReadTime(issues: ReadTimeIssue[], doc: Pick<VideoDoc, 'scenes'>): ReadTimeWarning[] {
412
+ const by = new Map<string, ReadTimeWarning>();
413
+ for (const issue of issues) {
414
+ const known = by.get(issue.sceneId);
415
+ if (!known || issue.missing > known.missing) by.set(issue.sceneId, { ...issue, formats: [issue.format] });
416
+ else if (issue.missing === known.missing && !known.formats.includes(issue.format)) known.formats.push(issue.format);
417
+ }
418
+ const order = (id: string): number => doc.scenes.findIndex((s) => s.id === id);
419
+ // Formats are checked in parallel: list them in the canonical order, not the order they finished.
420
+ const formatOrder = Object.keys(FORMATS);
421
+ for (const w of by.values()) w.formats.sort((a, b) => formatOrder.indexOf(a) - formatOrder.indexOf(b));
422
+ return [...by.values()].sort((a, b) => order(a.sceneId) - order(b.sceneId));
423
+ }
424
+
425
+ const secs = (x: number): string => String(Math.round(x * 100) / 100);
426
+
427
+ /**
428
+ * e.g. 'scene "feature" (feature-list) needs 7.4 s, has 6.2 s: +1.2 s (4:5) · all 31 words', or for
429
+ * a text that leaves before the exit (a longer scene does not help):
430
+ * 'scene "hook" (kinetic-type) text gone at 1.3 s, needs 2.4 s, has 0.95 s: +1.5 s (16:9) · 8 words in "one two" · slow it down, a longer scene won't help'.
431
+ */
432
+ export function formatReadTime(w: ReadTimeWarning): string {
433
+ const words = `${secs(w.words)} words`;
434
+ const where = `+${w.missing.toFixed(1)} s (${w.formats.join(', ')})`;
435
+ if (w.leaves !== undefined) {
436
+ const what = w.kind === 'scene' ? `texts gone by ${secs(w.leaves)} s, need ${secs(w.need)} s, have` : `text gone at ${secs(w.leaves)} s, needs ${secs(w.need)} s, has`;
437
+ const detail = w.kind === 'scene' ? words : `${words} in "${w.text ?? w.element ?? ''}"`;
438
+ return `scene "${w.sceneId}" (${w.type}) ${what} ${secs(w.has)} s: ${where} · ${detail} · slow it down, a longer scene won't help`;
439
+ }
440
+ const detail = w.kind === 'scene' ? `all ${words}` : `${words} in "${w.text ?? w.element ?? ''}"`;
441
+ return `scene "${w.sceneId}" (${w.type}) needs ${secs(w.duration + w.missing)} s, has ${secs(w.duration)} s: ${where} · ${detail}`;
442
+ }
443
+
444
+ /**
445
+ * Validation + timeline warnings + layout issues at every beat per format, and a warning for every
446
+ * SVG image of the video that has live text without text-rendering="geometricPrecision" (./svg-text).
447
+ */
448
+ export async function runCheck(cmd: Extract<Command, { cmd: 'check' }>, log: Log): Promise<CheckReport> {
449
+ let v: LoadedVideo;
450
+ try {
451
+ v = await loadVideo(cmd.file);
452
+ } catch (err) {
453
+ if (!(err instanceof CheckFailed)) throw err;
454
+ const report = checkReport({ issues: err.issues, timelineWarnings: [], layout: [], readTime: [], speech: [], captions: [] });
455
+ printCheck(cmd.file, null, report, log);
456
+ return report;
457
+ }
458
+ const { validation, timeline, timelineWarnings: tw } = validateVideo(v.json, v.doc, v.project.config);
459
+ const timelineWarnings = tw.map((w) => w.text);
460
+ const speech = timeline ? await speechWarnings(v, timeline, cmd.file) : [];
461
+ const captionsOn = timeline !== null && resolveCaptions(v.doc) !== null;
462
+ const captionFound: CaptionIssue[] = captionsOn ? await captionTimingWarnings(v, timeline, cmd.formats ?? v.doc.formats) : [];
463
+
464
+ const layout: CheckReport['layout'] = [];
465
+ // Labels that cover each other and code lines that wrap: warnings (layout-overlap, code-wrap).
466
+ const layoutSoft: LayoutFinding[] = [];
467
+ const readIssues: ReadTimeIssue[] = [];
468
+ const formats = cmd.formats ?? v.doc.formats;
469
+ const pageErrors: { format: FormatId; errors: { kind: 'page' | 'console'; text: string }[] }[] = [];
470
+ // The project asset files the pages load: every scene is mounted at once, so every picture of the video is asked for.
471
+ const assets = new Set<string>();
472
+ const server = await videoServer(v, { onAsset: (file) => void assets.add(file) });
473
+ const browser = await launchBrowser();
474
+ try {
475
+ await Promise.all(
476
+ formats.map(async (format) => {
477
+ const bp = await openPlayer(browser, server.url, v.file, format);
478
+ try {
479
+ const seen = new Set<string>();
480
+ // Every beat, and each scene's settled moment for the layout warnings alone: the last label of a scene pops in on the last beat.
481
+ const beatTimes = new Set(checkTimes(bp.timeline));
482
+ for (const { t, issues } of await collectLayoutIssues(bp, checkTimes(bp.timeline, { settled: true }))) {
483
+ for (const issue of issues) {
484
+ if (layoutWarningId(issue)) {
485
+ layoutSoft.push({ format, t, issue });
486
+ continue;
487
+ }
488
+ if (!beatTimes.has(t)) continue;
489
+ const key = `${issue.sceneId}|${issue.element}|${issue.kind}`;
490
+ if (seen.has(key)) continue;
491
+ seen.add(key);
492
+ layout.push({ format, t, issue });
493
+ }
494
+ }
495
+ readIssues.push(...(await collectReadTimeIssues(bp)));
496
+ if (captionsOn) captionFound.push(...(await collectCaptionIssues(bp)));
497
+ pageErrors.push({ format, errors: [...bp.errors] });
498
+ } finally {
499
+ await bp.close();
500
+ }
501
+ }),
502
+ );
503
+ } finally {
504
+ await browser.close();
505
+ await server.close();
506
+ }
507
+ layout.sort((a, b) => a.format.localeCompare(b.format) || a.t - b.t);
508
+ validation.issues.push(...playerErrorIssues(pageErrors, v.doc));
509
+ validation.issues.push(...(await svgTextWarnings(assets, v.project.assetsDir, v.json)));
510
+ validation.issues.push(...layoutWarnings(layoutSoft, v.doc.scenes));
511
+ const readTime = worstReadTime(readIssues, v.doc);
512
+ const captions = mergeCaptionIssues(captionFound, formats);
513
+ const report = checkReport(
514
+ { issues: validation.issues, timelineWarnings, layout, readTime, speech, captions },
515
+ ignoredWarnings(v.doc, v.project.config.rules),
516
+ );
517
+ printCheck(v.file, { v, timeline }, report, log);
518
+ return report;
519
+ }
520
+
521
+ /**
522
+ * The narration warnings of `check`: speechFitIssues with the clip lengths read from the WAV headers
523
+ * next to the video and the beat of the video's music track ('missing' for lines not spoken yet).
524
+ */
525
+ export async function speechWarnings(v: Pick<LoadedVideo, 'path' | 'doc' | 'project'>, timeline: ResolvedTimeline, file: string): Promise<SpeechIssue[]> {
526
+ const clips = videoClips(v);
527
+ if (clips.length === 0) return [];
528
+ const durations = await clipDurations(clips);
529
+ const track = v.doc.music ? v.project.config.theme?.music?.[v.doc.music.track] : undefined;
530
+ return speechFitIssues(timeline, durations, { bpm: trackBpm(track), voice: resolveVoice(v.doc, v.project.config), file });
531
+ }
532
+
533
+ /**
534
+ * The 'brief' caption warnings of `check` per format: captionTimingIssues of the cues timed by the
535
+ * clip lengths read from the WAV headers (an estimate where a clip is missing) at the project's
536
+ * reading speed.
537
+ */
538
+ export async function captionTimingWarnings(
539
+ v: Pick<LoadedVideo, 'path' | 'doc' | 'project'>,
540
+ timeline: ResolvedTimeline,
541
+ formats: readonly FormatId[],
542
+ ): Promise<CaptionIssue[]> {
543
+ const durations = await clipDurations(videoClips(v));
544
+ const spw = secondsPerWord(v.project.config);
545
+ return formats.flatMap((format) => captionTimingIssues(captionCues(v.doc, timeline, format, durations), format, spw));
546
+ }
547
+
548
+ /** One caption warning per message, in time order; " [4:5]" names the formats when not every checked one has it. */
549
+ export function mergeCaptionIssues(issues: readonly CaptionIssue[], formats: readonly FormatId[]): CaptionIssue[] {
550
+ const byMessage = new Map<string, { issue: CaptionIssue; formats: Set<FormatId> }>();
551
+ for (const issue of issues) {
552
+ const entry = byMessage.get(issue.message) ?? { issue, formats: new Set<FormatId>() };
553
+ entry.formats.add(issue.format);
554
+ byMessage.set(issue.message, entry);
555
+ }
556
+ return [...byMessage.values()]
557
+ .map(({ issue, formats: f }) => (f.size === formats.length ? issue : { ...issue, message: `${issue.message} [${[...f].join(', ')}]` }))
558
+ .sort((a, b) => a.t - b.t || a.index - b.index);
559
+ }
560
+
561
+ const SCENE_ERROR = /^beatsheet: scene "([^"]*)"(?: \([^)]*\))? (.*)$/;
562
+
563
+ /**
564
+ * The player catches a scene's mount/update errors, shows a placeholder and only logs them, so the
565
+ * layout looks fine: report those (and uncaught page errors) as errors, once per scene and message.
566
+ */
567
+ export function playerErrorIssues(
568
+ pages: { format: FormatId; errors: { kind: 'page' | 'console'; text: string }[] }[],
569
+ doc: VideoDoc,
570
+ ): ValidationIssue[] {
571
+ const out = new Map<string, { issue: ValidationIssue; formats: Set<FormatId> }>();
572
+ for (const { format, errors } of pages) {
573
+ for (const e of errors) {
574
+ const m = e.kind === 'console' ? SCENE_ERROR.exec(e.text) : null;
575
+ if (!m && e.kind !== 'page') continue;
576
+ const index = m ? doc.scenes.findIndex((s) => s.id === m[1]) : -1;
577
+ const issue: ValidationIssue = m
578
+ ? { path: index >= 0 ? ['scenes', index] : [], message: `player: scene "${m[1]}" ${m[2]}`, severity: 'error' }
579
+ : { path: [], message: `player: uncaught ${e.text}`, severity: 'error' };
580
+ const entry = out.get(issue.message) ?? { issue, formats: new Set<FormatId>() };
581
+ entry.formats.add(format);
582
+ out.set(issue.message, entry);
583
+ }
584
+ }
585
+ const all = pages.length;
586
+ return [...out.values()].map(({ issue, formats }) =>
587
+ formats.size === all ? issue : { ...issue, message: `${issue.message} [${[...formats].join(', ')}]` },
588
+ );
589
+ }
590
+
591
+ export interface VideoValidation {
592
+ validation: ValidationResult;
593
+ timeline: ResolvedTimeline | null;
594
+ /** Timeline warnings not already among the validation issues; sceneId for a scene's own. */
595
+ timelineWarnings: { sceneId?: string; message: string; text: string }[];
596
+ }
597
+
598
+ /** validateDoc + resolveTimeline; a timeline that cannot resolve becomes a validation error. */
599
+ export function validateVideo(json: unknown, doc: VideoDoc, project: ProjectConfig): VideoValidation {
600
+ const validation = validateDoc(json, project);
601
+ let timeline: ResolvedTimeline | null = null;
602
+ try {
603
+ timeline = resolveTimeline(doc, project);
604
+ } catch (err) {
605
+ validation.issues.push({ path: [], message: `Timeline: ${errorMessage(err)}`, severity: 'error' });
606
+ }
607
+ const known = new Set(validation.issues.map((i) => i.message));
608
+ const all = timeline
609
+ ? [
610
+ ...timeline.warnings.map((w) => ({ message: w, text: w })),
611
+ ...timeline.scenes.flatMap((s) => s.warnings.map((w) => ({ sceneId: s.id, message: w, text: `${s.id}: ${w}` }))),
612
+ ]
613
+ : [];
614
+ const timelineWarnings = all.filter((w) => !known.has(w.text) && ![...known].some((k) => w.text.endsWith(k) || k.endsWith(w.text)));
615
+ return { validation, timeline, timelineWarnings };
616
+ }
617
+
618
+ /**
619
+ * The report as lines: every warning ends with its id in brackets (what an ignoreWarnings list
620
+ * takes), and the last line counts the warnings the ignore lists left out.
621
+ */
622
+ export function printCheck(file: string, ctx: { v: LoadedVideo; timeline: ResolvedTimeline | null } | null, r: CheckReport, log: Log): void {
623
+ log(`check ${file}`);
624
+ if (ctx) {
625
+ log(` project ${describeProject(ctx.v.project)}`);
626
+ const rules = rulesSummary(ctx.v.project.config.rules);
627
+ if (rules) log(` rules ${rules}`);
628
+ const tl = ctx.timeline;
629
+ if (tl) {
630
+ log(` video "${ctx.v.doc.title}" · ${tl.scenes.length} scenes · ${tl.duration.toFixed(2)} s · ${tl.frameCount} frames @ ${tl.fps} fps · ${ctx.v.doc.formats.join(', ')}`);
631
+ }
632
+ }
633
+ const errs = r.issues.filter((i) => i.severity === 'error');
634
+ const warns = r.issues.filter((i) => i.severity === 'warning');
635
+ if (errs.length) {
636
+ log(`\nerrors (${errs.length})`);
637
+ for (const i of errs) log(` ${formatPath(i.path)} ${i.message}`);
638
+ }
639
+ if (warns.length || r.timelineWarnings.length || r.readTime.length || r.speech.length || r.captions.length) {
640
+ log(`\nwarnings (${warns.length + r.timelineWarnings.length + r.readTime.length + r.speech.length + r.captions.length})`);
641
+ for (const i of warns) log(` ${formatPath(i.path)} ${i.message}${i.code ? ` [${i.code}]` : ''}`);
642
+ for (const w of r.timelineWarnings) log(` timeline ${w}`);
643
+ for (const w of r.readTime) log(` read time ${formatReadTime(w)} [read-time]`);
644
+ for (const w of r.speech) log(` speech ${w.message} [${speechId(w)}]`);
645
+ for (const w of r.captions) log(` captions ${w.message} [${captionId(w)}]`);
646
+ }
647
+ const byFormat = new Map<FormatId, CheckReport['layout']>();
648
+ for (const l of r.layout) byFormat.set(l.format, [...(byFormat.get(l.format) ?? []), l]);
649
+ for (const [format, items] of byFormat) {
650
+ log(`\nlayout ${format} (${items.length})`);
651
+ for (const { t, issue } of items) {
652
+ log(` ${t.toFixed(2)}s ${issue.sceneId} ${issue.element} ${issue.kind} by ${Math.round(issue.amount)}px`);
653
+ }
654
+ }
655
+ const silenced = r.silenced ? `, ${r.silenced} silenced (${r.silencedIds.join(', ')})` : '';
656
+ log(`\n${r.errors === 0 ? 'ok' : 'failed'}: ${r.errors} error${r.errors === 1 ? '' : 's'}, ${r.warnings} warning${r.warnings === 1 ? '' : 's'}${silenced}`);
657
+ }
658
+
659
+ // ---------------------------------------------------------------------------
660
+
661
+ export interface SpeakReport {
662
+ /** Clips spoken in this run. */
663
+ spoken: SpokenClip[];
664
+ /** Narrated scenes whose clip was already there. */
665
+ cached: string[];
666
+ /** --dry-run: the scenes it would speak. */
667
+ wouldSpeak: { sceneId: string; key: string; characters: number }[];
668
+ /** --prune: clip files deleted (with --dry-run: that would be). */
669
+ pruned: string[];
670
+ }
671
+
672
+ /**
673
+ * `beatsheet speak`: speaks every narrated scene whose clip is missing (--scene: only those,
674
+ * --force: also existing ones) with one engine load, or lists them (--dry-run); --prune deletes
675
+ * clips no video in the folder uses. `plugins` replaces the project's plugin packages (tests).
676
+ */
677
+ export async function runSpeak(cmd: Extract<Command, { cmd: 'speak' }>, log: Log, deps: { plugins?: SpeechPlugins } = {}): Promise<SpeakReport> {
678
+ const v = await loadVideo(cmd.file);
679
+ const opts = { ...(cmd.scenes ? { scenes: cmd.scenes } : {}), force: cmd.force, file: cmd.file };
680
+ const plan = planSpeech(v, opts);
681
+ const report: SpeakReport = { spoken: [], cached: [], wouldSpeak: [], pruned: [] };
682
+ const n = plan.clips.length;
683
+ log(`speak ${cmd.file}${plan.voice ? ` · ${plan.voice}` : ''} · ${n} narrated scene${n === 1 ? '' : 's'}${cmd.scenes ? ' selected' : ''}${cmd.dryRun ? ' · dry run' : ''}`);
684
+ if (n === 0) log(' nothing to speak: no scene has narration');
685
+ const width = Math.max(0, ...plan.clips.map((c) => c.sceneId.length));
686
+ const todo = new Set(plan.todo);
687
+ for (const c of plan.clips) {
688
+ if (todo.has(c)) continue;
689
+ const same = plan.todo.find((t) => t.key === c.key);
690
+ if (same) log(` ${c.sceneId.padEnd(width)} same line as "${same.sceneId}" speech/${c.key}.wav`);
691
+ else {
692
+ report.cached.push(c.sceneId);
693
+ log(` ${c.sceneId.padEnd(width)} cached speech/${c.key}.wav`);
694
+ }
695
+ }
696
+ if (cmd.dryRun) {
697
+ for (const c of plan.todo) {
698
+ report.wouldSpeak.push({ sceneId: c.sceneId, key: c.key, characters: c.text.length });
699
+ log(` ${c.sceneId.padEnd(width)} would speak ${c.text.length} characters speech/${c.key}.wav "${c.text}"`);
700
+ }
701
+ } else if (plan.todo.length > 0) {
702
+ const plugins = deps.plugins ?? projectSpeechPlugins(v.project.root);
703
+ const result = await speakVideo(v, opts, {
704
+ plugins,
705
+ log,
706
+ emit: (e) => {
707
+ if (e.type === 'loading') log(` loading ${plan.engine}…`);
708
+ },
709
+ });
710
+ report.spoken = result.spoken;
711
+ }
712
+ if (cmd.prune) {
713
+ const dir = path.dirname(v.path);
714
+ const unused = await unusedClips(dir, v.project, (json) => {
715
+ const checked = checkDoc(json);
716
+ if (!checked.ok) throw new Error(checked.issues.map((i) => `${formatPath(i.path)}: ${i.message}`).join('; '));
717
+ return checked.doc;
718
+ });
719
+ for (const f of unused) {
720
+ if (!cmd.dryRun) await fs.rm(f, { force: true });
721
+ report.pruned.push(f);
722
+ log(` ${cmd.dryRun ? 'would prune' : 'pruned'} ${path.relative(dir, f)}`);
723
+ }
724
+ if (unused.length === 0) log(' prune: every clip in speech/ is used');
725
+ }
726
+ log(speakSummary(report, cmd.dryRun));
727
+ return report;
728
+ }
729
+
730
+ function speakSummary(r: SpeakReport, dryRun: boolean): string {
731
+ const parts: string[] = [];
732
+ if (dryRun) {
733
+ const chars = r.wouldSpeak.reduce((a, c) => a + c.characters, 0);
734
+ parts.push(`${r.wouldSpeak.length} to speak (${chars} characters)`);
735
+ } else {
736
+ const audio = r.spoken.reduce((a, c) => a + c.seconds, 0);
737
+ const took = r.spoken.reduce((a, c) => a + c.took, 0);
738
+ parts.push(r.spoken.length ? `${r.spoken.length} spoken (${audio.toFixed(2)} s of audio in ${took.toFixed(2)} s, ${(took / audio).toFixed(2)}x real time)` : '0 spoken');
739
+ }
740
+ parts.push(`${r.cached.length} cached`);
741
+ if (r.pruned.length) parts.push(`${r.pruned.length} ${dryRun ? 'to prune' : 'pruned'}`);
742
+ return `${dryRun ? 'dry run' : 'done'}: ${parts.join(', ')}`;
743
+ }
744
+
745
+ // ---------------------------------------------------------------------------
746
+
747
+ /** Starts the studio server and resolves when it is closed (SIGINT/SIGTERM or the returned stop()). */
748
+ export async function runStudio(cmd: Extract<Command, { cmd: 'studio' }>, log: Log, cwd = userCwd()): Promise<RunningServer> {
749
+ const project = await discoverProject(cwd, cwd);
750
+ // The speech status, speech jobs and the render preflight take beatsheet.config.ts as it is now.
751
+ const currentProject = projectReloader(project, log);
752
+ const print = createEventPrinter();
753
+ const server = await startServer({
754
+ project,
755
+ currentProject,
756
+ mode: 'studio',
757
+ port: cmd.port,
758
+ host: cmd.host,
759
+ log,
760
+ renderRunner: (baseUrl) => async (file, formats, emit, opts): Promise<void> => {
761
+ const abs = path.join(project.videosDir, file);
762
+ const doc = parseDoc(JSON.parse(await fs.readFile(abs, 'utf8')));
763
+ const wanted = formats ?? doc.formats;
764
+ for (const f of wanted) getFormat(f);
765
+ let gif: ResolvedGifSettings | undefined;
766
+ if (opts?.gif) {
767
+ const r = resolveGifRender(doc, opts.gif);
768
+ if (!r.ok) throw new Error(`${r.stored ? 'export.gif' : 'gif'}.${r.field}: ${r.message}`);
769
+ gif = r.settings;
770
+ }
771
+ const mp4 = opts?.mp4 !== false;
772
+ if (mp4) {
773
+ const speech = speechPreflight({ path: abs, doc, project: await currentProject() }, path.relative(cwd, abs) || abs);
774
+ if (speech) throw new Error(speech);
775
+ }
776
+ log(`render ${file} (${wanted.join(', ')}${gif ? `; ${mp4 ? 'MP4 + ' : ''}GIF ${gif.fps} fps, ${gif.width} px` : ''})`);
777
+ const outputs = await renderVideo({
778
+ baseUrl,
779
+ file,
780
+ formats: wanted,
781
+ name: videoName(file),
782
+ outDir: project.outDir,
783
+ mp4,
784
+ gif,
785
+ emit: (e) => {
786
+ emit(e);
787
+ const line = print(e);
788
+ if (line) log(line);
789
+ },
790
+ });
791
+ for (const line of loudnessLines(outputs)) log(line);
792
+ },
793
+ });
794
+ log(`beatsheet studio · ${describeProject(project)}`);
795
+ log(` studio ${server.url}/`);
796
+ log(` player ${server.url}${PLAYER_BASE}?video=<file>&format=16:9&mode=studio`);
797
+ log(` api ${server.url}/api/project`);
798
+ log(` assets ${server.url}${ASSET_PREFIX} -> ${project.assetsDir}`);
799
+ log(` videos ${project.videosDir}`);
800
+ if (cmd.open) openInBrowser(`${server.url}/`);
801
+ return server;
802
+ }
803
+
804
+ export function openInBrowser(url: string): void {
805
+ const [bin, args] =
806
+ process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
807
+ try {
808
+ spawn(bin as string, args as string[], { detached: true, stdio: 'ignore' }).unref();
809
+ } catch {
810
+ // best effort
811
+ }
812
+ }