@slidevideo/cli 0.3.1 → 0.9.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.
package/dist/cli.js CHANGED
@@ -104,7 +104,13 @@ try {
104
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
106
  command = positionals[0] ?? 'help';
107
- notifyUpdate(Boolean(values.json), Boolean(values.quiet));
107
+ const skipUpdateCheck = Boolean(values.version || values.help)
108
+ || ['help', 'license', 'impressum'].includes(command)
109
+ || (command === 'setup' && Boolean(values.manual))
110
+ || (command === 'skill' && !values.install);
111
+ if (!skipUpdateCheck) {
112
+ notifyUpdate(Boolean(values.json), Boolean(values.quiet));
113
+ }
108
114
  if (values.version) {
109
115
  const { version } = JSON.parse(await readFile(packagePath('package.json'), 'utf8'));
110
116
  console.log(values.json ? JSON.stringify({ version: 1, package_version: version }) : version);
@@ -284,9 +290,20 @@ impressum displays the provider's contact details.
284
290
  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');
285
291
  const port = Number(values.port ?? 0);
286
292
  requireCondition(values.port === undefined || /^\d+$/.test(values.port) && Number.isInteger(port) && port <= 65535, 'PREVIEW_PORT', '--port must be between 0 and 65535');
287
- await servePreview(values.storyboard, cache, port, viewport, (url, approximate) => {
293
+ await servePreview(values.storyboard, cache, port, viewport, (url, approximate, approximateCues) => {
288
294
  previewReady = true;
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.`);
295
+ if (values.json) {
296
+ console.log(JSON.stringify({ version: 1, command, status: 'ready', url, approximate, approximate_cues: approximateCues, timing_status: 'not_evaluated' }));
297
+ }
298
+ else {
299
+ console.log(`Open ${url} to preview the storyboard. Press Ctrl+C to stop.`);
300
+ if (approximate.length) {
301
+ const cueNote = approximateCues.length
302
+ ? `; approximate phrase cues (not synthesized alignment): ${approximateCues.join(', ')}. Run tts or build for synthesized alignment.`
303
+ : '.';
304
+ console.log(`Estimated timing (150 words/min, uncached speech): ${approximate.join(', ')}${cueNote}`);
305
+ }
306
+ }
290
307
  });
291
308
  }
292
309
  else {
@@ -30,9 +30,24 @@ export type CompositorPlan = {
30
30
  selectedReadbackFrames: number;
31
31
  canvasLayers: FrameLayer[];
32
32
  };
33
- export declare function frameLayers(output: VideoOutput, schedule: Schedule, licensed: boolean, hashes?: Record<string, string>): Promise<FrameLayer[]>;
33
+ export type WatermarkLayout = {
34
+ text: string;
35
+ font: string;
36
+ textX: number;
37
+ textY: number;
38
+ maxTextWidth: number;
39
+ rectangle: Rectangle;
40
+ };
41
+ export declare function frameLayers(output: VideoOutput, schedule: Schedule, hashes?: Record<string, string>): Promise<FrameLayer[]>;
42
+ export declare function watermarkLayout(output: VideoOutput): WatermarkLayout;
43
+ export declare function renderWatermarkCanvas(output: VideoOutput, fillStyle?: string): {
44
+ canvas: Canvas;
45
+ layout: WatermarkLayout;
46
+ };
47
+ export declare function writeWatermarkMask(file: string, output: VideoOutput): Promise<Rectangle>;
48
+ export declare function watermarkFilters(inputStream: string, maskInput: number, outputStream: string, rectangle: Rectangle): string[];
34
49
  export declare function writeStaticFrameLayers(file: string, output: VideoOutput, layers: FrameLayer[]): Promise<void>;
35
- export declare function visibleFrameLayerBounds(layers: FrameLayer[], frame: number, fps: number, audioOrigin: number): Rectangle[];
50
+ export declare function visibleFrameLayerBounds(layers: FrameLayer[], frame: number, fps: number, audioOrigin: number, extraRectangle?: Rectangle): Rectangle[];
36
51
  export declare function splitFrameLayers(layers: FrameLayer[]): {
37
52
  canvasLayers: FrameLayer[];
38
53
  staticTopLayers: FrameLayer[];
@@ -8,7 +8,7 @@ import { executable } from './executables.js';
8
8
  import { ProductionError, requireCondition } from './errors.js';
9
9
  import { loadOverlayImage } from './overlay-assets.js';
10
10
  import { ensureStampFonts } from './stamp-fonts.js';
11
- export async function frameLayers(output, schedule, licensed, hashes) {
11
+ export async function frameLayers(output, schedule, hashes) {
12
12
  const layers = [];
13
13
  const images = new Map();
14
14
  for (const overlay of schedule.overlays ?? []) {
@@ -37,30 +37,61 @@ export async function frameLayers(output, schedule, licensed, hashes) {
37
37
  };
38
38
  layers.push({ image, rectangle, opacity: overlay.opacity, opacityAt });
39
39
  }
40
- if (!licensed)
41
- layers.push(watermark(output));
42
40
  return layers;
43
41
  }
44
- function watermark(output) {
42
+ export function watermarkLayout(output) {
43
+ ensureStampFonts();
45
44
  const text = 'slidevideo.io';
46
- const size = Math.max(1, Math.round(output.height * 0.024));
47
- const margin = Math.max(1, Math.round(Math.min(output.width, output.height) * 0.018));
48
- const width = Math.max(1, Math.min(Math.ceil(size * 8), output.width - margin));
49
- const height = Math.max(1, Math.min(Math.ceil(size * 1.5), output.height - margin));
50
- const image = createCanvas(width, height);
51
- const context = image.getContext('2d');
52
- context.font = `600 ${size}px sans-serif`;
45
+ const fontSize = Math.max(1, Math.round(output.height * 0.0204));
46
+ const font = `700 ${fontSize}px SlideVideoSans`;
47
+ const measure = createCanvas(16, 16).getContext('2d');
48
+ measure.font = font;
49
+ const metrics = measure.measureText(text);
50
+ const ascent = Math.ceil(metrics.actualBoundingBoxAscent || fontSize * 0.78);
51
+ const descent = Math.ceil(metrics.actualBoundingBoxDescent || 0);
52
+ const pad = Math.max(1, Math.min(4, Math.floor(Math.min(output.width, output.height) * 0.05)));
53
+ const marginX = Math.max(1, Math.min(Math.max(1, Math.floor(output.width * 0.1)), Math.round(Math.min(output.width, output.height) * 0.0204)));
54
+ const marginY = Math.max(1, Math.min(Math.max(1, Math.floor(output.height * 0.1)), Math.round(Math.min(output.width, output.height) * 0.0185)));
55
+ const maxWidth = Math.max(1, output.width - marginX);
56
+ const maxHeight = Math.max(1, output.height - marginY);
57
+ const rawWidth = Math.min(Math.ceil(metrics.width) + pad * 2, maxWidth);
58
+ const rawHeight = Math.min(ascent + descent + pad * 2, maxHeight);
59
+ const width = rawWidth % 2 === 1 && rawWidth + 1 <= maxWidth ? rawWidth + 1 : rawWidth;
60
+ const height = rawHeight % 2 === 1 && rawHeight + 1 <= maxHeight ? rawHeight + 1 : rawHeight;
61
+ const rawX = Math.max(0, Math.min(output.width - width, output.width - marginX - width + pad));
62
+ const rawY = Math.max(0, Math.min(output.height - height, output.height - marginY - height + pad + descent));
63
+ const x = rawX % 2 === 1 && rawX > 0 ? rawX - 1 : rawX;
64
+ const y = rawY % 2 === 1 && rawY > 0 ? rawY - 1 : rawY;
65
+ const textX = Math.max(1, width - pad);
66
+ const textY = Math.max(1, height - pad - descent);
67
+ const maxTextWidth = Math.max(1, width - Math.min(pad * 2, width - 1));
68
+ return { text, font, textX, textY, maxTextWidth, rectangle: { x, y, width, height } };
69
+ }
70
+ export function renderWatermarkCanvas(output, fillStyle = 'rgba(255, 255, 255, 0.28)') {
71
+ const layout = watermarkLayout(output);
72
+ const canvas = createCanvas(layout.rectangle.width, layout.rectangle.height);
73
+ const context = canvas.getContext('2d');
74
+ context.font = layout.font;
53
75
  context.textAlign = 'right';
54
- context.textBaseline = 'middle';
55
- context.lineJoin = 'round';
56
- context.lineWidth = Math.max(1, size * 0.1);
57
- context.strokeStyle = '#222222';
58
- context.fillStyle = '#ffffff';
59
- const x = Math.max(0, width - Math.ceil(context.lineWidth));
60
- const maxWidth = Math.max(1, width - 2 * Math.ceil(context.lineWidth));
61
- context.strokeText(text, x, height / 2, maxWidth);
62
- context.fillText(text, x, height / 2, maxWidth);
63
- return { image, opacity: 0.5, rectangle: { x: output.width - margin - width, y: output.height - margin - height, width, height } };
76
+ context.textBaseline = 'alphabetic';
77
+ context.fillStyle = fillStyle;
78
+ context.fillText(layout.text, layout.textX, layout.textY, layout.maxTextWidth);
79
+ return { canvas, layout };
80
+ }
81
+ export async function writeWatermarkMask(file, output) {
82
+ const { canvas, layout } = renderWatermarkCanvas(output);
83
+ await writeFile(file, canvas.toBuffer('image/png'));
84
+ return layout.rectangle;
85
+ }
86
+ export function watermarkFilters(inputStream, maskInput, outputStream, rectangle) {
87
+ const { x, y, width, height } = rectangle;
88
+ return [
89
+ `[${inputStream}]split[wm_bg][wm_probe]`,
90
+ `[wm_probe]crop=${width}:${height}:${x}:${y},format=gray,scale=1:1:flags=area,format=rgb24,lutrgb=r='if(gte(val,116),20,236)':g='if(gte(val,116),28,242)':b='if(gte(val,116),36,248)',scale=${width}:${height}:flags=neighbor[wm_ink]`,
91
+ `[${maskInput}:v]alphaextract[wm_alpha]`,
92
+ '[wm_ink][wm_alpha]alphamerge[wm_patch]',
93
+ `[wm_bg][wm_patch]overlay=x=${x}:y=${y}:eof_action=repeat,format=yuv420p[${outputStream}]`,
94
+ ];
64
95
  }
65
96
  function paintFrameLayers(context, layers, time) {
66
97
  for (const layer of layers) {
@@ -78,9 +109,12 @@ export async function writeStaticFrameLayers(file, output, layers) {
78
109
  paintFrameLayers(canvas.getContext('2d'), layers, 0);
79
110
  await writeFile(file, canvas.toBuffer('image/png'));
80
111
  }
81
- export function visibleFrameLayerBounds(layers, frame, fps, audioOrigin) {
112
+ export function visibleFrameLayerBounds(layers, frame, fps, audioOrigin, extraRectangle) {
82
113
  const time = Math.max(0, frame * 1000 / fps - audioOrigin);
83
- return layers.filter(layer => (layer.opacityAt?.(time) ?? layer.opacity) > 0).map(layer => layer.rectangle);
114
+ const bounds = layers.filter(layer => (layer.opacityAt?.(time) ?? layer.opacity) > 0).map(layer => layer.rectangle);
115
+ if (extraRectangle)
116
+ bounds.push(extraRectangle);
117
+ return bounds;
84
118
  }
85
119
  function completion(child, operation) {
86
120
  let diagnostic = '';
@@ -338,7 +338,64 @@ export type StampAnnotationBase = {
338
338
  motion?: StampMotion;
339
339
  };
340
340
  export type StampAnnotation = StampAnnotationBase & AnnotationTiming;
341
- export type Annotation = HighlightAnnotation | UnderlineAnnotation | SpotlightAnnotation | ZoomAnnotation | LaserAnnotation | StampAnnotation;
341
+ export type ConnectorEndpoint = {
342
+ x: number;
343
+ y: number;
344
+ padding?: number;
345
+ } | {
346
+ target: AnnotationTarget;
347
+ anchor: TargetAnchor;
348
+ padding?: number;
349
+ };
350
+ export type ResolvedConnectorEndpoint = {
351
+ x: number;
352
+ y: number;
353
+ padding?: number;
354
+ } | {
355
+ target: ResolvedAnnotationTarget;
356
+ anchor: TargetAnchor;
357
+ padding?: number;
358
+ };
359
+ export type ConnectorTarget = {
360
+ type: 'connector';
361
+ units: 'normalized';
362
+ from: ConnectorEndpoint;
363
+ to: ConnectorEndpoint;
364
+ };
365
+ export type ResolvedConnectorTarget = {
366
+ type: 'connector';
367
+ units: 'normalized';
368
+ from: ResolvedConnectorEndpoint;
369
+ to: ResolvedConnectorEndpoint;
370
+ };
371
+ export type ArrowHead = 'filled' | 'open';
372
+ export type ArrowAppearance = {
373
+ color?: string;
374
+ opacity?: number;
375
+ width?: number;
376
+ style?: 'solid' | 'dashed';
377
+ head?: ArrowHead;
378
+ head_size?: number;
379
+ };
380
+ export type ArrowMotion = {
381
+ type: 'fade';
382
+ in_ms?: number;
383
+ out_ms?: number;
384
+ } | {
385
+ type: 'draw';
386
+ in_ms?: number;
387
+ out_ms?: number;
388
+ };
389
+ export type ArrowAnnotationBase = {
390
+ id: string;
391
+ scene: string;
392
+ effect: 'arrow';
393
+ target: ConnectorTarget;
394
+ appearance?: ArrowAppearance;
395
+ motion?: ArrowMotion;
396
+ };
397
+ export type ArrowAnnotation = ArrowAnnotationBase & AnnotationTiming;
398
+ export type Annotation = HighlightAnnotation | UnderlineAnnotation | SpotlightAnnotation | ZoomAnnotation | LaserAnnotation | StampAnnotation | ArrowAnnotation;
342
399
  export type ResolvedAnnotationWindow = {
343
400
  start_ms: number;
344
401
  end_ms: number;
@@ -371,7 +428,10 @@ export type ResolvedLaserAnnotation = Omit<LaserAnnotationBase, 'target'> & {
371
428
  export type ResolvedStampAnnotation = Omit<StampAnnotationBase, 'target'> & {
372
429
  target: ResolvedStampTarget;
373
430
  } & ResolvedAnnotationWindow;
374
- export type ResolvedAnnotation = ResolvedHighlightAnnotation | ResolvedUnderlineAnnotation | ResolvedSpotlightAnnotation | ResolvedZoomAnnotation | ResolvedLaserAnnotation | ResolvedStampAnnotation;
431
+ export type ResolvedArrowAnnotation = Omit<ArrowAnnotationBase, 'target'> & {
432
+ target: ResolvedConnectorTarget;
433
+ } & ResolvedAnnotationWindow;
434
+ export type ResolvedAnnotation = ResolvedHighlightAnnotation | ResolvedUnderlineAnnotation | ResolvedSpotlightAnnotation | ResolvedZoomAnnotation | ResolvedLaserAnnotation | ResolvedStampAnnotation | ResolvedArrowAnnotation;
375
435
  export type GeometryRequest = {
376
436
  key: string;
377
437
  target: GeometryTarget;
@@ -585,6 +645,7 @@ export type VisualArtifact = {
585
645
  export interface TtsAdapter {
586
646
  id: string;
587
647
  version: string;
648
+ readonly concurrency?: number;
588
649
  validate(voice: Voice): void;
589
650
  synthesize(segment: Narration, voice: Voice, destination: string): Promise<Omit<SpeechAsset, 'key'>>;
590
651
  }
package/dist/media.js CHANGED
@@ -92,7 +92,30 @@ export function ffmpegFilterScriptFlags(ffmpegPath = executable('ffmpeg')) {
92
92
  }
93
93
  return cached;
94
94
  }
95
- export async function audioDuration(path) { const pcm = await execute('ffmpeg', ['-v', 'error', '-i', path, '-vn', '-ac', '1', '-ar', '48000', '-f', 's16le', '-']); return pcm.length / 96; }
95
+ export async function audioDuration(path) {
96
+ const command = executable('ffmpeg');
97
+ const args = ['-v', 'error', '-xerror', '-i', path, '-vn', '-ac', '1', '-ar', '48000', '-f', 's16le', '-'];
98
+ return new Promise((resolve, reject) => {
99
+ const context = executionScope.getStore();
100
+ const signal = context?.signal;
101
+ signal?.throwIfAborted();
102
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], signal, killSignal: 'SIGKILL', windowsHide: true });
103
+ let bytes = 0;
104
+ const err = [];
105
+ const limit = context?.bounded ? undefined : 120000;
106
+ const timer = limit !== undefined ? setTimeout(() => { child.kill('SIGKILL'); }, limit) : undefined;
107
+ child.stdout.on('data', (data) => { bytes += data.length; });
108
+ child.stderr.on('data', (data) => err.push(data));
109
+ child.on('error', error => { clearTimeout(timer); reject(new ProductionError('DEPENDENCY', `${command}: ${error.message}`, 3)); });
110
+ child.on('close', code => {
111
+ clearTimeout(timer);
112
+ if (code !== 0)
113
+ reject(new ProductionError('SUBPROCESS', `${command} exited ${code}: ${Buffer.concat(err).toString().slice(-4000)}`, 3));
114
+ else
115
+ resolve(bytes / 96);
116
+ });
117
+ });
118
+ }
96
119
  export async function videoFramePeriod(path) {
97
120
  const data = JSON.parse((await execute('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_frames', '-show_entries', 'frame=best_effort_timestamp_time,duration_time', '-of', 'json', path])).toString());
98
121
  const frames = data.frames;
package/dist/pipeline.js CHANGED
@@ -213,8 +213,9 @@ export async function produce(options) {
213
213
  const visualPath = join(directory, 'recording/visual.json');
214
214
  const reportPath = join(directory, 'assembly/report.json');
215
215
  const resolveViewport = ['build', 'record', 'assemble'].includes(options.command) ? video : undefined;
216
+ const verifiedSpeech = new Map();
216
217
  const resolveSchedule = async () => {
217
- const schedule = await resolveTiming(story, await json(speechPath));
218
+ const schedule = await resolveTiming(story, await json(speechPath), verifiedSpeech);
218
219
  await adapter.validate(story, inspection, { ...(resolveViewport ? { viewport: resolveViewport } : {}), schedule });
219
220
  return schedule;
220
221
  };
@@ -290,7 +291,7 @@ export async function produce(options) {
290
291
  const prehashed = {};
291
292
  const operation = async () => {
292
293
  if (stage === 'tts') {
293
- const speech = await generateSpeech(story, join(directory, 'speech'), ttsAdapters, resolveSpeechCache(source, options.cache), options.progress);
294
+ const speech = await generateSpeech(story, join(directory, 'speech'), ttsAdapters, resolveSpeechCache(source, options.cache), options.progress, verifiedSpeech);
294
295
  artifacts.push(speechPath, ...speech.assets.map(asset => asset.audio));
295
296
  }
296
297
  if (stage === 'resolve') {
@@ -24,6 +24,7 @@ export type PlayerConfig = {
24
24
  width: number;
25
25
  height: number;
26
26
  approximate: string[];
27
+ approximate_cues: string[];
27
28
  scenes: PreviewScene[];
28
29
  audio: PreviewAudioCue[];
29
30
  stage: {
@@ -1,4 +1,4 @@
1
- import { activeViewTransform, annotationPaint, hasActiveSpotlight, laserPaint, laserVisible, paintEffects, spotlightAperturesVisible, stampPaint, stampVisible, targetKey, underlineFragmentsVisible, zoomTransformVisible } from '../annotation-paint.js';
1
+ import { activeViewTransform, annotationPaint, arrowPaint, arrowVisible, hasActiveSpotlight, laserPaint, laserVisible, paintEffects, spotlightAperturesVisible, stampPaint, stampVisible, targetKey, underlineFragmentsVisible, zoomTransformVisible } from '../annotation-paint.js';
2
2
  const labels = { loading: 'Loading presentation…', ready: 'Ready', playing: 'Playing', paused: 'Paused', ended: 'Finished', error: 'Playback failed' };
3
3
  const stage = document.querySelector('#stage');
4
4
  const status = document.querySelector('#status');
@@ -371,6 +371,14 @@ function nativePlayer(annotations) {
371
371
  activeEffects.push(painted);
372
372
  break;
373
373
  }
374
+ case 'arrow': {
375
+ const painted = arrowPaint(marker, { viewport: frame.viewport, content: frame.content }, target => targets.get(targetKey(target)));
376
+ if (!arrowVisible(painted)) {
377
+ throw new Error(`Annotation ${marker.id}: ${painted.degenerate_reason ?? 'arrow is clipped outside the slide-content rectangle'}`);
378
+ }
379
+ activeEffects.push(painted);
380
+ break;
381
+ }
374
382
  }
375
383
  }
376
384
  const view = activeViewTransform(activeEffects, frame.position_ms);
@@ -566,7 +574,10 @@ try {
566
574
  timeline.setAttribute('aria-valuemax', String(Math.round(durationMs)));
567
575
  if (config.approximate.length) {
568
576
  const pacing = document.getElementById('pacing');
569
- pacing.textContent = `Estimated narration timing (150 words/min): ${config.approximate.join(', ')}`;
577
+ const cues = config.approximate_cues ?? [];
578
+ pacing.textContent = cues.length
579
+ ? `Estimated preview timing (150 words/min, uncached): ${config.approximate.join(', ')} · Approximate phrase cues (not synthesized alignment): ${cues.join(', ')}`
580
+ : `Estimated narration timing (150 words/min): ${config.approximate.join(', ')}`;
570
581
  pacing.hidden = false;
571
582
  }
572
583
  audioSync = createAudioSync(config.audio ?? []);
@@ -1,2 +1,2 @@
1
1
  import { type Viewport } from '../contracts.js';
2
- export declare function servePreview(storyboard: string, cache: string | false | undefined, port: number, viewport: Viewport | undefined, ready: (url: string, approximate: string[]) => void): Promise<void>;
2
+ export declare function servePreview(storyboard: string, cache: string | false | undefined, port: number, viewport: Viewport | undefined, ready: (url: string, approximate: string[], approximateCues: string[]) => void): Promise<void>;
@@ -163,7 +163,7 @@ export async function servePreview(storyboard, cache, port, viewport = defaultVi
163
163
  requireCondition(adapter.startPreview, 'PREVIEW_CAPABILITY', `Adapter ${adapter.id} does not support preview`, 3);
164
164
  const inspection = await adapter.inspect(story.deck);
165
165
  await adapter.validate(story, inspection, { viewport });
166
- const { schedule, approximate, audio: verifiedAudio } = await resolvePreviewTiming(story, ttsAdapters, resolveSpeechCache(source, cache));
166
+ const { schedule, approximate, approximateCues, audio: verifiedAudio } = await resolvePreviewTiming(story, ttsAdapters, resolveSpeechCache(source, cache));
167
167
  audioFiles = verifiedAudio;
168
168
  await adapter.validate(story, inspection, { viewport, schedule });
169
169
  controller.signal.throwIfAborted();
@@ -201,9 +201,9 @@ export async function servePreview(storyboard, cache, port, viewport = defaultVi
201
201
  }
202
202
  }
203
203
  config = { deck: basename(story.deck), width: viewport.width, height: viewport.height,
204
- duration: schedule.duration_ms, approximate, scenes, audio,
204
+ duration: schedule.duration_ms, approximate, approximate_cues: approximateCues, scenes, audio,
205
205
  stage: 'url' in session ? { url: session.url } : { annotations: schedule.annotations } };
206
- ready(origin, approximate);
206
+ ready(origin, approximate, approximateCues);
207
207
  await new Promise(resolve => controller.signal.addEventListener('abort', () => resolve(), { once: true }));
208
208
  });
209
209
  }
package/dist/speech.d.ts CHANGED
@@ -11,5 +11,6 @@ export type RetainedSpeech = {
11
11
  audio?: VerifiedSpeechAudio;
12
12
  };
13
13
  export declare function retainedSpeechTiming(segment: Narration, voice: Voice, adapter: TtsAdapter, cache?: string): Promise<RetainedSpeech | undefined>;
14
- export declare function checkSpeech(asset: SpeechAsset): Promise<void>;
15
- export declare function generateSpeech(story: Storyboard, directory: string, adapters: Map<string, TtsAdapter>, cache?: string, progress?: ProgressReporter): Promise<SpeechManifest>;
14
+ export type VerifiedSpeech = Map<string, number>;
15
+ export declare function checkSpeech(asset: SpeechAsset, verified?: VerifiedSpeech): Promise<void>;
16
+ export declare function generateSpeech(story: Storyboard, directory: string, adapters: Map<string, TtsAdapter>, cache?: string, progress?: ProgressReporter, verified?: VerifiedSpeech): Promise<SpeechManifest>;
package/dist/speech.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { mkdir, copyFile, readFile } from 'node:fs/promises';
2
2
  import { join, resolve, dirname } from 'node:path';
3
3
  import { Ajv } from 'ajv';
4
- import { digest, json, saveJson, probe, hashFile, decode, executionSignal, audioDuration } from './media.js';
4
+ import { digest, json, saveJson, probe, hashFile, executionScope, executionSignal, audioDuration } from './media.js';
5
5
  import { requireCondition, ProductionError } from './errors.js';
6
6
  const speechSchema = JSON.parse(await readFile(new URL('../schemas/speech.v1.json', import.meta.url), 'utf8'));
7
7
  const validateSpeech = new Ajv({ allErrors: true }).compile(speechSchema);
@@ -72,7 +72,7 @@ export async function retainedSpeechTiming(segment, voice, adapter, cache) {
72
72
  }
73
73
  return { timing: { id: segment.id, duration_ms: asset.duration_ms, transcript: asset.transcript, alignment: asset.alignment }, ...(audio ? { audio } : {}) };
74
74
  }
75
- export async function checkSpeech(asset) {
75
+ export async function checkSpeech(asset, verified) {
76
76
  requireCondition(/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(asset.format), 'SPEECH_FORMAT', `Invalid speech file format for ${asset.id}`);
77
77
  let hash;
78
78
  try {
@@ -82,63 +82,166 @@ export async function checkSpeech(asset) {
82
82
  throw new ProductionError('SPEECH_INPUT', `Cannot read speech audio for ${asset.id}: ${asset.audio}`);
83
83
  }
84
84
  requireCondition(hash === asset.sha256, 'SPEECH_INTEGRITY', `Speech asset changed: ${asset.id}`);
85
- const properties = await probe(asset.audio);
86
- requireCondition(properties.has_audio && properties.duration_ms > 0 && Math.abs(await audioDuration(asset.audio) - asset.duration_ms) < 1, 'SPEECH_DURATION', `Speech duration mismatch: ${asset.id}`);
85
+ const knownDuration = verified?.get(hash);
86
+ if (knownDuration !== undefined) {
87
+ requireCondition(Math.abs(knownDuration - asset.duration_ms) < 1, 'SPEECH_DURATION', `Speech duration mismatch: ${asset.id}`);
88
+ }
89
+ else {
90
+ const properties = await probe(asset.audio);
91
+ const durationMs = await audioDuration(asset.audio);
92
+ requireCondition(properties.has_audio && properties.duration_ms > 0 && Math.abs(durationMs - asset.duration_ms) < 1, 'SPEECH_DURATION', `Speech duration mismatch: ${asset.id}`);
93
+ verified?.set(hash, durationMs);
94
+ }
87
95
  checkAlignment(asset);
88
96
  }
89
- export async function generateSpeech(story, directory, adapters, cache, progress) {
97
+ class ConcurrencyLimiter {
98
+ limit;
99
+ active = 0;
100
+ queue = [];
101
+ constructor(limit) {
102
+ this.limit = limit;
103
+ }
104
+ async run(signal, fn) {
105
+ signal.throwIfAborted();
106
+ if (this.active >= this.limit) {
107
+ await new Promise((resolve, reject) => {
108
+ const onAbort = () => {
109
+ const index = this.queue.indexOf(release);
110
+ if (index >= 0)
111
+ this.queue.splice(index, 1);
112
+ reject(signal.reason);
113
+ };
114
+ const release = () => {
115
+ signal.removeEventListener('abort', onAbort);
116
+ resolve();
117
+ };
118
+ signal.addEventListener('abort', onAbort, { once: true });
119
+ this.queue.push(release);
120
+ });
121
+ }
122
+ signal.throwIfAborted();
123
+ this.active++;
124
+ try {
125
+ return await fn();
126
+ }
127
+ finally {
128
+ this.active--;
129
+ const next = this.queue.shift();
130
+ if (next)
131
+ next();
132
+ }
133
+ }
134
+ }
135
+ export async function generateSpeech(story, directory, adapters, cache, progress, verified) {
90
136
  await mkdir(directory, { recursive: true });
91
- const assets = [];
92
- progress?.(`Speech: ${story.narration.length} segments`);
93
- for (const segment of story.narration) {
94
- executionSignal()?.throwIfAborted();
137
+ const total = story.narration.length;
138
+ const assets = new Array(total);
139
+ progress?.(`Speech: ${total} segments`);
140
+ const prepared = story.narration.map((segment, index) => {
95
141
  const voice = segment.voice ?? story.voice;
96
142
  requireCondition(voice, 'VOICE_REQUIRED', `Narration ${segment.id} needs a voice`);
97
143
  const adapter = adapters.get(voice.provider);
98
144
  requireCondition(adapter, 'TTS_ADAPTER', `Unsupported TTS provider ${voice.provider}`, 3);
99
145
  adapter.validate(voice);
100
146
  const key = speechKey(segment, voice, adapter);
101
- let asset;
102
147
  const cached = cache ? join(resolve(cache), `${key}.json`) : undefined;
103
- if (cached) {
104
- let entry;
148
+ return { index, segment, voice, adapter, key, cached };
149
+ });
150
+ const parentScope = executionScope.getStore();
151
+ parentScope?.signal.throwIfAborted();
152
+ const local = new AbortController();
153
+ const onParentAbort = () => local.abort(parentScope.signal.reason);
154
+ parentScope?.signal.addEventListener('abort', onParentAbort, { once: true });
155
+ const providerLimiters = new Map();
156
+ const limiterFor = (adapter) => {
157
+ let limiter = providerLimiters.get(adapter.id);
158
+ if (!limiter) {
159
+ limiter = new ConcurrencyLimiter(Math.max(1, adapter.concurrency ?? 2));
160
+ providerLimiters.set(adapter.id, limiter);
161
+ }
162
+ return limiter;
163
+ };
164
+ const cacheLimiter = new ConcurrencyLimiter(4);
165
+ const inFlightByKey = new Map();
166
+ let started = 0;
167
+ let firstError;
168
+ const recordError = (error) => {
169
+ if (firstError === undefined)
170
+ firstError = error;
171
+ if (!local.signal.aborted)
172
+ local.abort(error);
173
+ };
174
+ try {
175
+ const tasks = prepared.map(({ index, segment, voice, adapter, key, cached }) => executionScope.run({ signal: local.signal, bounded: parentScope?.bounded ?? false }, async () => {
105
176
  try {
106
- entry = await json(cached);
177
+ local.signal.throwIfAborted();
178
+ let cachedAsset;
179
+ if (cached && !inFlightByKey.has(key)) {
180
+ let entry;
181
+ try {
182
+ entry = await json(cached);
183
+ }
184
+ catch (error) {
185
+ if (error.code !== 'ENOENT')
186
+ throw new ProductionError('CACHE_INPUT', `Cannot read speech cache entry ${cached}`);
187
+ }
188
+ if (entry !== undefined) {
189
+ const manifest = { version: 1, assets: [entry] };
190
+ requireCondition(validateSpeech(manifest), 'CACHE_INPUT', `Invalid speech cache entry for ${segment.id}: ${cached}`);
191
+ cachedAsset = manifest.assets[0];
192
+ }
193
+ }
194
+ if (cachedAsset) {
195
+ const asset = await cacheLimiter.run(local.signal, async () => {
196
+ progress?.(`Reusing cached speech ${segment.id} (${++started}/${total})`);
197
+ const resolvedAudio = resolve(dirname(cached), cachedAsset.audio);
198
+ const candidate = { ...cachedAsset, audio: resolvedAudio };
199
+ requireCondition(matchesSpeechCache(candidate, segment, voice, adapter), 'CACHE_MISMATCH', `Cache does not match ${segment.id}`);
200
+ await checkSpeech(candidate, verified);
201
+ const destination = speechPath(directory, segment.id, candidate.format);
202
+ await copyFile(candidate.audio, destination);
203
+ return { ...candidate, id: segment.id, audio: destination };
204
+ });
205
+ assets[index] = asset;
206
+ return;
207
+ }
208
+ const existing = inFlightByKey.get(key);
209
+ if (existing) {
210
+ const source = await existing;
211
+ local.signal.throwIfAborted();
212
+ const destination = speechPath(directory, segment.id, source.format);
213
+ await copyFile(source.audio, destination);
214
+ assets[index] = { ...source, id: segment.id, audio: destination };
215
+ return;
216
+ }
217
+ const synthPromise = limiterFor(adapter).run(local.signal, async () => {
218
+ progress?.(`Generating speech ${segment.id} (${++started}/${total})`);
219
+ const generated = await adapter.synthesize(segment, voice, speechPath(directory, segment.id, 'mp3'));
220
+ const asset = { ...generated, key };
221
+ await checkSpeech(asset, verified);
222
+ if (cached) {
223
+ const cachedAudio = speechPath(resolve(cache), key, asset.format);
224
+ await mkdir(resolve(cache), { recursive: true });
225
+ await copyFile(asset.audio, cachedAudio);
226
+ await saveJson(cached, { ...asset, audio: `${key}.${asset.format}` });
227
+ }
228
+ return asset;
229
+ });
230
+ inFlightByKey.set(key, synthPromise);
231
+ assets[index] = await synthPromise;
107
232
  }
108
233
  catch (error) {
109
- if (error.code !== 'ENOENT')
110
- throw new ProductionError('CACHE_INPUT', `Cannot read speech cache entry ${cached}`);
111
- }
112
- if (entry !== undefined) {
113
- const manifest = { version: 1, assets: [entry] };
114
- requireCondition(validateSpeech(manifest), 'CACHE_INPUT', `Invalid speech cache entry for ${segment.id}: ${cached}`);
115
- asset = manifest.assets[0];
116
- }
117
- }
118
- if (asset) {
119
- progress?.(`Reusing cached speech ${segment.id} (${assets.length + 1}/${story.narration.length})`);
120
- asset.audio = resolve(dirname(cached), asset.audio);
121
- requireCondition(matchesSpeechCache(asset, segment, voice, adapter), 'CACHE_MISMATCH', `Cache does not match ${segment.id}`);
122
- await checkSpeech(asset);
123
- await decode(asset.audio);
124
- const destination = speechPath(directory, segment.id, asset.format);
125
- await copyFile(asset.audio, destination);
126
- asset = { ...asset, id: segment.id, audio: destination };
127
- }
128
- else {
129
- progress?.(`Generating speech ${segment.id} (${assets.length + 1}/${story.narration.length})`);
130
- const generated = await adapter.synthesize(segment, voice, speechPath(directory, segment.id, 'mp3'));
131
- asset = { ...generated, key };
132
- await checkSpeech(asset);
133
- if (cached) {
134
- const cachedAudio = speechPath(resolve(cache), key, asset.format);
135
- await mkdir(resolve(cache), { recursive: true });
136
- await copyFile(asset.audio, cachedAudio);
137
- await saveJson(cached, { ...asset, audio: `${key}.${asset.format}` });
234
+ recordError(error);
138
235
  }
139
- }
140
- assets.push(asset);
236
+ }));
237
+ await Promise.allSettled(tasks);
238
+ }
239
+ finally {
240
+ parentScope?.signal.removeEventListener('abort', onParentAbort);
141
241
  }
242
+ if (firstError !== undefined)
243
+ throw firstError;
244
+ executionSignal()?.throwIfAborted();
142
245
  const manifest = { version: 1, assets };
143
246
  await saveJson(join(directory, 'manifest.json'), manifest);
144
247
  return manifest;
@@ -109,7 +109,23 @@ export async function loadStoryboard(file) {
109
109
  requireCondition(badChar === undefined, 'STAMP_GLYPH', `Annotation ${annotation.id}: character ${JSON.stringify(badChar)} is not supported by the bundled ${font} stamp font; use characters covered by the bundled font or appearance.symbol (check, cross, warning, star, info, arrow-right)`, 2, context);
110
110
  }
111
111
  }
112
- if ((annotation.effect === 'underline' || annotation.effect === 'spotlight' || annotation.effect === 'zoom' || annotation.effect === 'laser' || annotation.effect === 'stamp') && annotation.motion && 'duration_ms' in annotation && annotation.duration_ms !== undefined) {
112
+ if (annotation.effect === 'arrow') {
113
+ for (const [role, endpoint] of [['from', annotation.target.from], ['to', annotation.target.to]]) {
114
+ if ('target' in endpoint) {
115
+ if (endpoint.target.type === 'text') {
116
+ requireCondition(endpoint.target.text.trim().length > 0, 'ANNOTATION_TARGET', `Annotation ${annotation.id}: arrow ${role} text target cannot be empty or whitespace`, 2, context);
117
+ }
118
+ if (endpoint.target.type === 'region') {
119
+ const { x, y, width, height } = endpoint.target;
120
+ requireCondition(x + width <= 1 && y + height <= 1, 'ANNOTATION_BOUNDS', `Annotation ${annotation.id}: arrow ${role} region exceeds normalized slide bounds`, 2, context);
121
+ }
122
+ }
123
+ }
124
+ if (!('target' in annotation.target.from) && !('target' in annotation.target.to)) {
125
+ requireCondition(annotation.target.from.x !== annotation.target.to.x || annotation.target.from.y !== annotation.target.to.y, 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: arrow endpoints are coincident`, 2, context);
126
+ }
127
+ }
128
+ if ((annotation.effect === 'underline' || annotation.effect === 'spotlight' || annotation.effect === 'zoom' || annotation.effect === 'laser' || annotation.effect === 'stamp' || annotation.effect === 'arrow') && annotation.motion && 'duration_ms' in annotation && annotation.duration_ms !== undefined) {
113
129
  const inMs = annotation.motion.in_ms ?? 0;
114
130
  const outMs = annotation.motion.out_ms ?? 0;
115
131
  requireCondition(inMs + outMs <= annotation.duration_ms, 'ANNOTATION_MOTION', `Annotation ${annotation.id}: ${annotation.motion.type} motion exceeds annotation duration`, 2, context);