@slidevideo/cli 0.10.0 → 0.11.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/CHANGELOG.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.11.0
6
+
7
+ - Support standalone MP4 scenes (`scenes[].media`) separate from `slides.md` or `.pptx`—including intro/outro branding bumpers with source audio stings, mid-deck or deck-free screen recordings, direct FFmpeg splicing with normalized annotations, and native playback in `slidevideo play`.
8
+ - Support video-anchored narration, reveals, and annotations (`at: { media, time_ms }`) with optional phrase-to-frame alignment, beat-mismatch policies (`continuous`, `freeze`, `fit_video`) on `play` actions, and live media timestamp readouts in `slidevideo play`.
9
+
5
10
  ## 0.10.0
6
11
 
7
12
  - Extract per-slide speaker notes in `slidevideo inspect` for both Slidev and PowerPoint decks.
@@ -101,6 +101,10 @@ function stopMedia(element: HTMLMediaElement, completed: boolean) {
101
101
  if (window.__slidevideoTimers) window.__slidevideoTimers.clearInternalInterval(monitor.timer)
102
102
  else window.clearInterval(monitor.timer)
103
103
  monitors.delete(element); element.pause()
104
+ if (completed && monitor.item.action.type === 'play' && monitor.item.action.trim_end_ms !== undefined) {
105
+ const endSeconds = monitor.item.action.trim_end_ms / 1000
106
+ if (Math.abs(element.currentTime - endSeconds) > 0.02) element.currentTime = endSeconds
107
+ }
104
108
  if (completed) state.events.push({ id: `${monitor.item.id}:ended`, type: 'media-ended', scheduled_ms: monitor.item.end_ms, observed_ms: scheduleNow(), media_ms: element.currentTime * 1000 })
105
109
  }
106
110
  const waits = new Map<number, () => void>()
@@ -156,7 +160,8 @@ async function apply(item: ScheduledAction) {
156
160
  if (action.type === 'play') {
157
161
  const element = media(action.media)
158
162
  stopMedia(element, true)
159
- element.currentTime = (action.trim_start_ms ?? 0) / 1000
163
+ const startSeconds = (action.trim_start_ms ?? 0) / 1000
164
+ if (Math.abs(element.currentTime - startSeconds) > 0.02) element.currentTime = startSeconds
160
165
  element.playbackRate = action.rate ?? 1
161
166
  element.muted = true
162
167
  await element.play()
@@ -446,13 +451,21 @@ async function play(verifyTiming = false, plannedSkips: StaticSkip[] = []) {
446
451
  origin = start
447
452
  const requests = geometryRequests(schedule)
448
453
  if (requests.length) geometry = geometryCollector(requests, state.annotation_geometry, () => ({ slide: String(nav.currentSlideRoute.value.meta.slide.frontmatter.name ?? `slide-${nav.currentSlideNo.value}`), visit, click: nav.clicks.value, index: nav.currentSlideNo.value }), () => scheduleNow(), message => { state.failure = message })
449
- for (const entry of playbackEntries(schedule)) {
454
+ const entries: (ReturnType<typeof playbackEntries>[number] | { at: number; order: number; type: 'media-end'; id: string })[] = playbackEntries(schedule)
455
+ for (const item of schedule.actions) if (item.action.type === 'play') entries.push({ at: item.end_ms, order: 0, type: 'media-end', id: item.action.media })
456
+ entries.sort((a, b) => a.at - b.at || a.order - b.order)
457
+ for (const entry of entries) {
450
458
  await waitUntilSchedule(entry.at, current, skips, skipCursor)
451
459
  if (current !== generation) throw new Error('Playback reset')
452
460
  if (state.failure) throw new Error(state.failure)
453
461
  if (entry.type === 'geometry-start') { geometry!.start(entry.request); continue }
454
462
  if (entry.type === 'geometry-end') { geometry!.end(entry.request); continue }
455
463
  if (entry.type === 'annotation-start' || entry.type === 'annotation-end') continue
464
+ if (entry.type === 'media-end') {
465
+ const element = document.getElementById(entry.id)
466
+ if (element instanceof HTMLMediaElement) stopMedia(element, true)
467
+ continue
468
+ }
456
469
  const item = entry.item
457
470
  await apply(item)
458
471
  const observed_ms = scheduleNow()
@@ -33,8 +33,8 @@ export function createPreview(
33
33
  const media = new Set<HTMLMediaElement>()
34
34
  const animations = new Set<Animation>()
35
35
  const allGeometryRequests = geometryRequests(schedule)
36
- const entries: (ReturnType<typeof playbackEntries>[number] | { at: number; order: number; type: 'media-end'; id: string })[] = playbackEntries(schedule)
37
- for (const item of schedule.actions) if (item.action.type === 'play') entries.push({ at: item.end_ms, order: 0, type: 'media-end', id: item.action.media })
36
+ const entries: (ReturnType<typeof playbackEntries>[number] | { at: number; order: number; type: 'media-end'; id: string; trimEndSeconds?: number })[] = playbackEntries(schedule)
37
+ for (const item of schedule.actions) if (item.action.type === 'play') entries.push({ at: item.end_ms, order: 0, type: 'media-end', id: item.action.media, trimEndSeconds: item.action.trim_end_ms !== undefined ? item.action.trim_end_ms / 1000 : undefined })
38
38
  entries.sort((a, b) => a.at - b.at || a.order - b.order)
39
39
 
40
40
  const elapsed = () => Math.min(schedule.duration_ms, status === 'playing' ? offset + performance.now() - origin : offset)
@@ -206,6 +206,7 @@ export function createPreview(
206
206
  const element = document.getElementById(clip.id)
207
207
  if (element instanceof HTMLMediaElement) element.pause()
208
208
  }
209
+ const activeMedia = new Set<string>()
209
210
  for (const item of schedule.actions) {
210
211
  if (item.action.type !== 'play') continue
211
212
  if (item.start_ms <= targetMs && targetMs < item.end_ms) {
@@ -217,11 +218,28 @@ export function createPreview(
217
218
  element.playbackRate = rate
218
219
  await seekMediaElement(element, mediaMs / 1000)
219
220
  media.add(element)
221
+ activeMedia.add(item.action.media)
220
222
  if (shouldPlay) await element.play()
221
223
  else element.pause()
222
224
  }
223
225
  }
224
226
  }
227
+ const frozenMedia = new Map<string, number>()
228
+ for (const item of schedule.actions) {
229
+ if (item.action.type !== 'play' || activeMedia.has(item.action.media)) continue
230
+ if (item.end_ms <= targetMs) {
231
+ const endMs = item.action.trim_end_ms ?? ((item.action.trim_start_ms ?? 0) + (item.end_ms - item.start_ms) * (item.action.rate ?? 1))
232
+ frozenMedia.set(item.action.media, endMs)
233
+ }
234
+ }
235
+ for (const [mediaId, endMs] of frozenMedia) {
236
+ const element = document.getElementById(mediaId)
237
+ if (element instanceof HTMLMediaElement) {
238
+ element.muted = true
239
+ element.pause()
240
+ await seekMediaElement(element, endMs / 1000)
241
+ }
242
+ }
225
243
  activateCollectorAt(targetMs, shouldPlay)
226
244
  }
227
245
  async function run(current: number, startIndex: number) {
@@ -236,7 +254,13 @@ export function createPreview(
236
254
  else if (entry.type === 'annotation-end') { active.delete(entry.annotation.id); paint() }
237
255
  else if (entry.type === 'media-end') {
238
256
  const element = document.getElementById(entry.id)
239
- if (element instanceof HTMLMediaElement) { element.pause(); media.delete(element) }
257
+ if (element instanceof HTMLMediaElement) {
258
+ element.pause()
259
+ if (entry.trimEndSeconds !== undefined && Math.abs(element.currentTime - entry.trimEndSeconds) > 0.02) {
260
+ element.currentTime = entry.trimEndSeconds
261
+ }
262
+ media.delete(element)
263
+ }
240
264
  } else {
241
265
  await apply(entry.item)
242
266
  if (current !== generation) return
@@ -5,6 +5,7 @@ import { extname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { nativePreview } from './powerpoint-preview.js';
7
7
  import { defaultVideoOutput, defaultViewport, normalizeSpeakerNotes } from '../contracts.js';
8
+ import { deckMediaIds, hasStandaloneMediaSchedule, isSlideScene, projectDeckSchedule, slideSceneCues } from '../standalone-media.js';
8
9
  import { geometryRequests } from '../annotation-paint.js';
9
10
  import { planStaticSkips, remapCaptureTimestamps } from './capture-compression.js';
10
11
  import { calibrate, estimateOrigin } from '../calibration.js';
@@ -428,7 +429,12 @@ export class PowerPointAdapter {
428
429
  }
429
430
  for (const media of deck.media)
430
431
  requireCondition(isSupportedNativeMedia(media), 'POWERPOINT_CAPABILITY', `Video ${media.id} requires full-source embedded media with no native trim, autoplay, loop, rewind or fullscreen transform`, 3);
432
+ const slideScenes = story.scenes.filter(isSlideScene);
433
+ const slideSceneIds = new Set(slideScenes.map(scene => scene.id));
434
+ const usedDeckMedia = deckMediaIds(story);
431
435
  for (const declaration of story.media) {
436
+ if (!usedDeckMedia.has(declaration.id))
437
+ continue;
432
438
  const candidates = deck.media.filter(media => media.id === declaration.id);
433
439
  requireCondition(candidates.length > 0, 'MEDIA_TARGET', `The native deck has no embedded video named ${declaration.id}`, 3);
434
440
  let hash;
@@ -440,19 +446,23 @@ export class PowerPointAdapter {
440
446
  }
441
447
  requireCondition(candidates.every(media => media.sha256 === hash), 'MEDIA_SOURCE_MISMATCH', `Storyboard media ${declaration.id} does not match the exact embedded video bytes in the deck`);
442
448
  }
443
- for (const scene of story.scenes)
449
+ for (const scene of slideScenes)
444
450
  this.slide(scene.slide);
445
- const actions = [...story.scenes.flatMap(scene => scene.actions), ...story.cues.map(cue => ({ ...cue.action, id: cue.id }))];
451
+ const actions = [...slideScenes.flatMap(scene => scene.actions), ...slideSceneCues(story).map(cue => ({ ...cue.action, id: cue.id }))];
446
452
  for (const action of actions) {
447
453
  if (action.type === 'slide') {
448
454
  const targetSlide = this.slide(action.target);
449
455
  const requiredSettle = slideEntrySettleMs(targetSlide);
450
456
  requireCondition(action.duration_ms + 0.1 >= requiredSettle, 'SLIDE_TRANSITION_DURATION', `Slide action ${action.id} must reserve at least ${requiredSettle} ms for ${targetSlide.id} transition and automatic entry animations`, 3);
451
457
  }
452
- if (action.type === 'play')
458
+ if (action.type === 'play') {
453
459
  requireCondition((action.rate ?? 1) === 1, 'POWERPOINT_CAPABILITY', `Video action ${action.id} requires playback rate 1 in native PowerPoint playback`, 3);
460
+ requireCondition((action.overflow ?? 'continuous') === 'continuous', 'POWERPOINT_CAPABILITY', `Video action ${action.id} uses overflow ${action.overflow}, which is not supported in native PowerPoint playback`, 3);
461
+ }
454
462
  }
455
463
  for (const annotation of story.annotations) {
464
+ if (!slideSceneIds.has(annotation.scene))
465
+ continue;
456
466
  const targets = annotation.target.type === 'path'
457
467
  ? annotation.target.points.flatMap(point => 'target' in point ? [point.target] : [])
458
468
  : annotation.target.type === 'connector'
@@ -463,64 +473,69 @@ export class PowerPointAdapter {
463
473
  }
464
474
  }
465
475
  if (schedule) {
466
- this.operations(story, schedule);
467
- for (const annotation of schedule.annotations) {
468
- const slide = this.slide(annotation.slide);
469
- const targets = annotation.target.type === 'path'
470
- ? annotation.target.points.flatMap(point => 'target' in point ? [point.target] : [])
471
- : annotation.target.type === 'connector'
472
- ? [annotation.target.from, annotation.target.to].flatMap(ep => 'target' in ep ? [ep.target] : [])
473
- : [annotation.target];
474
- for (const target of targets) {
475
- if (target.type === 'shape') {
476
- const candidates = slide.shapes.filter(shape => shape.id === target.id);
477
- requireCondition(candidates.length === 1, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: shape ${target.id} is missing or ambiguous`, 3);
478
- const shape = candidates[0];
479
- requireCondition(shape.unsupported.length === 0 && annotation.click >= shape.visible_from_click, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}, shape ${shape.id} (${shape.name}): ${shape.unsupported.join('; ') || `hidden until click ${shape.visible_from_click}`}`, 3);
480
- }
481
- if (target.type === 'text') {
482
- const needle = target.text.trim().replace(/\s+/g, ' ');
483
- let shapes;
484
- if (target.container) {
485
- requireCondition(target.container.type === 'shape', 'ANNOTATION_TARGET', `Annotation ${annotation.id}: PowerPoint text container requires a shape ID`, 3);
486
- const containerId = target.container.id;
487
- const candidates = slide.shapes.filter(shape => shape.id === containerId);
488
- requireCondition(candidates.length === 1, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: shape ${containerId} is missing or ambiguous`, 3);
476
+ const projection = hasStandaloneMediaSchedule(schedule) ? projectDeckSchedule(story, schedule) : undefined;
477
+ const deckStory = projection?.storyboard ?? story;
478
+ const deckSchedule = projection?.schedule ?? schedule;
479
+ if (!hasStandaloneMediaSchedule(schedule) || projection) {
480
+ this.operations(deckStory, deckSchedule);
481
+ for (const annotation of deckSchedule.annotations) {
482
+ const slide = this.slide(annotation.slide);
483
+ const targets = annotation.target.type === 'path'
484
+ ? annotation.target.points.flatMap(point => 'target' in point ? [point.target] : [])
485
+ : annotation.target.type === 'connector'
486
+ ? [annotation.target.from, annotation.target.to].flatMap(ep => 'target' in ep ? [ep.target] : [])
487
+ : [annotation.target];
488
+ for (const target of targets) {
489
+ if (target.type === 'shape') {
490
+ const candidates = slide.shapes.filter(shape => shape.id === target.id);
491
+ requireCondition(candidates.length === 1, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: shape ${target.id} is missing or ambiguous`, 3);
489
492
  const shape = candidates[0];
490
- const issues = [...shape.unsupported, ...(shape.text_unsupported ?? [])];
491
- requireCondition(issues.length === 0 && annotation.click >= shape.visible_from_click && Boolean(shape.text), 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}, shape ${shape.id} (${shape.name}): ${issues.join('; ') || (annotation.click < shape.visible_from_click ? `hidden until click ${shape.visible_from_click}` : 'shape contains no text')}`, 3);
492
- shapes = [shape];
493
- }
494
- else {
495
- shapes = slide.shapes.filter(shape => shape.unsupported.length === 0 && (shape.text_unsupported ?? []).length === 0 && annotation.click >= shape.visible_from_click && Boolean(shape.text));
493
+ requireCondition(shape.unsupported.length === 0 && annotation.click >= shape.visible_from_click, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}, shape ${shape.id} (${shape.name}): ${shape.unsupported.join('; ') || `hidden until click ${shape.visible_from_click}`}`, 3);
496
494
  }
497
- const matches = [];
498
- for (const shape of shapes) {
499
- const text = shape.text ?? '';
500
- let pos = text.indexOf(needle);
501
- while (pos >= 0) {
502
- matches.push({ shape, pos });
503
- pos = text.indexOf(needle, pos + 1);
495
+ if (target.type === 'text') {
496
+ const needle = target.text.trim().replace(/\s+/g, ' ');
497
+ let shapes;
498
+ if (target.container) {
499
+ requireCondition(target.container.type === 'shape', 'ANNOTATION_TARGET', `Annotation ${annotation.id}: PowerPoint text container requires a shape ID`, 3);
500
+ const containerId = target.container.id;
501
+ const candidates = slide.shapes.filter(shape => shape.id === containerId);
502
+ requireCondition(candidates.length === 1, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: shape ${containerId} is missing or ambiguous`, 3);
503
+ const shape = candidates[0];
504
+ const issues = [...shape.unsupported, ...(shape.text_unsupported ?? [])];
505
+ requireCondition(issues.length === 0 && annotation.click >= shape.visible_from_click && Boolean(shape.text), 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}, shape ${shape.id} (${shape.name}): ${issues.join('; ') || (annotation.click < shape.visible_from_click ? `hidden until click ${shape.visible_from_click}` : 'shape contains no text')}`, 3);
506
+ shapes = [shape];
504
507
  }
508
+ else {
509
+ shapes = slide.shapes.filter(shape => shape.unsupported.length === 0 && (shape.text_unsupported ?? []).length === 0 && annotation.click >= shape.visible_from_click && Boolean(shape.text));
510
+ }
511
+ const matches = [];
512
+ for (const shape of shapes) {
513
+ const text = shape.text ?? '';
514
+ let pos = text.indexOf(needle);
515
+ while (pos >= 0) {
516
+ matches.push({ shape, pos });
517
+ pos = text.indexOf(needle, pos + 1);
518
+ }
519
+ }
520
+ if (matches.length === 0) {
521
+ const unsupportedMatch = !target.container
522
+ ? slide.shapes.find(shape => shape.unsupported.length === 0 && (shape.text_unsupported ?? []).length > 0 && annotation.click >= shape.visible_from_click && (shape.text ?? '').includes(needle))
523
+ : undefined;
524
+ const detail = unsupportedMatch
525
+ ? `shape ${unsupportedMatch.id} (${unsupportedMatch.name}): ${(unsupportedMatch.text_unsupported ?? []).join('; ')}`
526
+ : `text ${JSON.stringify(needle)} not found in visible supported shapes`;
527
+ requireCondition(false, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: ${detail}`, 3);
528
+ }
529
+ requireCondition(target.occurrence !== undefined || matches.length === 1, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: text ${JSON.stringify(needle)} matched ${matches.length} times; specify container or occurrence`, 3);
530
+ const selected = matches[(target.occurrence ?? 1) - 1];
531
+ requireCondition(selected !== undefined, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: text occurrence ${target.occurrence} does not exist`, 3);
505
532
  }
506
- if (matches.length === 0) {
507
- const unsupportedMatch = !target.container
508
- ? slide.shapes.find(shape => shape.unsupported.length === 0 && (shape.text_unsupported ?? []).length > 0 && annotation.click >= shape.visible_from_click && (shape.text ?? '').includes(needle))
509
- : undefined;
510
- const detail = unsupportedMatch
511
- ? `shape ${unsupportedMatch.id} (${unsupportedMatch.name}): ${(unsupportedMatch.text_unsupported ?? []).join('; ')}`
512
- : `text ${JSON.stringify(needle)} not found in visible supported shapes`;
513
- requireCondition(false, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: ${detail}`, 3);
514
- }
515
- requireCondition(target.occurrence !== undefined || matches.length === 1, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: text ${JSON.stringify(needle)} matched ${matches.length} times; specify container or occurrence`, 3);
516
- const selected = matches[(target.occurrence ?? 1) - 1];
517
- requireCondition(selected !== undefined, 'ANNOTATION_TARGET', `Annotation ${annotation.id}, slide ${annotation.slide}: text occurrence ${target.occurrence} does not exist`, 3);
518
533
  }
519
534
  }
520
535
  }
521
536
  }
522
537
  else if (!story.cues.some(cue => cue.action.type === 'slide' || cue.action.type === 'reveal')) {
523
- for (const scene of story.scenes) {
538
+ for (const scene of slideScenes) {
524
539
  let slide = this.slide(scene.slide);
525
540
  let click = 0;
526
541
  for (const action of scene.actions) {
@@ -3,6 +3,7 @@ import { fork } from 'node:child_process';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { dirname } from 'node:path';
5
5
  import { normalizeSpeakerNotes } from '../contracts.js';
6
+ import { isSlideScene, slideSceneCues } from '../standalone-media.js';
6
7
  import { slidevInputs } from './slidev-inputs.js';
7
8
  import { requireCondition, ProductionError } from '../errors.js';
8
9
  async function loadDeck(deck) {
@@ -51,10 +52,14 @@ export async function inspectSlidev(deck) {
51
52
  }
52
53
  export function validateSlidev(story, inspection, options) {
53
54
  const schedule = options?.schedule;
54
- for (const scene of story.scenes) {
55
+ const slideScenes = story.scenes.filter(isSlideScene);
56
+ const slideSceneIds = new Set(slideScenes.map(scene => scene.id));
57
+ for (const scene of slideScenes) {
55
58
  requireCondition(inspection.slides.some(s => s.id === scene.slide), 'SLIDE_REFERENCE', `Scene ${scene.id} has unknown slide ${scene.slide}`);
56
59
  }
57
60
  for (const annotation of story.annotations) {
61
+ if (!slideSceneIds.has(annotation.scene))
62
+ continue;
58
63
  const targets = annotation.target.type === 'path'
59
64
  ? annotation.target.points.flatMap(point => 'target' in point ? [point.target] : [])
60
65
  : annotation.target.type === 'connector'
@@ -64,7 +69,7 @@ export function validateSlidev(story, inspection, options) {
64
69
  requireCondition(target.type !== 'shape' && !(target.type === 'text' && target.container?.type === 'shape'), 'ANNOTATION_TARGET', `Annotation ${annotation.id} uses a PowerPoint shape target unsupported by Slidev`, 3, { annotation: annotation.id });
65
70
  }
66
71
  }
67
- const actions = [...story.scenes.flatMap(s => s.actions), ...story.cues.map(c => ({ ...c.action, id: c.id }))];
72
+ const actions = [...slideScenes.flatMap(s => s.actions), ...slideSceneCues(story).map(c => ({ ...c.action, id: c.id }))];
68
73
  for (const action of actions) {
69
74
  if (action.type === 'slide')
70
75
  requireCondition(inspection.slides.some(s => s.id === action.target), 'SLIDE_REFERENCE', `Unknown slide ${action.target}`);
@@ -72,7 +77,9 @@ export function validateSlidev(story, inspection, options) {
72
77
  requireCondition(inspection.media_ids.includes(action.media), 'MEDIA_TARGET', `Deck has no media element ${action.media}`, 3);
73
78
  }
74
79
  const slides = new Map(inspection.slides.map(slide => [slide.id, slide]));
75
- const sequence = schedule ? schedule.actions.map(item => item.action) : story.scenes.flatMap(scene => [{ id: `${scene.id}:slide`, type: 'slide', target: scene.slide, duration_ms: 0 }, ...scene.actions]);
80
+ const sequence = schedule
81
+ ? schedule.actions.filter(item => slideSceneIds.has(item.scene)).map(item => item.action)
82
+ : slideScenes.flatMap(scene => [{ id: `${scene.id}:slide`, type: 'slide', target: scene.slide, duration_ms: 0 }, ...scene.actions]);
76
83
  let active;
77
84
  let click = 0;
78
85
  const pendingNavigation = !schedule && story.cues.some(cue => cue.action.type === 'slide');
@@ -1,4 +1,4 @@
1
- import { type Schedule, type SpeechManifest, type VisualArtifact, type ProductionOptions } from './contracts.js';
1
+ import { type CaptureMapping, type Schedule, type SpeechManifest, type VisualArtifact, type ProductionOptions } from './contracts.js';
2
2
  type AssemblyOptions = ProductionOptions & {
3
3
  licensed?: boolean;
4
4
  inputHashes?: Record<string, string>;
@@ -12,7 +12,7 @@ export declare function assemble(schedule: Schedule, speech: SpeechManifest, vis
12
12
  final_hold: string;
13
13
  trim_start_ms: number;
14
14
  trim_end_ms: number;
15
- mapping: import("./contracts.js").CaptureMapping;
15
+ mapping: CaptureMapping;
16
16
  transformations: unknown[];
17
17
  editorial_review: string;
18
18
  compositor?: {
package/dist/assembly.js CHANGED
@@ -7,6 +7,7 @@ import { execute, executionScope, executionSignal, ffmpegFilterScriptFlags, hash
7
7
  import { ProductionError, requireCondition } from './errors.js';
8
8
  import { configuredLicense, executable } from './executables.js';
9
9
  import { annotationApplications, verifyAnnotations } from './annotations.js';
10
+ import { hasStandaloneMediaSchedule, remapDeckVisualToFull, standaloneAnnotationGeometry } from './standalone-media.js';
10
11
  const NARRATION_SAMPLE_RATE = 48000;
11
12
  const NARRATION_CHANNELS = 2;
12
13
  const NARRATION_BYTES_PER_SAMPLE = 4 * NARRATION_CHANNELS; // f32le stereo
@@ -102,10 +103,112 @@ async function writeNarrationTrack(destination, items, audioOrigin) {
102
103
  throw error;
103
104
  }
104
105
  }
106
+ async function buildSplicedBaseVideo(schedule, visual, video, mapping, temporaryDirectory) {
107
+ const inputIndexes = new Map();
108
+ const args = ['-v', 'error', '-xerror', '-y'];
109
+ const inputFor = (filePath) => {
110
+ const existing = inputIndexes.get(filePath);
111
+ if (existing !== undefined)
112
+ return existing;
113
+ const index = inputIndexes.size;
114
+ inputIndexes.set(filePath, index);
115
+ args.push('-i', filePath);
116
+ return index;
117
+ };
118
+ const scalePad = `scale=${video.width}:${video.height}:force_original_aspect_ratio=decrease,pad=${video.width}:${video.height}:(ow-iw)/2:(oh-ih)/2:black,setsar=1`;
119
+ const filters = [];
120
+ const segments = [];
121
+ const windows = [];
122
+ let deckCursor = 0;
123
+ for (const scene of schedule.scenes ?? []) {
124
+ const sceneDurationMs = scene.end_ms - scene.start_ms;
125
+ if (sceneDurationMs <= 0)
126
+ continue;
127
+ if (scene.kind === 'slide') {
128
+ requireCondition(Boolean(visual.file), 'CAPTURE_ORIGIN', 'Assembly requires a recorded presentation capture for slide scenes', 6);
129
+ const deckIdx = inputFor(visual.file);
130
+ const deckStart = deckCursor;
131
+ const deckEnd = deckCursor + sceneDurationMs;
132
+ deckCursor = deckEnd;
133
+ windows.push({
134
+ id: scene.id,
135
+ slide: scene.slide,
136
+ full_start_ms: scene.start_ms,
137
+ full_end_ms: scene.end_ms,
138
+ deck_start_ms: deckStart,
139
+ deck_end_ms: deckEnd,
140
+ });
141
+ const rawStart = mapping.offset_ms + deckStart;
142
+ const rawEnd = mapping.offset_ms + deckEnd;
143
+ const clipStart = Math.max(mapping.trim_start_ms, rawStart);
144
+ const leadHoldSec = Math.max(0, clipStart - rawStart) / 1000;
145
+ const minFrameMs = 1000 / video.fps;
146
+ const clipEnd = Math.min(mapping.trim_end_ms, Math.max(clipStart + minFrameMs, rawEnd));
147
+ const sceneDurSec = sceneDurationMs / 1000;
148
+ const seg = `seg${segments.length}`;
149
+ const leadPad = leadHoldSec > 1e-6 ? `,tpad=start_mode=clone:start_duration=${leadHoldSec}` : '';
150
+ filters.push(`[${deckIdx}:v]trim=start=${clipStart / 1000}:end=${clipEnd / 1000},setpts=PTS-STARTPTS${leadPad},${scalePad},fps=${video.fps},tpad=stop_mode=clone:stop_duration=${sceneDurSec},trim=duration=${sceneDurSec},setpts=PTS-STARTPTS,format=yuv420p[${seg}]`);
151
+ segments.push(`[${seg}]`);
152
+ continue;
153
+ }
154
+ const mediaEntry = schedule.media.find(item => item.id === scene.media);
155
+ requireCondition(mediaEntry, 'MISSING_MEDIA', `Missing scheduled media ${scene.media}`, 7);
156
+ const mediaIdx = inputFor(mediaEntry.src);
157
+ const slices = schedule.actions
158
+ .filter((item) => item.scene === scene.id && item.action.type === 'play')
159
+ .sort((a, b) => a.start_ms - b.start_ms);
160
+ for (let index = 0; index < slices.length; index++) {
161
+ const slice = slices[index];
162
+ requireCondition(slice.start_ms >= scene.start_ms - 1e-6 && slice.end_ms <= scene.end_ms + 1e-6, 'MEDIA_SCENE_RANGE', `Play ${slice.id} exceeds standalone media scene ${scene.id} bounds`, 7);
163
+ const trimStartSec = (slice.action.trim_start_ms ?? 0) / 1000;
164
+ const trimEndSec = (slice.action.trim_end_ms ?? mediaEntry.duration_ms) / 1000;
165
+ const rate = slice.action.rate ?? 1;
166
+ const sliceDurSec = (slice.end_ms - slice.start_ms) / 1000;
167
+ const leadHoldSec = index === 0 ? Math.max(0, slice.start_ms - scene.start_ms) / 1000 : 0;
168
+ const nextStart = slices[index + 1]?.start_ms ?? scene.end_ms;
169
+ const tailHoldSec = Math.max(0, nextStart - slice.end_ms) / 1000;
170
+ const totalSegDurSec = leadHoldSec + sliceDurSec + tailHoldSec;
171
+ const seg = `seg${segments.length}`;
172
+ const leadPad = leadHoldSec > 1e-6 ? `,tpad=start_mode=clone:start_duration=${leadHoldSec}` : '';
173
+ filters.push(`[${mediaIdx}:v]trim=start=${trimStartSec}:end=${trimEndSec},setpts=(PTS-STARTPTS)/${rate},${scalePad},fps=${video.fps}${leadPad},tpad=stop_mode=clone:stop_duration=${tailHoldSec + 0.25},trim=duration=${totalSegDurSec},setpts=PTS-STARTPTS,format=yuv420p[${seg}]`);
174
+ segments.push(`[${seg}]`);
175
+ }
176
+ }
177
+ requireCondition(segments.length > 0, 'ASSEMBLY', 'No visual segments available for standalone media splicing', 7);
178
+ if (segments.length === 1) {
179
+ filters.push(`${segments[0]}null[v]`);
180
+ }
181
+ else {
182
+ filters.push(`${segments.join('')}concat=n=${segments.length}:v=1:a=0[v]`);
183
+ }
184
+ const filterScript = join(temporaryDirectory, 'splice-filter.txt');
185
+ await writeFile(filterScript, filters.join(';'));
186
+ const filterFlags = await ffmpegFilterScriptFlags();
187
+ const splicedPath = join(temporaryDirectory, 'spliced.mp4');
188
+ await execute('ffmpeg', [
189
+ ...args,
190
+ filterFlags.complex,
191
+ filterScript,
192
+ '-map',
193
+ '[v]',
194
+ '-an',
195
+ '-c:v',
196
+ 'libx264',
197
+ '-preset',
198
+ 'fast',
199
+ '-crf',
200
+ '14',
201
+ '-pix_fmt',
202
+ 'yuv420p',
203
+ splicedPath,
204
+ ]);
205
+ return { file: splicedPath, windows };
206
+ }
105
207
  export async function assemble(schedule, speech, visual, directory, output, options = { verify_timing: false, output: defaultVideoOutput }) {
106
208
  const video = options.output;
107
209
  const licensed = options.licensed ?? configuredLicense();
108
- requireCondition(visual.timing.status !== 'failed' && (!options.verify_timing || visual.timing.status === 'accepted'), 'TIMING_REQUIRED', 'Assembly cannot use failed or missing requested timing proof', 6);
210
+ const standaloneOnly = visual.provenance.adapter === 'standalone-media';
211
+ requireCondition(visual.timing.status !== 'failed' && (!options.verify_timing || standaloneOnly || visual.timing.status === 'accepted'), 'TIMING_REQUIRED', 'Assembly cannot use failed or missing requested timing proof', 6);
109
212
  const mapping = visual.origin?.mapping ?? (visual.timing.status === 'accepted' ? visual.timing.mapping : undefined);
110
213
  requireCondition(mapping && Object.values(mapping).every(Number.isFinite) && mapping.trim_start_ms >= 0 && mapping.trim_end_ms > mapping.trim_start_ms, 'CAPTURE_ORIGIN', 'Assembly requires a usable capture origin', 6);
111
214
  requireCondition(mapping.rate === 1, 'TIMING_RATE', 'Capture clock drift cannot be hidden by stretching narration', 6);
@@ -140,14 +243,30 @@ export async function assemble(schedule, speech, visual, directory, output, opti
140
243
  const transformations = [];
141
244
  const { trim_start_ms, trim_end_ms, offset_ms } = mapping;
142
245
  const originDelta = offset_ms - trim_start_ms;
143
- if (options.verify_timing)
246
+ if (options.verify_timing && !standaloneOnly)
144
247
  requireCondition(originDelta >= -100 && originDelta <= 100, 'TRIM_MAPPING', 'Presentation trim differs from measured origin', 6);
145
- const audioOrigin = Math.max(0, originDelta);
146
- const pictureLeadHold = Math.max(0, -originDelta);
248
+ const spliced = hasStandaloneMediaSchedule(schedule)
249
+ ? await buildSplicedBaseVideo(schedule, visual, video, mapping, temporaryDirectory)
250
+ : undefined;
251
+ const baseVideoFile = spliced ? spliced.file : visual.file;
252
+ const audioOrigin = spliced ? 0 : Math.max(0, originDelta);
253
+ const pictureLeadHold = spliced ? 0 : Math.max(0, -originDelta);
147
254
  const duration = (schedule.duration_ms + audioOrigin) / 1000;
148
- const baseFilter = `trim=start=${trim_start_ms / 1000}:end=${trim_end_ms / 1000},setpts=PTS-STARTPTS,tpad=start_mode=clone:start_duration=${pictureLeadHold / 1000},fps=${video.fps},tpad=stop_mode=clone:stop_duration=${duration},trim=duration=${duration},format=yuv420p`;
255
+ const baseFilter = spliced
256
+ ? `fps=${video.fps},tpad=stop_mode=clone:stop_duration=${duration},trim=duration=${duration},format=yuv420p`
257
+ : `trim=start=${trim_start_ms / 1000}:end=${trim_end_ms / 1000},setpts=PTS-STARTPTS,tpad=start_mode=clone:start_duration=${pictureLeadHold / 1000},fps=${video.fps},tpad=stop_mode=clone:stop_duration=${duration},trim=duration=${duration},format=yuv420p`;
149
258
  const frameCount = Math.ceil(duration * video.fps - 1e-9);
150
- const annotations = annotationApplications(video, schedule, visual, audioOrigin);
259
+ const effectiveVisual = spliced
260
+ ? {
261
+ ...remapDeckVisualToFull(visual, spliced.windows),
262
+ file: baseVideoFile,
263
+ annotation_geometry: [
264
+ ...(remapDeckVisualToFull(visual, spliced.windows).annotation_geometry ?? []),
265
+ ...standaloneAnnotationGeometry(schedule, video),
266
+ ],
267
+ }
268
+ : visual;
269
+ const annotations = annotationApplications(video, schedule, effectiveVisual, audioOrigin);
151
270
  const renderer = annotations.length || schedule.overlays?.length || !licensed ? await import('./compositor.js') : undefined;
152
271
  const layers = await renderer?.frameLayers(video, schedule, options.inputHashes) ?? [];
153
272
  const { canvasLayers, staticTopLayers } = renderer ? renderer.splitFrameLayers(layers) : { canvasLayers: [], staticTopLayers: [] };
@@ -168,12 +287,12 @@ export async function assemble(schedule, speech, visual, directory, output, opti
168
287
  let input = 1;
169
288
  switch (plan.kind) {
170
289
  case 'none':
171
- args.push('-i', visual.file);
290
+ args.push('-i', baseVideoFile);
172
291
  filters.push(`[0:v]${baseFilter}[${stageOut}]`);
173
292
  input = 1;
174
293
  break;
175
294
  case 'sparse':
176
- args.push('-i', visual.file);
295
+ args.push('-i', baseVideoFile);
177
296
  args.push('-f', 'rawvideo', '-pixel_format', 'rgba', '-video_size', `${video.width}x${video.height}`, '-framerate', String(video.fps), '-i', 'pipe:0');
178
297
  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
298
  input = 2;
@@ -243,7 +362,7 @@ export async function assemble(schedule, speech, visual, directory, output, opti
243
362
  args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '18', '-t', String(duration), '-movflags', '+faststart');
244
363
  let compositor;
245
364
  if (plan.kind !== 'none') {
246
- compositor = await renderer.compositeFrames(visual.file, baseFilter, [...args, temporary], video, annotations, plan, frameCount, audioOrigin, temporaryDirectory);
365
+ compositor = await renderer.compositeFrames(baseVideoFile, baseFilter, [...args, temporary], video, annotations, plan, frameCount, audioOrigin, temporaryDirectory);
247
366
  }
248
367
  else {
249
368
  await execute('ffmpeg', [...args, temporary]);
@@ -258,7 +377,7 @@ export async function assemble(schedule, speech, visual, directory, output, opti
258
377
  let annotationEvidence;
259
378
  if (annotations.length && options.verify_timing) {
260
379
  try {
261
- annotationEvidence = await verifyAnnotations(temporary, visual.file, baseFilter, annotations, video, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, video.fps, audioOrigin, watermarkRect), outputSha256);
380
+ annotationEvidence = await verifyAnnotations(temporary, baseVideoFile, baseFilter, annotations, video, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, video.fps, audioOrigin, watermarkRect), outputSha256);
262
381
  }
263
382
  catch (error) {
264
383
  await copyFile(temporary, join(directory, 'failed-composite.mp4'));