@slidevideo/cli 0.3.0 → 0.3.1

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 (52) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -2
  3. package/addons/slidevideo/geometry.ts +334 -1
  4. package/addons/slidevideo/global-top.vue +57 -6
  5. package/addons/slidevideo/preview.ts +242 -25
  6. package/assets/fonts/OFL-LICENSES.txt +95 -0
  7. package/assets/fonts/instrument-serif-latin-2.woff2 +0 -0
  8. package/assets/fonts/instrument-serif-latin-ext-1.woff2 +0 -0
  9. package/assets/fonts/jetbrains-mono-latin-4.woff2 +0 -0
  10. package/assets/fonts/jetbrains-mono-latin-ext-3.woff2 +0 -0
  11. package/assets/fonts/plus-jakarta-sans-latin-6.woff2 +0 -0
  12. package/assets/fonts/plus-jakarta-sans-latin-ext-5.woff2 +0 -0
  13. package/dist/adapters/powerpoint-preview.d.ts +1 -1
  14. package/dist/adapters/powerpoint-preview.js +13 -2
  15. package/dist/adapters/powerpoint.js +91 -14
  16. package/dist/adapters/slidev-inspection.js +7 -2
  17. package/dist/annotation-paint.d.ts +195 -5
  18. package/dist/annotation-paint.js +1188 -2
  19. package/dist/annotations.d.ts +26 -2
  20. package/dist/annotations.js +1117 -29
  21. package/dist/captions.d.ts +6 -0
  22. package/dist/captions.js +320 -0
  23. package/dist/cli.js +40 -17
  24. package/dist/compositor.js +51 -3
  25. package/dist/contracts.d.ts +253 -14
  26. package/dist/pipeline.d.ts +6 -1
  27. package/dist/pipeline.js +66 -19
  28. package/dist/preview/contracts.d.ts +14 -0
  29. package/dist/preview/player.js +523 -33
  30. package/dist/preview/server.d.ts +1 -1
  31. package/dist/preview/server.js +124 -3
  32. package/dist/preview/view.d.ts +1 -1
  33. package/dist/preview/view.js +26 -7
  34. package/dist/run.d.ts +1 -0
  35. package/dist/run.js +20 -0
  36. package/dist/speech.d.ts +10 -1
  37. package/dist/speech.js +17 -1
  38. package/dist/stamp-fonts.d.ts +17 -0
  39. package/dist/stamp-fonts.js +202 -0
  40. package/dist/storyboard.js +60 -3
  41. package/dist/timing.d.ts +2 -0
  42. package/dist/timing.js +277 -11
  43. package/package.json +12 -1
  44. package/schemas/annotation-geometry.v1.json +111 -0
  45. package/schemas/schedule.v1.json +1672 -84
  46. package/schemas/storyboard.v1.json +3725 -85
  47. package/skills/slidevideo/SKILL.md +5 -5
  48. package/skills/slidevideo/references/decks.md +6 -4
  49. package/skills/slidevideo/references/production.md +12 -11
  50. package/skills/slidevideo/references/storyboard.md +268 -5
  51. package/tools/powerpoint/powerpoint.ps1 +155 -6
  52. package/tools/powerpoint/preview.ps1 +68 -1
@@ -0,0 +1,6 @@
1
+ import type { Schedule, SpeechManifest } from './contracts.js';
2
+ export type CaptionFormat = 'vtt' | 'srt';
3
+ export type CaptionSelection = CaptionFormat | 'both' | 'none';
4
+ export declare function writeCaptions(schedule: Schedule, speech: SpeechManifest, selection: CaptionSelection, basePath: string, audioOriginMs?: number, options?: {
5
+ protectExisting?: boolean;
6
+ }): Promise<Partial<Record<CaptionFormat, string>>>;
@@ -0,0 +1,320 @@
1
+ import { lstat, mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ import { requireCondition } from './errors.js';
4
+ const MAX_LINE_CHARS = 42;
5
+ const MAX_LINES_PER_CUE = 2;
6
+ const SENTENCE_BREAK_MIN_CHARS = 24;
7
+ const CLAUSE_BREAK_MIN_CHARS = 48;
8
+ function splitProportionally(text, startMs, endMs) {
9
+ const tokens = text.trim().split(/\s+/).filter(Boolean);
10
+ if (tokens.length <= 1)
11
+ return tokens.length ? [{ text: tokens[0], start_ms: startMs, end_ms: endMs }] : [];
12
+ const totalDur = Math.max(1, endMs - startMs);
13
+ const totalWeight = tokens.reduce((sum, token) => sum + Math.max(1, token.length), 0);
14
+ let consumed = 0;
15
+ return tokens.map((token, index) => {
16
+ const start = startMs + (totalDur * consumed) / totalWeight;
17
+ consumed += Math.max(1, token.length);
18
+ const end = index === tokens.length - 1 ? endMs : startMs + (totalDur * consumed) / totalWeight;
19
+ return { text: token, start_ms: start, end_ms: Math.max(start + 1, end) };
20
+ });
21
+ }
22
+ function extractTimedWords(alignment) {
23
+ if (!alignment.units.length)
24
+ return [];
25
+ if (alignment.granularity === 'word' || alignment.granularity === 'phrase') {
26
+ const units = alignment.units;
27
+ const words = [];
28
+ const leadSlice = alignment.text.slice(0, units[0].start);
29
+ let pendingPrefix = '';
30
+ if (leadSlice.trim()) {
31
+ if (/\s$/.test(leadSlice)) {
32
+ words.push(...splitProportionally(leadSlice, units[0].start_ms, units[0].start_ms));
33
+ }
34
+ else {
35
+ const lastWs = leadSlice.search(/\s[^\s]*$/);
36
+ if (lastWs >= 0) {
37
+ const standalone = leadSlice.slice(0, lastWs).trim();
38
+ if (standalone)
39
+ words.push(...splitProportionally(standalone, units[0].start_ms, units[0].start_ms));
40
+ pendingPrefix = leadSlice.slice(lastWs).trim();
41
+ }
42
+ else {
43
+ pendingPrefix = leadSlice.trim();
44
+ }
45
+ }
46
+ }
47
+ for (let i = 0; i < units.length; i++) {
48
+ const unit = units[i];
49
+ const core = unit.text.trim();
50
+ if (!core)
51
+ continue;
52
+ let text = pendingPrefix ? `${pendingPrefix}${core}` : core;
53
+ pendingPrefix = '';
54
+ const standaloneAfter = [];
55
+ if (i + 1 < units.length) {
56
+ const gap = alignment.text.slice(unit.end, units[i + 1].start);
57
+ const firstWs = gap.search(/\s/);
58
+ if (firstWs < 0) {
59
+ text += gap;
60
+ }
61
+ else {
62
+ const suffix = gap.slice(0, firstWs);
63
+ if (suffix)
64
+ text += suffix;
65
+ const rest = gap.slice(firstWs);
66
+ if (/\s$/.test(rest)) {
67
+ const middle = rest.trim();
68
+ if (middle)
69
+ standaloneAfter.push(middle);
70
+ }
71
+ else {
72
+ const lastWs = rest.search(/\s[^\s]*$/);
73
+ const middle = rest.slice(0, lastWs).trim();
74
+ if (middle)
75
+ standaloneAfter.push(middle);
76
+ pendingPrefix = rest.slice(lastWs).trim();
77
+ }
78
+ }
79
+ }
80
+ else {
81
+ const tail = alignment.text.slice(unit.end);
82
+ const firstWs = tail.search(/\s/);
83
+ if (firstWs < 0) {
84
+ if (tail)
85
+ text += tail;
86
+ }
87
+ else {
88
+ const suffix = tail.slice(0, firstWs);
89
+ if (suffix)
90
+ text += suffix;
91
+ const rest = tail.slice(firstWs).trim();
92
+ if (rest)
93
+ standaloneAfter.push(rest);
94
+ }
95
+ }
96
+ words.push(...splitProportionally(text, unit.start_ms, unit.end_ms));
97
+ for (const extra of standaloneAfter) {
98
+ const extraEnd = i + 1 < units.length ? Math.max(unit.end_ms, units[i + 1].start_ms) : unit.end_ms;
99
+ words.push(...splitProportionally(extra, unit.end_ms, extraEnd));
100
+ }
101
+ }
102
+ if (pendingPrefix && words.length > 0)
103
+ words[words.length - 1].text += pendingPrefix;
104
+ return words;
105
+ }
106
+ // Character granularity: group contiguous non-whitespace characters into words
107
+ const words = [];
108
+ let currentText = '';
109
+ let startMs = 0;
110
+ let endMs = 0;
111
+ for (const unit of alignment.units) {
112
+ if (/^\s+$/.test(unit.text)) {
113
+ if (currentText) {
114
+ words.push({ text: currentText, start_ms: startMs, end_ms: endMs });
115
+ currentText = '';
116
+ }
117
+ continue;
118
+ }
119
+ if (!currentText)
120
+ startMs = unit.start_ms;
121
+ currentText += unit.text;
122
+ endMs = unit.end_ms;
123
+ }
124
+ if (currentText)
125
+ words.push({ text: currentText, start_ms: startMs, end_ms: endMs });
126
+ return words;
127
+ }
128
+ function wrapLines(text) {
129
+ const words = text.trim().split(/\s+/).filter(Boolean);
130
+ if (!words.length)
131
+ return '';
132
+ const totalChars = words.reduce((sum, w) => sum + w.length, 0) + words.length - 1;
133
+ if (totalChars <= MAX_LINE_CHARS)
134
+ return words.join(' ');
135
+ // Balance across 2 lines when it fits in 2 lines
136
+ const target = Math.ceil(totalChars / 2);
137
+ let bestSplit = -1;
138
+ let bestDiff = Infinity;
139
+ let leftLen = 0;
140
+ for (let i = 0; i < words.length - 1; i++) {
141
+ leftLen += (i > 0 ? 1 : 0) + words[i].length;
142
+ const rightLen = totalChars - leftLen - 1;
143
+ if (leftLen <= MAX_LINE_CHARS && rightLen <= MAX_LINE_CHARS) {
144
+ const diff = Math.abs(leftLen - target);
145
+ if (diff < bestDiff) {
146
+ bestDiff = diff;
147
+ bestSplit = i + 1;
148
+ }
149
+ }
150
+ }
151
+ if (bestSplit > 0) {
152
+ return `${words.slice(0, bestSplit).join(' ')}\n${words.slice(bestSplit).join(' ')}`;
153
+ }
154
+ // Greedy wrap (at most MAX_LINES_PER_CUE lines for bounded cues)
155
+ const lines = [];
156
+ let current = '';
157
+ for (const word of words) {
158
+ if (!current)
159
+ current = word;
160
+ else if (current.length + 1 + word.length <= MAX_LINE_CHARS)
161
+ current += ` ${word}`;
162
+ else {
163
+ lines.push(current);
164
+ current = word;
165
+ }
166
+ }
167
+ if (current)
168
+ lines.push(current);
169
+ return lines.join('\n');
170
+ }
171
+ function fitsInLines(words, maxLines = MAX_LINES_PER_CUE) {
172
+ let lines = 1;
173
+ let lineLen = 0;
174
+ for (const word of words) {
175
+ if (lineLen === 0) {
176
+ lineLen = word.text.length;
177
+ }
178
+ else if (lineLen + 1 + word.text.length <= MAX_LINE_CHARS) {
179
+ lineLen += 1 + word.text.length;
180
+ }
181
+ else {
182
+ lines++;
183
+ if (lines > maxLines)
184
+ return false;
185
+ lineLen = word.text.length;
186
+ }
187
+ }
188
+ return true;
189
+ }
190
+ function chunkWordGroups(words) {
191
+ const groups = [];
192
+ let current = [];
193
+ let currentChars = 0;
194
+ const flush = () => {
195
+ if (!current.length)
196
+ return;
197
+ groups.push(current);
198
+ current = [];
199
+ currentChars = 0;
200
+ };
201
+ for (const word of words) {
202
+ if (current.length > 0 && !fitsInLines([...current, word]))
203
+ flush();
204
+ current.push(word);
205
+ currentChars = current.length === 1 ? word.text.length : currentChars + 1 + word.text.length;
206
+ const endsSentence = /[.!?]["'”’)\]]*$/.test(word.text);
207
+ const endsClause = /[,;:]["'”’)\]]*$/.test(word.text);
208
+ if ((endsSentence && currentChars >= SENTENCE_BREAK_MIN_CHARS) || (endsClause && currentChars >= CLAUSE_BREAK_MIN_CHARS)) {
209
+ flush();
210
+ }
211
+ }
212
+ flush();
213
+ return groups;
214
+ }
215
+ function buildCaptionCues(schedule, speech, audioOriginMs = 0) {
216
+ const assets = new Map(speech.assets.map(asset => [asset.id, asset]));
217
+ const rawCues = [];
218
+ for (const item of schedule.actions) {
219
+ if (item.action.type !== 'speak')
220
+ continue;
221
+ const asset = assets.get(item.action.segment);
222
+ if (!asset)
223
+ continue;
224
+ const segStart = item.start_ms + audioOriginMs;
225
+ const segEnd = item.end_ms + audioOriginMs;
226
+ const words = asset.alignment ? extractTimedWords(asset.alignment) : [];
227
+ if (words.length > 0) {
228
+ for (const group of chunkWordGroups(words)) {
229
+ const start = group[0].start_ms;
230
+ const end = group[group.length - 1].end_ms;
231
+ rawCues.push({
232
+ start_ms: Math.max(segStart, segStart + start),
233
+ end_ms: Math.min(segEnd, Math.max(segStart + start + 1, segStart + end)),
234
+ text: wrapLines(group.map(w => w.text).join(' ')),
235
+ });
236
+ }
237
+ }
238
+ else {
239
+ const plainWords = asset.transcript.original.trim().split(/\s+/).filter(Boolean).map(text => ({ text }));
240
+ const groups = chunkWordGroups(plainWords);
241
+ const totalDuration = Math.max(1, segEnd - segStart);
242
+ const weights = groups.map(group => Math.max(1, group.reduce((sum, w) => sum + w.text.length, 0) + group.length - 1));
243
+ const totalWeight = weights.reduce((sum, w) => sum + w, 0);
244
+ let consumed = 0;
245
+ for (let i = 0; i < groups.length; i++) {
246
+ const start = segStart + (totalDuration * consumed) / totalWeight;
247
+ consumed += weights[i];
248
+ const end = i === groups.length - 1 ? segEnd : segStart + (totalDuration * consumed) / totalWeight;
249
+ rawCues.push({
250
+ start_ms: start,
251
+ end_ms: Math.max(start + 1, end),
252
+ text: wrapLines(groups[i].map(w => w.text).join(' ')),
253
+ });
254
+ }
255
+ }
256
+ }
257
+ const cues = [];
258
+ let prevEnd = 0;
259
+ for (const cue of rawCues) {
260
+ const start_ms = Math.max(prevEnd, Math.round(cue.start_ms));
261
+ const end_ms = Math.max(start_ms + 1, Math.round(cue.end_ms));
262
+ prevEnd = end_ms;
263
+ cues.push({ index: cues.length + 1, start_ms, end_ms, text: cue.text });
264
+ }
265
+ return cues;
266
+ }
267
+ function formatTimestamp(ms, decimalSep) {
268
+ const clamped = Math.max(0, Math.round(ms));
269
+ const hours = Math.floor(clamped / 3_600_000);
270
+ const minutes = Math.floor((clamped % 3_600_000) / 60_000);
271
+ const seconds = Math.floor((clamped % 60_000) / 1000);
272
+ const millis = clamped % 1000;
273
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}${decimalSep}${String(millis).padStart(3, '0')}`;
274
+ }
275
+ function escapeVttText(text) {
276
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
277
+ }
278
+ function formatWebVtt(cues) {
279
+ const blocks = ['WEBVTT'];
280
+ for (const cue of cues) {
281
+ blocks.push(`${cue.index}\n${formatTimestamp(cue.start_ms, '.')} --> ${formatTimestamp(cue.end_ms, '.')}\n${escapeVttText(cue.text)}`);
282
+ }
283
+ return `${blocks.join('\n\n')}\n`;
284
+ }
285
+ function formatSrt(cues) {
286
+ if (!cues.length)
287
+ return '';
288
+ const blocks = cues.map(cue => `${cue.index}\n${formatTimestamp(cue.start_ms, ',')} --> ${formatTimestamp(cue.end_ms, ',')}\n${cue.text}`);
289
+ return `${blocks.join('\n\n')}\n`;
290
+ }
291
+ export async function writeCaptions(schedule, speech, selection, basePath, audioOriginMs = 0, options) {
292
+ if (selection === 'none')
293
+ return {};
294
+ const formats = selection === 'both' ? ['vtt', 'srt'] : [selection];
295
+ if (options?.protectExisting) {
296
+ for (const format of formats) {
297
+ const destination = `${basePath}.${format}`;
298
+ let exists = false;
299
+ try {
300
+ await lstat(destination);
301
+ exists = true;
302
+ }
303
+ catch (error) {
304
+ if (error.code !== 'ENOENT')
305
+ throw error;
306
+ }
307
+ requireCondition(!exists, 'OUTPUT_EXISTS', `Caption output already exists: ${destination}`);
308
+ }
309
+ }
310
+ const cues = buildCaptionCues(schedule, speech, audioOriginMs);
311
+ const written = {};
312
+ for (const format of formats) {
313
+ const destination = `${basePath}.${format}`;
314
+ await mkdir(dirname(destination), { recursive: true });
315
+ const content = format === 'vtt' ? formatWebVtt(cues) : formatSrt(cues);
316
+ await writeFile(destination, content, 'utf8');
317
+ written[format] = destination;
318
+ }
319
+ return written;
320
+ }
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import { existsSync } from 'node:fs';
4
4
  import { readFile } from 'node:fs/promises';
5
5
  import { servePreview } from './preview/server.js';
6
6
  import { produce } from './pipeline.js';
7
- import { resolve, join } from 'node:path';
7
+ import { join } from 'node:path';
8
8
  import { json } from './media.js';
9
9
  import { ProductionError, requireCondition } from './errors.js';
10
10
  import { packagePath, userConfigFile } from './installation.js';
@@ -97,13 +97,12 @@ let previewReady = false;
97
97
  let runDirectory;
98
98
  try {
99
99
  const { values, positionals } = parseArgs({ options: {
100
- storyboard: { type: 'string' }, deck: { type: 'string' }, width: { type: 'string' }, height: { type: 'string' }, fps: { type: 'string' }, port: { type: 'string' }, run: { type: 'string' }, 'cache-dir': { type: 'string' }, output: { type: 'string' }, export: { type: 'string' }, 'timeout-minutes': { type: 'string' },
100
+ storyboard: { type: 'string' }, deck: { type: 'string' }, width: { type: 'string' }, height: { type: 'string' }, fps: { type: 'string' }, port: { type: 'string' }, run: { type: 'string' }, 'cache-dir': { type: 'string' }, output: { type: 'string' }, captions: { type: 'string' }, export: { type: 'string' }, 'timeout-minutes': { type: 'string' },
101
101
  browser: { type: 'string' }, python: { type: 'string' }, ffmpeg: { type: 'string' }, ffprobe: { type: 'string' },
102
102
  presentation: { type: 'string' }, provider: { type: 'string' }, 'voice-id': { type: 'string' }, install: { type: 'boolean' }, project: { type: 'boolean' }, manual: { type: 'boolean' },
103
103
  license: { type: 'boolean' },
104
- json: { type: 'boolean' }, quiet: { type: 'boolean' }, resume: { type: 'boolean' }, 'verify-timing': { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
104
+ json: { type: 'boolean' }, quiet: { type: 'boolean' }, resume: { type: 'boolean' }, 'no-cache': { type: 'boolean' }, 'verify-timing': { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
105
105
  }, allowPositionals: true });
106
- runDirectory = values.run;
107
106
  command = positionals[0] ?? 'help';
108
107
  notifyUpdate(Boolean(values.json), Boolean(values.quiet));
109
108
  if (values.version) {
@@ -117,10 +116,12 @@ try {
117
116
  --deck <file> Inspect a .md or .pptx deck directly before a storyboard exists.
118
117
  --width/--height <px> Even viewport or output size (default: 1920x1080; PPTX inspect --deck uses slide size).
119
118
  --fps <15|24|30|60> Output frame rate for record, assemble, or build (default: 30).
120
- --run <directory> Required for artifact-producing commands.
121
- --cache-dir <dir> Speech cache for tts or build, read-only timing metadata for play.
119
+ --run <directory> Run directory (default: runs/YYYYMMDD-HHmmss for build and tts; required for resolve, record, assemble, and build --resume).
120
+ --cache-dir <dir> Speech cache directory for play, tts, or build (default: .slidevideo/speech beside storyboard).
121
+ --no-cache Disable speech cache reading and writing for play, tts, or build.
122
122
  --port <number> Local play server port (default: auto).
123
123
  --output <file> New final MP4 destination for assemble or build.
124
+ --captions <vtt|srt|both|none> Caption export (default: both for build/assemble with narration; optional for resolve).
124
125
  --resume Reuse intact build stages with matching inputs and mode.
125
126
  --verify-timing Opt in to decoded timing proof for build or record; assemble checks the recorded mode.
126
127
  --export <file> Optional resolved schedule export.
@@ -134,7 +135,7 @@ setup prepares shared tools and speech providers, and detects Slidev and native
134
135
  Normal production leaves timing unevaluated and the video for user review.
135
136
  inspect lists slide targets, click counts, media IDs and annotation targets from --deck or --storyboard without recording.
136
137
  validate checks inputs without recording.
137
- play --storyboard <file> serves silent slides and annotations with Play, Pause and Replay. Ctrl+C stops the server.
138
+ play --storyboard <file> serves slides and annotations (with cached audio when available) with Play, Pause and Replay. Ctrl+C stops the server.
138
139
  skill displays or registers (--install) the bundled coding-agent skill; see skill --help for references and options.
139
140
  license displays the bundled license terms. Use setup --license to manage activation.
140
141
  impressum displays the provider's contact details.
@@ -167,7 +168,7 @@ impressum displays the provider's contact details.
167
168
  await withExecutables({}, setupLicense);
168
169
  }
169
170
  else if (command === 'setup') {
170
- requireCondition(positionals.length === 1 && !['storyboard', 'deck', 'width', 'height', 'fps', 'port', 'run', 'cache-dir', 'output', 'export', 'timeout-minutes', 'resume', 'verify-timing', 'project'].some(key => key in values), 'OPTION', 'Run slidevideo setup --help for setup options');
171
+ requireCondition(positionals.length === 1 && !['storyboard', 'deck', 'width', 'height', 'fps', 'port', 'run', 'cache-dir', 'no-cache', 'output', 'captions', 'export', 'timeout-minutes', 'resume', 'verify-timing', 'project'].some(key => key in values), 'OPTION', 'Run slidevideo setup --help for setup options');
171
172
  let initialChecklist;
172
173
  const report = await withExecutables(values, () => setup(values, current => {
173
174
  initialChecklist = setupChecklist(current, configuredLicense());
@@ -228,9 +229,20 @@ impressum displays the provider's contact details.
228
229
  requireCondition(/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(raw) && Number.isFinite(minutes) && minutes > 0 && minutes <= 180, 'TIMEOUT', '--timeout-minutes must be a positive number up to 180');
229
230
  timeout = Math.ceil(minutes * 60_000);
230
231
  }
232
+ requireCondition(values.run === undefined || values.run.trim().length > 0, 'OPTION', '--run requires a directory path');
231
233
  requireCondition(!values.output || ['assemble', 'build'].includes(command), 'OPTION', '--output requires assemble or build');
234
+ requireCondition(values.captions === undefined || ['resolve', 'assemble', 'build'].includes(command), 'OPTION', '--captions requires resolve, assemble or build');
235
+ let captions;
236
+ if (values.captions !== undefined) {
237
+ const normalized = values.captions.trim().toLowerCase();
238
+ requireCondition(normalized === 'vtt' || normalized === 'srt' || normalized === 'both' || normalized === 'none', 'OPTION', '--captions must be vtt, srt, both or none');
239
+ captions = normalized;
240
+ }
232
241
  requireCondition(!values.resume || command === 'build', 'OPTION', '--resume requires build');
233
- requireCondition(!values['cache-dir'] || ['tts', 'build', 'play'].includes(command), 'OPTION', '--cache-dir requires play, tts or build');
242
+ requireCondition(values['cache-dir'] === undefined || ['tts', 'build', 'play'].includes(command), 'OPTION', '--cache-dir requires play, tts or build');
243
+ requireCondition(values['cache-dir'] === undefined || values['cache-dir'].trim().length > 0, 'OPTION', '--cache-dir requires a directory path');
244
+ requireCondition(!values['no-cache'] || ['tts', 'build', 'play'].includes(command), 'OPTION', '--no-cache requires play, tts or build');
245
+ requireCondition(!(values['cache-dir'] !== undefined && values['no-cache']), 'OPTION', 'Cannot combine --cache-dir and --no-cache');
234
246
  requireCondition(!values.export || ['resolve', 'build'].includes(command), 'OPTION', '--export requires resolve or build');
235
247
  requireCondition(!values['verify-timing'] || ['record', 'assemble', 'build'].includes(command), 'OPTION', '--verify-timing requires record, assemble or build');
236
248
  requireCondition(values.port === undefined || command === 'play', 'OPTION', '--port requires play');
@@ -265,13 +277,14 @@ impressum displays the provider's contact details.
265
277
  else {
266
278
  requireCondition(values.deck === undefined, 'OPTION', '--deck requires inspect');
267
279
  }
280
+ const cache = values['no-cache'] ? false : values['cache-dir'];
268
281
  await withExecutables(values, async () => {
269
282
  if (command === 'play') {
270
283
  requireCondition(values.storyboard, 'STORYBOARD_REQUIRED', 'play requires --storyboard');
271
- requireCondition(values.run === undefined && values['timeout-minutes'] === undefined, 'OPTION', 'play takes --storyboard, --cache-dir, --port, --width and --height; Ctrl+C stops the server');
284
+ requireCondition(values.run === undefined && values['timeout-minutes'] === undefined, 'OPTION', 'play takes --storyboard, --cache-dir, --no-cache, --port, --width and --height; Ctrl+C stops the server');
272
285
  const port = Number(values.port ?? 0);
273
286
  requireCondition(values.port === undefined || /^\d+$/.test(values.port) && Number.isInteger(port) && port <= 65535, 'PREVIEW_PORT', '--port must be between 0 and 65535');
274
- await servePreview(values.storyboard, values['cache-dir'], port, viewport, (url, approximate) => {
287
+ await servePreview(values.storyboard, cache, port, viewport, (url, approximate) => {
275
288
  previewReady = true;
276
289
  console.log(values.json ? JSON.stringify({ version: 1, command, status: 'ready', url, approximate, timing_status: 'not_evaluated' }) : `Open ${url} to preview the storyboard. Press Ctrl+C to stop.`);
277
290
  });
@@ -289,9 +302,18 @@ impressum displays the provider's contact details.
289
302
  progress?.(operation);
290
303
  const heartbeat = progress ? setInterval(() => process.stderr.write(`[slidevideo] ${operation} (${Math.floor((Date.now() - started) / 1000)}s elapsed)\n`), 5000) : undefined;
291
304
  try {
292
- const result = await produce({ command, storyboard: values.storyboard, inspect: inspectInput, viewport, fps, run: values.run, cache: values['cache-dir'], output: values.output, export: values.export, resume: values.resume, verify_timing: values['verify-timing'], timeout_ms: timeout, progress });
305
+ const result = await produce({ command, storyboard: values.storyboard, inspect: inspectInput, viewport, fps, run: values.run, cache, output: values.output, captions, export: values.export, resume: values.resume, verify_timing: values['verify-timing'], timeout_ms: timeout, progress, onRunResolved: directory => { runDirectory = directory; } });
293
306
  progress?.(`${command} completed`);
294
- console.log(values.json || command === 'inspect' ? JSON.stringify(result) : `${command} completed${result.artifacts.video ? `: ${result.artifacts.video}` : ''}`);
307
+ const captionFiles = [result.artifacts.captions_vtt, result.artifacts.captions_srt].filter(Boolean);
308
+ const details = [
309
+ ...(result.run_dir ? [`run: ${result.run_dir}`] : []),
310
+ ...(captionFiles.length ? [`captions: ${captionFiles.join(', ')}`] : []),
311
+ ];
312
+ const suffix = details.length ? ` (${details.join('; ')})` : '';
313
+ const summary = result.artifacts.video
314
+ ? `${command} completed: ${result.artifacts.video}${suffix}`
315
+ : `${command} completed${suffix}`;
316
+ console.log(values.json || command === 'inspect' ? JSON.stringify(result) : summary);
295
317
  }
296
318
  catch (error) {
297
319
  progress?.(`${command} failed`);
@@ -307,14 +329,15 @@ impressum displays the provider's contact details.
307
329
  catch (error) {
308
330
  const failure = error instanceof ProductionError ? error : new ProductionError('INTERNAL', error instanceof Error ? error.message : String(error), error instanceof TypeError ? 2 : 1);
309
331
  let run;
310
- if (runDirectory) {
332
+ const resolvedRun = runDirectory;
333
+ if (resolvedRun) {
311
334
  try {
312
- run = await json(join(resolve(runDirectory), 'manifest.json'));
335
+ run = await json(join(resolvedRun, 'manifest.json'));
313
336
  }
314
337
  catch { }
315
338
  }
316
- const result = { version: 1, command, status: 'failed', run_id: run?.run_id, completed_stages: Object.entries(run?.stages ?? {}).filter(([, stage]) => stage?.status === 'completed').map(([name]) => name), artifacts: run ? { manifest: join(resolve(runDirectory), 'manifest.json') } : {}, timing_status: 'not_accepted', warnings: [], errors: [{ stage: command, code: failure.code, message: failure.message, ...failure.context }] };
317
- const diagnostic = jsonMode ? JSON.stringify(result) : `${failure.code}: ${failure.message}`;
339
+ const result = { version: 1, command, status: 'failed', run_id: run?.run_id, ...(resolvedRun ? { run_dir: resolvedRun } : {}), completed_stages: Object.entries(run?.stages ?? {}).filter(([, stage]) => stage?.status === 'completed').map(([name]) => name), artifacts: run && resolvedRun ? { manifest: join(resolvedRun, 'manifest.json') } : {}, timing_status: 'not_accepted', warnings: [], errors: [{ stage: command, code: failure.code, message: failure.message, ...failure.context }] };
340
+ const diagnostic = jsonMode ? JSON.stringify(result) : `${failure.code}: ${failure.message}${resolvedRun ? ` (run: ${resolvedRun})` : ''}`;
318
341
  if (previewReady)
319
342
  console.error(diagnostic);
320
343
  else
@@ -2,11 +2,12 @@ import { spawn } from 'node:child_process';
2
2
  import { writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { createCanvas, ImageData } from '@napi-rs/canvas';
5
- import { effectDirtyBounds, effectNeedsBaseFrames, paintEffects } from './annotation-paint.js';
5
+ import { activeViewTransform, effectDirtyBounds, effectNeedsBaseFrames, hasActiveSpotlight, paintEffects } from './annotation-paint.js';
6
6
  import { balancedSum, executionSignal, ffmpegFilterScriptFlags, hasStageDeadline } from './media.js';
7
7
  import { executable } from './executables.js';
8
8
  import { ProductionError, requireCondition } from './errors.js';
9
9
  import { loadOverlayImage } from './overlay-assets.js';
10
+ import { ensureStampFonts } from './stamp-fonts.js';
10
11
  export async function frameLayers(output, schedule, licensed, hashes) {
11
12
  const layers = [];
12
13
  const images = new Map();
@@ -241,6 +242,8 @@ function createFrameReader(stream, frameBytes, decoded) {
241
242
  export async function compositeFrames(source, baseFilter, encoderArgs, output, applications, plan, frameCount, audioOrigin, stagingDirectory) {
242
243
  const signal = executionSignal();
243
244
  signal?.throwIfAborted();
245
+ if (applications.some(app => app.effect === 'stamp'))
246
+ ensureStampFonts();
244
247
  const bytes = output.width * output.height * 4;
245
248
  const slots = [Buffer.alloc(bytes), Buffer.alloc(bytes)];
246
249
  const slotOpaque = [false, false];
@@ -289,10 +292,29 @@ export async function compositeFrames(source, baseFilter, encoderArgs, output, a
289
292
  signal?.addEventListener('abort', onAbort, { once: true });
290
293
  });
291
294
  let readbackContext;
295
+ let sourceCanvas;
296
+ let sourceContext;
292
297
  let overlayContext;
293
298
  let overlayCanvasDirty;
299
+ let maskCanvas;
300
+ let maskContext;
294
301
  const ensureReadbackContext = () => readbackContext ??= createCanvas(output.width, output.height).getContext('2d', { alpha: false });
302
+ const ensureSourceCanvas = () => {
303
+ sourceCanvas ??= createCanvas(output.width, output.height);
304
+ sourceContext ??= sourceCanvas.getContext('2d', { alpha: false });
305
+ return { canvas: sourceCanvas, context: sourceContext };
306
+ };
295
307
  const ensureOverlayContext = () => overlayContext ??= createCanvas(output.width, output.height).getContext('2d');
308
+ const ensureSpotlightScratch = () => {
309
+ maskCanvas ??= createCanvas(output.width, output.height);
310
+ maskContext ??= maskCanvas.getContext('2d');
311
+ return {
312
+ context: maskContext,
313
+ drawTo: (target, { x, y, width, height }) => {
314
+ target.drawImage(maskCanvas, x, y, width, height, x, y, width, height);
315
+ },
316
+ };
317
+ };
296
318
  let emittedCount = 0;
297
319
  let paintedFrames = 0;
298
320
  let intervalIndex = 0;
@@ -343,7 +365,33 @@ export async function compositeFrames(source, baseFilter, encoderArgs, output, a
343
365
  const context = ensureReadbackContext();
344
366
  const { x: dx, y: dy, width: dw, height: dh } = dirty;
345
367
  context.putImageData(slotImages[slot], 0, 0, dx, dy, dw, dh);
346
- paintEffects(context, activeAnnotations, outputTime);
368
+ const view = activeViewTransform(activeAnnotations, outputTime);
369
+ if (view) {
370
+ const source = ensureSourceCanvas();
371
+ const { x: cx, y: cy, width: cw, height: ch } = view.content;
372
+ source.context.putImageData(slotImages[slot], 0, 0, cx, cy, cw, ch);
373
+ context.save();
374
+ context.beginPath();
375
+ context.rect(cx, cy, cw, ch);
376
+ context.clip();
377
+ context.translate(cx, cy);
378
+ context.scale(view.scale, view.scale);
379
+ context.translate(-view.source.x, -view.source.y);
380
+ context.imageSmoothingEnabled = true;
381
+ context.imageSmoothingQuality = 'high';
382
+ context.drawImage(source.canvas, 0, 0);
383
+ paintEffects(context, activeAnnotations, outputTime, {
384
+ backdrop: true,
385
+ spotlightScratch: hasActiveSpotlight(activeAnnotations, outputTime) ? ensureSpotlightScratch() : undefined,
386
+ });
387
+ context.restore();
388
+ }
389
+ else {
390
+ paintEffects(context, activeAnnotations, outputTime, {
391
+ backdrop: true,
392
+ spotlightScratch: hasActiveSpotlight(activeAnnotations, outputTime) ? ensureSpotlightScratch() : undefined,
393
+ });
394
+ }
347
395
  paintFrameLayers(context, plan.canvasLayers, scheduleTime);
348
396
  copyPatchToBuffer(context.getImageData(dx, dy, dw, dh).data, target, output.width, dirty);
349
397
  paintedFrames++;
@@ -364,7 +412,7 @@ export async function compositeFrames(source, baseFilter, encoderArgs, output, a
364
412
  if (overlayCanvasDirty) {
365
413
  context.clearRect(overlayCanvasDirty.x, overlayCanvasDirty.y, overlayCanvasDirty.width, overlayCanvasDirty.height);
366
414
  }
367
- paintEffects(context, activeAnnotations, outputTime);
415
+ paintEffects(context, activeAnnotations, outputTime, { backdrop: false });
368
416
  paintFrameLayers(context, plan.canvasLayers, scheduleTime);
369
417
  overlayCanvasDirty = dirty;
370
418
  copyPatchToBuffer(context.getImageData(dirty.x, dirty.y, dirty.width, dirty.height).data, target, output.width, dirty);