@slidevideo/cli 0.3.0 → 0.3.2

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 (61) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +3 -3
  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/edge.d.ts +1 -0
  14. package/dist/adapters/edge.js +4 -3
  15. package/dist/adapters/elevenlabs.d.ts +1 -0
  16. package/dist/adapters/elevenlabs.js +4 -3
  17. package/dist/adapters/powerpoint-preview.d.ts +1 -1
  18. package/dist/adapters/powerpoint-preview.js +13 -2
  19. package/dist/adapters/powerpoint.js +91 -14
  20. package/dist/adapters/slidev-inspection.js +7 -2
  21. package/dist/annotation-paint.d.ts +195 -5
  22. package/dist/annotation-paint.js +1188 -2
  23. package/dist/annotations.d.ts +26 -2
  24. package/dist/annotations.js +1117 -29
  25. package/dist/assembly.js +143 -37
  26. package/dist/captions.d.ts +6 -0
  27. package/dist/captions.js +320 -0
  28. package/dist/cli.js +59 -19
  29. package/dist/compositor.d.ts +17 -2
  30. package/dist/compositor.js +108 -26
  31. package/dist/contracts.d.ts +254 -14
  32. package/dist/media.js +24 -1
  33. package/dist/pipeline.d.ts +6 -1
  34. package/dist/pipeline.js +68 -20
  35. package/dist/preview/contracts.d.ts +15 -0
  36. package/dist/preview/player.js +527 -34
  37. package/dist/preview/server.d.ts +1 -1
  38. package/dist/preview/server.js +125 -4
  39. package/dist/preview/view.d.ts +1 -1
  40. package/dist/preview/view.js +26 -7
  41. package/dist/run.d.ts +1 -0
  42. package/dist/run.js +20 -0
  43. package/dist/speech.d.ts +13 -3
  44. package/dist/speech.js +164 -45
  45. package/dist/stamp-fonts.d.ts +17 -0
  46. package/dist/stamp-fonts.js +202 -0
  47. package/dist/storyboard.js +60 -3
  48. package/dist/timing.d.ts +4 -1
  49. package/dist/timing.js +322 -14
  50. package/dist/update-check-worker.js +43 -11
  51. package/dist/update-check.js +14 -10
  52. package/package.json +12 -1
  53. package/schemas/annotation-geometry.v1.json +111 -0
  54. package/schemas/schedule.v1.json +1672 -84
  55. package/schemas/storyboard.v1.json +3725 -85
  56. package/skills/slidevideo/SKILL.md +5 -5
  57. package/skills/slidevideo/references/decks.md +6 -4
  58. package/skills/slidevideo/references/production.md +12 -11
  59. package/skills/slidevideo/references/storyboard.md +268 -5
  60. package/tools/powerpoint/powerpoint.ps1 +155 -6
  61. package/tools/powerpoint/preview.ps1 +68 -1
package/dist/assembly.js CHANGED
@@ -1,10 +1,107 @@
1
1
  import { join, dirname } from 'node:path';
2
+ import { spawn } from 'node:child_process';
3
+ import { createWriteStream } from 'node:fs';
2
4
  import { lstat, mkdir, mkdtemp, link, rm, copyFile, writeFile } from 'node:fs/promises';
3
5
  import { defaultVideoOutput } from './contracts.js';
4
- import { execute, ffmpegFilterScriptFlags, hashFile, probe, decode, saveJson } from './media.js';
5
- import { requireCondition } from './errors.js';
6
- import { configuredLicense } from './executables.js';
6
+ import { execute, executionScope, executionSignal, ffmpegFilterScriptFlags, hashFile, probe, decode, saveJson } from './media.js';
7
+ import { ProductionError, requireCondition } from './errors.js';
8
+ import { configuredLicense, executable } from './executables.js';
7
9
  import { annotationApplications, verifyAnnotations } from './annotations.js';
10
+ const NARRATION_SAMPLE_RATE = 48000;
11
+ const NARRATION_CHANNELS = 2;
12
+ const NARRATION_BYTES_PER_SAMPLE = 4 * NARRATION_CHANNELS; // f32le stereo
13
+ const ZERO_CHUNK = Buffer.alloc(65536);
14
+ async function writeChunk(stream, chunk) {
15
+ executionSignal()?.throwIfAborted();
16
+ if (stream.write(chunk))
17
+ return;
18
+ await new Promise((resolve, reject) => {
19
+ const onDrain = () => { cleanup(); resolve(); };
20
+ const onError = (error) => { cleanup(); reject(error); };
21
+ const cleanup = () => { stream.off('drain', onDrain); stream.off('error', onError); };
22
+ stream.once('drain', onDrain);
23
+ stream.once('error', onError);
24
+ });
25
+ }
26
+ async function appendDecodedNarration(stream, audioPath, maxBytes) {
27
+ const command = executable('ffmpeg');
28
+ const context = executionScope.getStore();
29
+ const signal = context?.signal;
30
+ signal?.throwIfAborted();
31
+ const child = spawn(command, ['-v', 'error', '-xerror', '-i', audioPath, '-vn', '-ac', String(NARRATION_CHANNELS), '-ar', String(NARRATION_SAMPLE_RATE), '-f', 'f32le', '-'], {
32
+ stdio: ['ignore', 'pipe', 'pipe'],
33
+ signal,
34
+ killSignal: 'SIGKILL',
35
+ windowsHide: true,
36
+ });
37
+ const err = [];
38
+ const limit = context?.bounded ? undefined : 120000;
39
+ const timer = limit !== undefined ? setTimeout(() => { child.kill('SIGKILL'); }, limit) : undefined;
40
+ child.stderr.on('data', data => err.push(data));
41
+ const exit = new Promise((resolve, reject) => {
42
+ child.on('error', error => { clearTimeout(timer); reject(new ProductionError('DEPENDENCY', `${command}: ${error.message}`, 3)); });
43
+ child.on('close', code => {
44
+ clearTimeout(timer);
45
+ if (code !== 0)
46
+ reject(new ProductionError('SUBPROCESS', `${command} exited ${code}: ${Buffer.concat(err).toString().slice(-4000)}`, 3));
47
+ else
48
+ resolve();
49
+ });
50
+ });
51
+ let written = 0;
52
+ try {
53
+ for await (const chunk of child.stdout) {
54
+ const remaining = maxBytes - written;
55
+ if (remaining <= 0)
56
+ continue;
57
+ const slice = chunk.length <= remaining ? chunk : chunk.subarray(0, remaining);
58
+ if (slice.length > 0) {
59
+ await writeChunk(stream, slice);
60
+ written += slice.length;
61
+ }
62
+ }
63
+ await exit;
64
+ }
65
+ catch (error) {
66
+ child.kill('SIGKILL');
67
+ await exit.catch(() => { });
68
+ throw error;
69
+ }
70
+ return written;
71
+ }
72
+ async function writeNarrationTrack(destination, items, audioOrigin) {
73
+ const stream = createWriteStream(destination);
74
+ let writtenSamples = 0;
75
+ try {
76
+ for (const { item, asset } of items) {
77
+ executionSignal()?.throwIfAborted();
78
+ const targetStartSample = Math.round(((item.start_ms + audioOrigin) * NARRATION_SAMPLE_RATE) / 1000);
79
+ requireCondition(targetStartSample >= writtenSamples, 'ASSEMBLY', `Narration segment ${item.id} overlaps an earlier segment`, 7);
80
+ let gapBytes = (targetStartSample - writtenSamples) * NARRATION_BYTES_PER_SAMPLE;
81
+ while (gapBytes > 0) {
82
+ const size = Math.min(gapBytes, ZERO_CHUNK.length);
83
+ await writeChunk(stream, size === ZERO_CHUNK.length ? ZERO_CHUNK : ZERO_CHUNK.subarray(0, size));
84
+ gapBytes -= size;
85
+ }
86
+ writtenSamples = targetStartSample;
87
+ const maxSamples = Math.round((asset.duration_ms * NARRATION_SAMPLE_RATE) / 1000);
88
+ const writtenBytes = await appendDecodedNarration(stream, asset.audio, maxSamples * NARRATION_BYTES_PER_SAMPLE);
89
+ const remainder = writtenBytes % NARRATION_BYTES_PER_SAMPLE;
90
+ if (remainder !== 0) {
91
+ await writeChunk(stream, ZERO_CHUNK.subarray(0, NARRATION_BYTES_PER_SAMPLE - remainder));
92
+ }
93
+ writtenSamples += Math.ceil(writtenBytes / NARRATION_BYTES_PER_SAMPLE);
94
+ }
95
+ await new Promise((resolve, reject) => {
96
+ stream.once('error', reject);
97
+ stream.end(() => resolve());
98
+ });
99
+ }
100
+ catch (error) {
101
+ stream.destroy();
102
+ throw error;
103
+ }
104
+ }
8
105
  export async function assemble(schedule, speech, visual, directory, output, options = { verify_timing: false, output: defaultVideoOutput }) {
9
106
  const video = options.output;
10
107
  const licensed = options.licensed ?? configuredLicense();
@@ -52,7 +149,7 @@ export async function assemble(schedule, speech, visual, directory, output, opti
52
149
  const frameCount = Math.ceil(duration * video.fps - 1e-9);
53
150
  const annotations = annotationApplications(video, schedule, visual, audioOrigin);
54
151
  const renderer = annotations.length || schedule.overlays?.length || !licensed ? await import('./compositor.js') : undefined;
55
- const layers = await renderer?.frameLayers(video, schedule, licensed, options.inputHashes) ?? [];
152
+ const layers = await renderer?.frameLayers(video, schedule, options.inputHashes) ?? [];
56
153
  const { canvasLayers, staticTopLayers } = renderer ? renderer.splitFrameLayers(layers) : { canvasLayers: [], staticTopLayers: [] };
57
154
  const plan = renderer ? renderer.planCompositor(frameCount, video.fps, audioOrigin, annotations, canvasLayers) : { kind: 'none' };
58
155
  let layerImage;
@@ -60,62 +157,69 @@ export async function assemble(schedule, speech, visual, directory, output, opti
60
157
  layerImage = join(temporaryDirectory, 'overlays.png');
61
158
  await renderer.writeStaticFrameLayers(layerImage, video, staticTopLayers);
62
159
  }
160
+ let watermarkImage;
161
+ let watermarkRect;
162
+ if (!licensed) {
163
+ watermarkImage = join(temporaryDirectory, 'watermark.png');
164
+ watermarkRect = await renderer.writeWatermarkMask(watermarkImage, video);
165
+ }
166
+ const hasPostLayers = Boolean(layerImage || watermarkImage);
167
+ const stageOut = hasPostLayers ? 'stage_v' : 'v';
63
168
  let input = 1;
64
169
  switch (plan.kind) {
65
170
  case 'none':
66
171
  args.push('-i', visual.file);
67
- if (layerImage) {
68
- args.push('-i', layerImage);
69
- filters.push(`[0:v]${baseFilter}[base]`, '[base][1:v]overlay=eof_action=repeat,format=yuv420p[v]');
70
- input = 2;
71
- }
72
- else {
73
- filters.push(`[0:v]${baseFilter}[v]`);
74
- input = 1;
75
- }
172
+ filters.push(`[0:v]${baseFilter}[${stageOut}]`);
173
+ input = 1;
76
174
  break;
77
175
  case 'sparse':
78
176
  args.push('-i', visual.file);
79
177
  args.push('-f', 'rawvideo', '-pixel_format', 'rgba', '-video_size', `${video.width}x${video.height}`, '-framerate', String(video.fps), '-i', 'pipe:0');
80
- if (layerImage) {
81
- args.push('-i', layerImage);
82
- filters.push(`[0:v]${baseFilter}[base]`, `[1:v]setpts='${plan.ptsExpr}'[comp_in]`, `[base][comp_in]overlay=eof_action=pass:format=rgb:enable='${plan.betweenExpr}'[comp]`, '[comp][2:v]overlay=eof_action=repeat,format=yuv420p[v]');
83
- input = 3;
84
- }
85
- else {
86
- filters.push(`[0:v]${baseFilter}[base]`, `[1:v]setpts='${plan.ptsExpr}'[comp_in]`, `[base][comp_in]overlay=eof_action=pass:format=rgb:enable='${plan.betweenExpr}',format=yuv420p[v]`);
87
- input = 2;
88
- }
178
+ filters.push(`[0:v]${baseFilter}[base]`, `[1:v]setpts='${plan.ptsExpr}'[comp_in]`, `[base][comp_in]overlay=eof_action=pass:format=rgb:enable='${plan.betweenExpr}',format=yuv420p[${stageOut}]`);
179
+ input = 2;
89
180
  break;
90
181
  case 'full':
91
182
  args.push('-f', 'rawvideo', '-pixel_format', 'rgba', '-video_size', `${video.width}x${video.height}`, '-framerate', String(video.fps), '-i', 'pipe:0');
92
- if (layerImage) {
93
- args.push('-i', layerImage);
94
- filters.push('[0:v]format=yuv420p[base]', '[base][1:v]overlay=eof_action=repeat,format=yuv420p[v]');
95
- input = 2;
96
- }
97
- else {
98
- filters.push('[0:v]format=yuv420p[v]');
99
- input = 1;
100
- }
183
+ filters.push(`[0:v]format=yuv420p[${stageOut}]`);
184
+ input = 1;
101
185
  break;
102
186
  default: {
103
187
  const _exhaustive = plan;
104
188
  throw new Error(`Unhandled compositor plan: ${String(_exhaustive)}`);
105
189
  }
106
190
  }
191
+ let currentStream = stageOut;
192
+ if (layerImage) {
193
+ args.push('-i', layerImage);
194
+ const nextStream = watermarkImage ? 'topped_v' : 'v';
195
+ filters.push(`[${currentStream}][${input}:v]overlay=eof_action=repeat,format=yuv420p[${nextStream}]`);
196
+ currentStream = nextStream;
197
+ input++;
198
+ }
199
+ if (watermarkImage && watermarkRect) {
200
+ args.push('-i', watermarkImage);
201
+ filters.push(...renderer.watermarkFilters(currentStream, input, 'v', watermarkRect));
202
+ input++;
203
+ }
107
204
  if (annotations.length)
108
205
  await saveJson(join(directory, 'annotations-applied.json'), { version: 1, annotations });
206
+ const narrationItems = [];
109
207
  for (const item of schedule.actions) {
110
208
  if (item.action.type === 'speak') {
111
209
  const segment = item.action.segment;
112
210
  const asset = speech.assets.find(a => a.id === segment);
113
- args.push('-i', asset.audio);
114
- filters.push(`[${input}:a]atrim=duration=${asset.duration_ms / 1000},asetpts=PTS-STARTPTS,adelay=${item.start_ms + audioOrigin}:all=1[a${input}]`);
115
- tracks.push(`[a${input}]`);
211
+ narrationItems.push({ item, asset });
116
212
  transformations.push({ id: item.id, kind: 'narration', start_ms: item.start_ms, duration_ms: asset.duration_ms });
117
- input++;
118
213
  }
214
+ }
215
+ if (narrationItems.length) {
216
+ const narrationPath = join(temporaryDirectory, 'narration.pcm');
217
+ await writeNarrationTrack(narrationPath, narrationItems, audioOrigin);
218
+ args.push('-f', 'f32le', '-ar', String(NARRATION_SAMPLE_RATE), '-ac', String(NARRATION_CHANNELS), '-i', narrationPath);
219
+ tracks.push(`[${input}:a]`);
220
+ input++;
221
+ }
222
+ for (const item of schedule.actions) {
119
223
  if (item.action.type === 'play' && item.action.audio === 'source') {
120
224
  const action = item.action;
121
225
  const media = schedule.media.find(m => m.id === action.media);
@@ -126,7 +230,9 @@ export async function assemble(schedule, speech, visual, directory, output, opti
126
230
  input++;
127
231
  }
128
232
  }
129
- if (tracks.length)
233
+ if (tracks.length === 1)
234
+ filters.push(`${tracks[0]}apad,atrim=duration=${duration}[a]`);
235
+ else if (tracks.length > 1)
130
236
  filters.push(`${tracks.join('')}amix=inputs=${tracks.length}:normalize=0,apad,atrim=duration=${duration}[a]`);
131
237
  const filterScript = join(temporaryDirectory, 'filter-complex.txt');
132
238
  await writeFile(filterScript, filters.join(';'));
@@ -152,7 +258,7 @@ export async function assemble(schedule, speech, visual, directory, output, opti
152
258
  let annotationEvidence;
153
259
  if (annotations.length && options.verify_timing) {
154
260
  try {
155
- annotationEvidence = await verifyAnnotations(temporary, visual.file, baseFilter, annotations, video, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, video.fps, audioOrigin), outputSha256);
261
+ annotationEvidence = await verifyAnnotations(temporary, visual.file, baseFilter, annotations, video, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, video.fps, audioOrigin, watermarkRect), outputSha256);
156
262
  }
157
263
  catch (error) {
158
264
  await copyFile(temporary, join(directory, 'failed-composite.mp4'));
@@ -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
+ }