@slidevideo/cli 0.2.2 → 0.3.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,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.3.0
6
+
7
+ - Speed up normal Slidev and PowerPoint recording by compressing static slide holds while keeping dynamic slides and `--verify-timing` at `1.0x`.
8
+ - Fix native PowerPoint inspection timeouts on larger decks, slideshow startup races, and sequential click-reveal playback.
9
+ - Make speech caches portable across directories by storing relative audio paths in cache metadata.
10
+
5
11
  ## 0.2.2
6
12
 
7
13
  - Support finite native PowerPoint slide transitions, broader finite `MainSequence` animations (including `Wipe`, `Split`, `Fly In`, emphasis, exit, motion paths, and automatic pre-click entry), static `.svg` graphics, cropped pictures, grouped shape targets, dynamic full-resolution window capture with output letterboxing, and storyboard video trims (`trim_start_ms` / `trim_end_ms`).
@@ -45,25 +45,36 @@ if (previewEnabled) {
45
45
  document.addEventListener('volumechange', silence, true)
46
46
  for (const type of ['keydown', 'pointerdown', 'click', 'dblclick', 'wheel']) document.addEventListener(type, preventNavigation, { capture: true, passive: false })
47
47
  }
48
- const state = { version: 1, phase: 'idle', events: [] as ObservedEvent[], markers: [] as { color: string; observed_ms: number; paint_interval_ms: number; rendered_by_ms: number }[], failure: '', annotation_geometry: [] as AnnotationGeometry[] }
48
+ type StaticSkip = { schedule_start_ms: number; schedule_end_ms: number; skip_ms: number }
49
+ type AppliedSkip = { record_at_ms: number; skip_ms: number }
50
+ const state = { version: 1, phase: 'idle', events: [] as ObservedEvent[], markers: [] as { color: string; observed_ms: number; paint_interval_ms: number; rendered_by_ms: number }[], failure: '', annotation_geometry: [] as AnnotationGeometry[], applied_skips: [] as AppliedSkip[] }
49
51
  let generation = 0
50
52
  let origin = 0
53
+ let skippedMs = 0
54
+ const scheduleNow = () => (performance.now() - origin) + skippedMs
51
55
  let schedule: Schedule
52
56
  let visit = ''
53
57
  let geometry: ReturnType<typeof geometryCollector> | undefined
54
- const monitors = new Map<HTMLMediaElement, { timer: ReturnType<typeof setInterval>; item: ScheduledAction }>()
58
+ const monitors = new Map<HTMLMediaElement, { timer: number; item: ScheduledAction }>()
55
59
  function stopMedia(element: HTMLMediaElement, completed: boolean) {
56
60
  const monitor = monitors.get(element)
57
61
  if (!monitor) return
58
- clearInterval(monitor.timer); monitors.delete(element); element.pause()
59
- if (completed) state.events.push({ id: `${monitor.item.id}:ended`, type: 'media-ended', scheduled_ms: monitor.item.end_ms, observed_ms: performance.now() - origin, media_ms: element.currentTime * 1000 })
62
+ if (window.__slidevideoTimers) window.__slidevideoTimers.clearInternalInterval(monitor.timer)
63
+ else window.clearInterval(monitor.timer)
64
+ monitors.delete(element); element.pause()
65
+ 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 })
60
66
  }
61
- const waits = new Map<ReturnType<typeof setTimeout>, () => void>()
67
+ const waits = new Map<number, () => void>()
62
68
  const wait = (ms: number) => new Promise<void>(resolve => {
63
- const timer = setTimeout(() => { waits.delete(timer); resolve() }, Math.max(0, ms))
69
+ const scheduleTimer = window.__slidevideoTimers ? window.__slidevideoTimers.setInternalTimeout : (cb: () => void, delay: number) => window.setTimeout(cb, delay)
70
+ const timer = scheduleTimer(() => { waits.delete(timer); resolve() }, Math.max(0, ms))
64
71
  waits.set(timer, resolve)
65
72
  })
66
- function clearWaits() { for (const [timer, resolve] of waits) { clearTimeout(timer); resolve() }; waits.clear() }
73
+ function clearWaits() {
74
+ const cancelTimer = window.__slidevideoTimers ? window.__slidevideoTimers.clearInternalTimeout : (id: number) => window.clearTimeout(id)
75
+ for (const [timer, resolve] of waits) { cancelTimer(timer); resolve() }
76
+ waits.clear()
77
+ }
67
78
  const painted = async () => {
68
79
  await nextTick()
69
80
  const first = await new Promise<number>(resolve => requestAnimationFrame(resolve))
@@ -117,7 +128,7 @@ async function prepare(value: Schedule, expectedHashes: Record<string, string> =
117
128
  generation++; clearWaits()
118
129
  geometry?.stop(); geometry = undefined; visit = ''
119
130
  for (const element of monitors.keys()) stopMedia(element, false)
120
- state.phase = 'preparing'; state.events = []; state.markers = []; state.failure = ''; state.annotation_geometry = []; marker.value = ''
131
+ state.phase = 'preparing'; state.events = []; state.markers = []; state.failure = ''; state.annotation_geometry = []; state.applied_skips = []; marker.value = ''
121
132
  schedule = value
122
133
  for (const slide of nav.slides.value) { await navigate(slide.no); }
123
134
  await document.fonts.ready
@@ -136,9 +147,11 @@ async function prepare(value: Schedule, expectedHashes: Record<string, string> =
136
147
  }
137
148
  element.muted = true; element.pause(); element.currentTime = 0; element.playbackRate = 1
138
149
  if (element.readyState < 3) await new Promise<void>((resolve, reject) => {
139
- element.addEventListener('canplay', () => resolve(), { once: true })
140
- element.addEventListener('error', () => reject(new Error(`Media cannot load ${clip.id}`)), { once: true })
141
- setTimeout(() => reject(new Error(`Media readiness timeout ${clip.id}`)), 10000)
150
+ const scheduleTimer = window.__slidevideoTimers ? window.__slidevideoTimers.setInternalTimeout : (cb: () => void, delay: number) => window.setTimeout(cb, delay)
151
+ const cancelTimer = window.__slidevideoTimers ? window.__slidevideoTimers.clearInternalTimeout : (id: number) => window.clearTimeout(id)
152
+ const timer = scheduleTimer(() => reject(new Error(`Media readiness timeout ${clip.id}`)), 10000)
153
+ element.addEventListener('canplay', () => { cancelTimer(timer); resolve() }, { once: true })
154
+ element.addEventListener('error', () => { cancelTimer(timer); reject(new Error(`Media cannot load ${clip.id}`)) }, { once: true })
142
155
  })
143
156
  }
144
157
  let selected = nav.slides.value[0]
@@ -158,9 +171,231 @@ async function showMarker(color: string, current: number) {
158
171
  await wait(350)
159
172
  if (current !== generation) throw new Error('Playback reset')
160
173
  }
161
- async function play(verifyTiming = false) {
174
+ const STATIC_RASTER_EXT = /\.(?:jpe?g|bmp|ico)$/i
175
+ const STATIC_RASTER_DATA = /^data:image\/(?:jpe?g|bmp|x-icon)(?:[;,]|$)/i
176
+ const SVG_EXT = /\.svg$/i
177
+ const SVG_DATA = /^data:image\/svg\+xml(?:[;,]|$)/i
178
+ const PNG_EXT = /\.png$/i
179
+ const PNG_DATA = /^data:image\/png(?:[;,]|$)/i
180
+ const SVG_DYNAMIC_CONTENT = /<(?:[a-z_][\w.-]*:)?(?:animate|animateTransform|animateMotion|animateColor|set|discard|script|foreignObject|image)\b|<(?:[a-z_][\w.-]*:)?use\b[^>]*\bhref\s*=\s*["'](?!#)|@keyframes\b|\banimation(?:-name)?\s*:/i
181
+ const svgStaticCache = new Map<string, boolean>()
182
+ const pngStaticCache = new Map<string, boolean>()
183
+ function isStaticPngBytes(bytes: Uint8Array): boolean {
184
+ if (bytes.length < 24 || bytes[0] !== 0x89 || bytes[1] !== 0x50 || bytes[2] !== 0x4e || bytes[3] !== 0x47) return false
185
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
186
+ let offset = 8
187
+ while (offset + 8 <= bytes.length) {
188
+ const length = view.getUint32(offset)
189
+ const type = String.fromCharCode(bytes[offset + 4], bytes[offset + 5], bytes[offset + 6], bytes[offset + 7])
190
+ if (type === 'acTL') return false
191
+ if (type === 'IDAT' || type === 'IEND') return true
192
+ offset += 12 + length
193
+ }
194
+ return false
195
+ }
196
+ async function isPngImageStatic(src: string, deadlineMs: number): Promise<boolean> {
197
+ const cached = pngStaticCache.get(src)
198
+ if (cached !== undefined) return cached
199
+ if (performance.now() >= deadlineMs) return false
200
+ try {
201
+ let bytes: Uint8Array
202
+ if (/^data:image\/png/i.test(src)) {
203
+ if (src.length > 262144) return false
204
+ const comma = src.indexOf(',')
205
+ const meta = comma >= 0 ? src.slice(0, comma) : ''
206
+ const payload = comma >= 0 ? src.slice(comma + 1) : ''
207
+ const raw = /;base64/i.test(meta) ? atob(payload) : decodeURIComponent(payload)
208
+ bytes = Uint8Array.from(raw, ch => ch.charCodeAt(0))
209
+ } else {
210
+ const remaining = deadlineMs - performance.now()
211
+ if (remaining <= 0) return false
212
+ const resolved = new URL(src, location.href)
213
+ if (resolved.origin !== location.origin) { pngStaticCache.set(src, false); return false }
214
+ const controller = new AbortController()
215
+ const scheduleTimer = window.__slidevideoTimers ? window.__slidevideoTimers.setInternalTimeout : (cb: () => void, delay: number) => window.setTimeout(cb, delay)
216
+ const cancelTimer = window.__slidevideoTimers ? window.__slidevideoTimers.clearInternalTimeout : (id: number) => window.clearTimeout(id)
217
+ const timer = scheduleTimer(() => controller.abort(), remaining)
218
+ try {
219
+ const response = await fetch(resolved.href, { signal: controller.signal })
220
+ if (!response.ok) { pngStaticCache.set(src, false); return false }
221
+ bytes = new Uint8Array(await response.arrayBuffer())
222
+ } finally {
223
+ cancelTimer(timer)
224
+ }
225
+ }
226
+ const isStatic = isStaticPngBytes(bytes)
227
+ pngStaticCache.set(src, isStatic)
228
+ return isStatic
229
+ } catch {
230
+ return false
231
+ }
232
+ }
233
+ async function isSvgImageStatic(src: string, deadlineMs: number): Promise<boolean> {
234
+ const cached = svgStaticCache.get(src)
235
+ if (cached !== undefined) return cached
236
+ if (performance.now() >= deadlineMs) return false
237
+ try {
238
+ let text = ''
239
+ if (/^data:image\/svg\+xml/i.test(src)) {
240
+ if (src.length > 262144) return false
241
+ const comma = src.indexOf(',')
242
+ const meta = comma >= 0 ? src.slice(0, comma) : ''
243
+ const payload = comma >= 0 ? src.slice(comma + 1) : ''
244
+ text = /;base64/i.test(meta) ? atob(payload) : decodeURIComponent(payload)
245
+ } else {
246
+ const remaining = deadlineMs - performance.now()
247
+ if (remaining <= 0) return false
248
+ const resolved = new URL(src, location.href)
249
+ if (resolved.origin !== location.origin) { svgStaticCache.set(src, false); return false }
250
+ const controller = new AbortController()
251
+ const scheduleTimer = window.__slidevideoTimers ? window.__slidevideoTimers.setInternalTimeout : (cb: () => void, delay: number) => window.setTimeout(cb, delay)
252
+ const cancelTimer = window.__slidevideoTimers ? window.__slidevideoTimers.clearInternalTimeout : (id: number) => window.clearTimeout(id)
253
+ const timer = scheduleTimer(() => controller.abort(), remaining)
254
+ try {
255
+ const response = await fetch(resolved.href, { signal: controller.signal })
256
+ if (!response.ok) { svgStaticCache.set(src, false); return false }
257
+ text = await response.text()
258
+ } finally {
259
+ cancelTimer(timer)
260
+ }
261
+ }
262
+ const isStatic = !SVG_DYNAMIC_CONTENT.test(text)
263
+ svgStaticCache.set(src, isStatic)
264
+ return isStatic
265
+ } catch {
266
+ return false
267
+ }
268
+ }
269
+ async function isImageUrlStatic(src: string, deadlineMs: number): Promise<boolean> {
270
+ if (!src) return true
271
+ if (STATIC_RASTER_DATA.test(src)) return true
272
+ if (SVG_DATA.test(src)) return isSvgImageStatic(src, deadlineMs)
273
+ if (PNG_DATA.test(src)) return isPngImageStatic(src, deadlineMs)
274
+ if (/^data:/i.test(src) || /^blob:/i.test(src)) return false
275
+ let pathname = ''
276
+ try { pathname = new URL(src, location.href).pathname } catch { return false }
277
+ if (STATIC_RASTER_EXT.test(pathname)) return true
278
+ if (SVG_EXT.test(pathname)) return isSvgImageStatic(src, deadlineMs)
279
+ if (PNG_EXT.test(pathname)) return isPngImageStatic(src, deadlineMs)
280
+ return false
281
+ }
282
+ function hasSlideScriptOrMotion(): boolean {
283
+ const slide = nav.currentSlideRoute.value?.meta?.slide
284
+ if (!slide) return true
285
+ const raw = String(slide.content ?? '')
286
+ const stripped = raw.replace(/```[\s\S]*?```/g, '').replace(/`[^`]*`/g, '')
287
+ return /<script\b/i.test(stripped) || /\bv-motion\b/.test(stripped)
288
+ }
289
+ async function isSlideStatic(current: number, maxBudgetMs: number): Promise<boolean> {
290
+ if (monitors.size > 0 || hasSlideScriptOrMotion() || window.__slidevideoTimers?.hasPending()) return false
291
+ if (await window.__slidevideoHasInFlightRequests?.()) return false
292
+ const root = document.body
293
+ if (!root || window.__slidevideoTimers?.hasShadowHost(root)) return false
294
+ const svgDeadline = performance.now() + Math.min(100, Math.max(0, maxBudgetMs))
295
+ const hasDynamicDom = async () => {
296
+ for (const mediaEl of root.querySelectorAll<HTMLMediaElement>('video, audio')) {
297
+ if (!mediaEl.paused && !mediaEl.ended) return true
298
+ }
299
+ for (const element of root.querySelectorAll('canvas, iframe, object, embed, progress:not([value])')) {
300
+ if (element.tagName === 'CANVAS' && element.hasAttribute('data-slidevideo-canvas')) continue
301
+ if (element.checkVisibility({ opacityProperty: true, visibilityProperty: true })) return true
302
+ }
303
+ if (root.querySelector('svg animate, svg animateTransform, svg animateMotion, svg animateColor, svg set, svg discard, svg foreignObject')) return true
304
+ for (const refEl of root.querySelectorAll('svg image, svg use')) {
305
+ const href = refEl.getAttribute('href') || refEl.getAttribute('xlink:href') || ''
306
+ if (href && !href.startsWith('#') && !(await isImageUrlStatic(href, svgDeadline))) return true
307
+ }
308
+ for (const img of root.querySelectorAll('img')) {
309
+ if (!img.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue
310
+ if (!img.complete && (img.currentSrc || img.getAttribute('src') || img.getAttribute('srcset'))) return true
311
+ const src = img.currentSrc || img.getAttribute('src') || ''
312
+ if (src && !(await isImageUrlStatic(src, svgDeadline))) return true
313
+ }
314
+ for (const element of root.querySelectorAll('*')) {
315
+ if (!element.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue
316
+ for (const pseudo of [null, '::before', '::after'] as const) {
317
+ const style = getComputedStyle(element, pseudo)
318
+ for (const prop of ['backgroundImage', 'content', 'maskImage', 'borderImageSource', 'listStyleImage'] as const) {
319
+ const value = style[prop]
320
+ if (!value || value === 'none' || value === 'normal' || !value.includes('url(')) continue
321
+ for (const match of value.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]+))\s*\)/gi)) {
322
+ const bgUrl = match[1] ?? match[2] ?? match[3] ?? ''
323
+ if (!bgUrl) continue
324
+ if (!(await isImageUrlStatic(bgUrl, svgDeadline))) return true
325
+ if (!/^data:/i.test(bgUrl)) {
326
+ try {
327
+ const resolved = new URL(bgUrl, location.href).href
328
+ if (performance.getEntriesByName(resolved, 'resource').length === 0) return true
329
+ } catch {
330
+ return true
331
+ }
332
+ }
333
+ }
334
+ }
335
+ }
336
+ }
337
+ return false
338
+ }
339
+ const hasRunningAnimation = () => document.getAnimations().some(animation => {
340
+ if (animation.playState !== 'running' && !animation.pending) return false
341
+ const effect = animation.effect
342
+ const target = effect instanceof KeyframeEffect ? effect.target : null
343
+ return target instanceof Node && root.contains(target)
344
+ })
345
+ if (await hasDynamicDom() || hasRunningAnimation()) return false
346
+ let mutated = false
347
+ const observer = new MutationObserver(() => { mutated = true })
348
+ observer.observe(root, { subtree: true, childList: true, attributes: true, characterData: true })
349
+ try {
350
+ await new Promise<number>(resolve => requestAnimationFrame(resolve))
351
+ await new Promise<number>(resolve => requestAnimationFrame(resolve))
352
+ } finally {
353
+ observer.disconnect()
354
+ }
355
+ if (current !== generation) throw new Error('Playback reset')
356
+ if (mutated || monitors.size > 0 || window.__slidevideoTimers?.hasPending() || window.__slidevideoTimers?.hasShadowHost(root) || await window.__slidevideoHasInFlightRequests?.() || await hasDynamicDom() || hasRunningAnimation()) return false
357
+ return true
358
+ }
359
+ async function waitUntilSchedule(targetMs: number, current: number, plannedSkips: StaticSkip[], skipCursor: { index: number; startMs: number }) {
360
+ while (scheduleNow() < targetMs) {
361
+ if (current !== generation) throw new Error('Playback reset')
362
+ if (state.failure) throw new Error(state.failure)
363
+ const skip = plannedSkips[skipCursor.index]
364
+ if (skip && skipCursor.startMs <= targetMs) {
365
+ if (scheduleNow() < skipCursor.startMs) {
366
+ await wait(skipCursor.startMs - scheduleNow())
367
+ continue
368
+ }
369
+ const skipTarget = Math.min(skip.schedule_end_ms, targetMs)
370
+ const svgBudgetMs = Math.max(0, skipTarget - scheduleNow() - 50)
371
+ if (await isSlideStatic(current, svgBudgetMs)) {
372
+ const remainingSkip = skipTarget - scheduleNow()
373
+ if (remainingSkip > 0) {
374
+ state.applied_skips.push({ record_at_ms: performance.now() - origin, skip_ms: remainingSkip })
375
+ skippedMs += remainingSkip
376
+ }
377
+ if (skipTarget >= skip.schedule_end_ms) {
378
+ skipCursor.index++
379
+ skipCursor.startMs = plannedSkips[skipCursor.index]?.schedule_start_ms ?? Infinity
380
+ } else {
381
+ skipCursor.startMs = skipTarget
382
+ }
383
+ continue
384
+ }
385
+ skipCursor.index++
386
+ skipCursor.startMs = plannedSkips[skipCursor.index]?.schedule_start_ms ?? Infinity
387
+ continue
388
+ }
389
+ await wait(targetMs - scheduleNow())
390
+ }
391
+ }
392
+ async function play(verifyTiming = false, plannedSkips: StaticSkip[] = []) {
162
393
  if (state.phase !== 'ready') throw new Error('Prepare playback first')
163
394
  const current = generation
395
+ skippedMs = 0
396
+ state.applied_skips = []
397
+ const skips = verifyTiming ? [] : plannedSkips
398
+ const skipCursor = { index: 0, startMs: skips[0]?.schedule_start_ms ?? Infinity }
164
399
  state.phase = 'recording'; origin = performance.now()
165
400
  try {
166
401
  await showMarker('#ff00ff', current)
@@ -171,9 +406,9 @@ async function play(verifyTiming = false) {
171
406
  for (const event of state.markers) { event.observed_ms -= start - origin; event.rendered_by_ms -= start - origin }
172
407
  origin = start
173
408
  const requests = geometryRequests(schedule)
174
- 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 }), () => performance.now() - origin, message => { state.failure = message })
409
+ 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 })
175
410
  for (const entry of playbackEntries(schedule)) {
176
- while (performance.now() - origin < entry.at) await wait(entry.at - (performance.now() - origin))
411
+ await waitUntilSchedule(entry.at, current, skips, skipCursor)
177
412
  if (current !== generation) throw new Error('Playback reset')
178
413
  if (state.failure) throw new Error(state.failure)
179
414
  if (entry.type === 'geometry-start') { geometry!.start(entry.request); continue }
@@ -181,15 +416,16 @@ async function play(verifyTiming = false) {
181
416
  if (entry.type === 'annotation-start' || entry.type === 'annotation-end') continue
182
417
  const item = entry.item
183
418
  await apply(item)
184
- const observed_ms = performance.now() - origin
419
+ const observed_ms = scheduleNow()
185
420
  if (verifyTiming && observed_ms - item.start_ms > 100) throw new Error(`Late action ${item.id}: ${observed_ms - item.start_ms} ms`)
186
421
  state.events.push({ id: item.id, type: item.action.type, scheduled_ms: item.start_ms, observed_ms })
187
422
  if (item.action.type === 'play') {
188
423
  const action = item.action
189
424
  const element = media(action.media)
190
- const monitor = setInterval(() => {
425
+ const scheduleInterval = window.__slidevideoTimers ? window.__slidevideoTimers.setInternalInterval : (cb: () => void, delay: number) => window.setInterval(cb, delay)
426
+ const monitor = scheduleInterval(() => {
191
427
  if (generation !== current) { stopMedia(element, false); return }
192
- const expected = (performance.now() - origin - item.start_ms) * (action.rate ?? 1) + (action.trim_start_ms ?? 0)
428
+ const expected = (scheduleNow() - item.start_ms) * (action.rate ?? 1) + (action.trim_start_ms ?? 0)
193
429
  if (expected > (item.end_ms - item.start_ms) * (action.rate ?? 1) + (action.trim_start_ms ?? 0)) {
194
430
  stopMedia(element, true)
195
431
  } else if (Math.abs(element.currentTime * 1000 - expected) > 150) {
@@ -199,7 +435,7 @@ async function play(verifyTiming = false) {
199
435
  monitors.set(element, { timer: monitor, item })
200
436
  }
201
437
  }
202
- await wait(schedule.duration_ms - (performance.now() - origin))
438
+ await waitUntilSchedule(schedule.duration_ms, current, skips, skipCursor)
203
439
  for (const element of monitors.keys()) stopMedia(element, true)
204
440
  if (state.failure) throw new Error(state.failure)
205
441
  geometry?.complete(); geometry?.stop(); geometry = undefined
@@ -1,4 +1,5 @@
1
1
  import type { Schedule, ScheduledAction, ObservedEvent, AnnotationGeometry, PresentationInspection } from '../contracts.js';
2
+ import type { AppliedSkip, StaticSkip } from './capture-compression.js';
2
3
  export type PlaybackState = {
3
4
  version: number;
4
5
  phase: string;
@@ -11,12 +12,13 @@ export type PlaybackState = {
11
12
  }[];
12
13
  failure: string;
13
14
  annotation_geometry?: AnnotationGeometry[];
15
+ applied_skips?: AppliedSkip[];
14
16
  };
15
17
  export interface PlaybackRuntime {
16
18
  version: number;
17
19
  state: PlaybackState;
18
20
  prepare(schedule: Schedule, expectedHashes?: Record<string, string>): Promise<void>;
19
- play(verifyTiming?: boolean): Promise<void>;
21
+ play(verifyTiming?: boolean, plannedSkips?: StaticSkip[]): Promise<void>;
20
22
  apply(action: ScheduledAction): Promise<void>;
21
23
  navigate(index: number, click?: number): Promise<void>;
22
24
  inspectTargets(): Promise<PresentationInspection['annotation_targets']>;
@@ -30,11 +32,21 @@ export interface PlaybackRuntime {
30
32
  restart(): Promise<void>;
31
33
  };
32
34
  }
35
+ export type TimerTracker = {
36
+ hasPending(): boolean;
37
+ hasShadowHost(root: Element): boolean;
38
+ setInternalTimeout(callback: () => void, ms: number): number;
39
+ clearInternalTimeout(id: number): void;
40
+ setInternalInterval(callback: () => void, ms: number): number;
41
+ clearInternalInterval(id: number): void;
42
+ };
33
43
  declare global {
34
44
  interface Window {
35
45
  __slidevideo: PlaybackRuntime;
36
46
  __slidevideoCapture?: {
37
47
  stop(): Promise<number>;
38
48
  };
49
+ __slidevideoTimers?: TimerTracker;
50
+ __slidevideoHasInFlightRequests?: () => Promise<boolean>;
39
51
  }
40
52
  }
@@ -0,0 +1,15 @@
1
+ export type DynamicWindow = {
2
+ start_ms: number;
3
+ end_ms: number;
4
+ };
5
+ export type StaticSkip = {
6
+ schedule_start_ms: number;
7
+ schedule_end_ms: number;
8
+ skip_ms: number;
9
+ };
10
+ export type AppliedSkip = {
11
+ record_at_ms: number;
12
+ skip_ms: number;
13
+ };
14
+ export declare function planStaticSkips(dynamicWindows: DynamicWindow[], checkpoints: number[], durationMs: number): StaticSkip[];
15
+ export declare function remapCaptureTimestamps(file: string, offsetMs: number, skips: AppliedSkip[]): Promise<void>;
@@ -0,0 +1,69 @@
1
+ import { rename, rm } from 'node:fs/promises';
2
+ import { dirname, extname, join } from 'node:path';
3
+ import { execute } from '../media.js';
4
+ const LEADING_SETTLE_MS = 250;
5
+ const TRAILING_GUARD_MS = 200;
6
+ const CHECKPOINT_LEADING_MS = 50;
7
+ const CHECKPOINT_TRAILING_MS = 20;
8
+ const MIN_SKIP_MS = 500;
9
+ export function planStaticSkips(dynamicWindows, checkpoints, durationMs) {
10
+ if (!Number.isFinite(durationMs) || durationMs <= LEADING_SETTLE_MS + TRAILING_GUARD_MS + MIN_SKIP_MS)
11
+ return [];
12
+ const keep = [
13
+ [0, Math.min(durationMs, LEADING_SETTLE_MS)],
14
+ [Math.max(0, durationMs - TRAILING_GUARD_MS), durationMs],
15
+ ];
16
+ for (const window of dynamicWindows) {
17
+ const start = Math.max(0, Math.min(durationMs, window.start_ms) - TRAILING_GUARD_MS);
18
+ const end = Math.min(durationMs, Math.max(window.start_ms, window.end_ms) + LEADING_SETTLE_MS);
19
+ keep.push([start, end]);
20
+ }
21
+ for (const point of checkpoints) {
22
+ if (!Number.isFinite(point))
23
+ continue;
24
+ const start = Math.max(0, point - CHECKPOINT_TRAILING_MS);
25
+ const end = Math.min(durationMs, point + CHECKPOINT_LEADING_MS);
26
+ keep.push([start, end]);
27
+ }
28
+ keep.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
29
+ const merged = [];
30
+ for (const interval of keep) {
31
+ const last = merged[merged.length - 1];
32
+ if (!last || interval[0] > last[1])
33
+ merged.push([interval[0], interval[1]]);
34
+ else if (interval[1] > last[1])
35
+ last[1] = interval[1];
36
+ }
37
+ const skips = [];
38
+ for (let i = 0; i < merged.length - 1; i++) {
39
+ const start = merged[i][1];
40
+ const end = merged[i + 1][0];
41
+ const skip = end - start;
42
+ if (skip >= MIN_SKIP_MS) {
43
+ skips.push({ schedule_start_ms: start, schedule_end_ms: end, skip_ms: skip });
44
+ }
45
+ }
46
+ return skips;
47
+ }
48
+ export async function remapCaptureTimestamps(file, offsetMs, skips) {
49
+ const valid = skips
50
+ .filter(skip => Number.isFinite(skip.record_at_ms) && skip.record_at_ms >= 0 && Number.isFinite(skip.skip_ms) && skip.skip_ms > 0)
51
+ .sort((a, b) => a.record_at_ms - b.record_at_ms);
52
+ if (!valid.length)
53
+ return;
54
+ const terms = valid.map(skip => {
55
+ const thresholdSec = ((offsetMs + skip.record_at_ms) / 1000).toFixed(6);
56
+ const skipSec = (skip.skip_ms / 1000).toFixed(6);
57
+ return `if(gte(TS*TB,${thresholdSec}),${skipSec},0)`;
58
+ });
59
+ const bsf = `setts=ts='TS+(${terms.join('+')})/TB'`;
60
+ const temporary = join(dirname(file), `.remapped-${Date.now()}${extname(file)}`);
61
+ try {
62
+ await execute('ffmpeg', ['-v', 'error', '-xerror', '-y', '-i', file, '-c:v', 'copy', '-bsf:v', bsf, temporary]);
63
+ await rename(temporary, file);
64
+ }
65
+ catch (error) {
66
+ await rm(temporary, { force: true }).catch(() => { });
67
+ throw error;
68
+ }
69
+ }
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import { nativePreview } from './powerpoint-preview.js';
7
7
  import { defaultVideoOutput, defaultViewport } from '../contracts.js';
8
8
  import { geometryRequests } from '../annotation-paint.js';
9
+ import { planStaticSkips, remapCaptureTimestamps } from './capture-compression.js';
9
10
  import { calibrate, estimateOrigin } from '../calibration.js';
10
11
  import { executionSignal, hasStageDeadline, hashFile, json, probe, saveJson, videoFramePeriod } from '../media.js';
11
12
  import { ProductionError, requireCondition } from '../errors.js';
@@ -119,6 +120,12 @@ function parseEvidence(value, directory, verified, requests, output) {
119
120
  requireCondition(object(marker) && marker.color === colors[index] && finite(marker.observed_ms) && finite(marker.rendered_by_ms) && finite(marker.paint_interval_ms) && marker.rendered_by_ms >= marker.observed_ms && marker.paint_interval_ms >= 0, 'POWERPOINT_PROTOCOL', 'Native marker has no measured paint interval', 6);
120
121
  for (const reference of value.references)
121
122
  requireCondition(object(reference) && typeof reference.id === 'string' && finite(reference.expected_ms) && typeof reference.before === 'string' && typeof reference.after === 'string' && ['transition', 'sample'].includes(String(reference.mode)) && finite(reference.frame_period_ms), 'POWERPOINT_PROTOCOL', 'Native verification returned an invalid reference', 6);
123
+ if (value.applied_skips !== undefined) {
124
+ requireCondition(Array.isArray(value.applied_skips), 'POWERPOINT_PROTOCOL', 'Native recording returned invalid static skip evidence', 5);
125
+ for (const skip of value.applied_skips) {
126
+ requireCondition(object(skip) && finite(skip.record_at_ms) && Number(skip.record_at_ms) >= 0 && finite(skip.skip_ms) && Number(skip.skip_ms) > 0, 'POWERPOINT_PROTOCOL', 'Native recording returned an invalid static skip entry', 5);
127
+ }
128
+ }
122
129
  for (const version of Object.values(value.dependencies))
123
130
  requireCondition(typeof version === 'string', 'POWERPOINT_PROTOCOL', 'Native recording returned invalid dependency versions', 5);
124
131
  return value;
@@ -513,8 +520,11 @@ export class PowerPointAdapter {
513
520
  });
514
521
  const request = join(directory, 'request.json');
515
522
  const geometry_requests = geometryRequests(schedule).map(item => ({ ...item, native_id: this.slide(item.slide).native_id }));
523
+ const static_skips = mode === 'record' && !verifyTiming
524
+ ? planStaticSkips(operations.map(operation => ({ start_ms: operation.at_ms, end_ms: operation.end_ms })), geometry_requests.flatMap(item => [item.start_ms, item.end_ms]), schedule.duration_ms)
525
+ : [];
516
526
  const capture = mode === 'record' ? { ffmpeg: executable('ffmpeg'), ffprobe: executable('ffprobe') } : {};
517
- await saveJson(request, { version: 1, mode, directory, deck: story.deck, deck_sha256: this.deck.deck_sha256, parent_pid: process.pid, operations, geometry_requests, media, output, duration_ms: schedule.duration_ms, verify_timing: verifyTiming, ...capture });
527
+ await saveJson(request, { version: 1, mode, directory, deck: story.deck, deck_sha256: this.deck.deck_sha256, parent_pid: process.pid, operations, geometry_requests, media, output, duration_ms: schedule.duration_ms, verify_timing: verifyTiming, static_skips, ...capture });
518
528
  this.session = new NativeSession(directory, request);
519
529
  await this.session.waitFor('prepared.json', hasStageDeadline() ? undefined : 120000);
520
530
  }
@@ -528,7 +538,12 @@ export class PowerPointAdapter {
528
538
  requireCondition(properties.width === production.output.width && properties.height === production.output.height && !properties.has_audio, 'CAPTURE_DIMENSIONS', 'Native capture must contain the requested audience dimensions and no audio', 5);
529
539
  progress?.(production.verify_timing ? 'Verifying captured timing' : 'Locating capture origin; per-cue timing verification skipped');
530
540
  const timing = production.verify_timing ? await calibrate(observed.file, observed.markers, observed.references, schedule.duration_ms, directory) : await estimateOrigin(observed.file, observed.markers, schedule.duration_ms, directory);
531
- const visual = { version: 1, file: observed.file, properties, events: observed.events, ...(observed.annotation_geometry.length ? { annotation_geometry: observed.annotation_geometry } : {}), origin: { method: production.verify_timing ? 'decoded_markers' : 'opening_markers', uncertainty_ms: timing.uncertainty_ms, mapping: timing.mapping }, timing, provenance: { adapter: this.id, version: this.version, dependencies: observed.dependencies } };
541
+ let finalProperties = properties;
542
+ if (!production.verify_timing && observed.applied_skips?.length) {
543
+ await remapCaptureTimestamps(observed.file, timing.mapping.offset_ms, observed.applied_skips);
544
+ finalProperties = await probe(observed.file);
545
+ }
546
+ const visual = { version: 1, file: observed.file, properties: finalProperties, events: observed.events, ...(observed.annotation_geometry.length ? { annotation_geometry: observed.annotation_geometry } : {}), origin: { method: production.verify_timing ? 'decoded_markers' : 'opening_markers', uncertainty_ms: timing.uncertainty_ms, mapping: timing.mapping }, timing, provenance: { adapter: this.id, version: this.version, dependencies: observed.dependencies } };
532
547
  await saveJson(join(directory, 'visual.json'), visual);
533
548
  requireCondition(!production.verify_timing || timing.status === 'accepted', 'TIMING_ACCEPTANCE', 'Native capture completed but decoded timing evidence failed. See calibration.json.', 6);
534
549
  return visual;
@@ -8,6 +8,7 @@ import { dirname, join, resolve } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { defaultVideoOutput } from '../contracts.js';
10
10
  import { geometryRequests } from '../annotation-paint.js';
11
+ import { planStaticSkips, remapCaptureTimestamps } from './capture-compression.js';
11
12
  import { inspectSlidev, validateSlidev } from './slidev-inspection.js';
12
13
  import { calibrate, estimateOrigin } from '../calibration.js';
13
14
  import { execute, probe, saveJson, hashFile, digest, videoFramePeriod, executionSignal } from '../media.js';
@@ -156,9 +157,351 @@ export class SlidevAdapter {
156
157
  this.page = await this.browser.newPage({ viewport: { width: viewport.width, height: viewport.height }, deviceScaleFactor: 1, acceptDownloads: false });
157
158
  this.page.setDefaultNavigationTimeout(120000);
158
159
  this.page.on('pageerror', error => { this.log += `\nBrowser error: ${error.message}`; });
160
+ const inFlightRequests = new Set();
161
+ const serverOrigin = new URL(url).origin;
162
+ const isInternalCaptureRequest = (requestUrl) => {
163
+ try {
164
+ const parsed = new URL(requestUrl);
165
+ return parsed.origin === serverOrigin && (parsed.pathname === '/__slidevideo_capture' || parsed.pathname === '/__slidevideo_preview');
166
+ }
167
+ catch {
168
+ return false;
169
+ }
170
+ };
171
+ this.page.on('request', request => {
172
+ if (!isInternalCaptureRequest(request.url()))
173
+ inFlightRequests.add(request);
174
+ });
175
+ this.page.on('requestfinished', request => { inFlightRequests.delete(request); });
176
+ this.page.on('requestfailed', request => { inFlightRequests.delete(request); });
177
+ await this.page.exposeFunction('__slidevideoHasInFlightRequests', () => inFlightRequests.size > 0);
159
178
  await this.page.addInitScript(() => {
160
179
  localStorage.setItem('slidev-camera', 'none');
161
180
  localStorage.setItem('slidev-mic', 'none');
181
+ const nativeSetTimeout = window.setTimeout.bind(window);
182
+ const nativeClearTimeout = window.clearTimeout.bind(window);
183
+ const nativeSetInterval = window.setInterval.bind(window);
184
+ const nativeClearInterval = window.clearInterval.bind(window);
185
+ const nativeRequestAnimationFrame = window.requestAnimationFrame.bind(window);
186
+ const nativeCancelAnimationFrame = window.cancelAnimationFrame.bind(window);
187
+ const pendingTimeouts = new Set();
188
+ const stringTimeoutCleanups = new Map();
189
+ const activeIntervals = new Set();
190
+ const pendingAnimationFrames = new Set();
191
+ const pendingIdleCallbacks = new Set();
192
+ const activeExternalSources = new Set();
193
+ const shadowHosts = new WeakSet();
194
+ let pendingAsync = 0;
195
+ if (typeof Element !== 'undefined' && typeof Element.prototype.attachShadow === 'function') {
196
+ const nativeAttachShadow = Element.prototype.attachShadow;
197
+ Element.prototype.attachShadow = function (init) {
198
+ shadowHosts.add(this);
199
+ return nativeAttachShadow.call(this, init);
200
+ };
201
+ }
202
+ const isFrameworkCaller = () => {
203
+ const frames = (new Error().stack ?? '').split('\n').slice(1).map(line => line.trim());
204
+ const caller = frames[2] ?? '';
205
+ return /\/@vite\/client|\/node_modules\/(?:@slidev\/|vue\/|@vue\/|\.vite\/deps\/(?:vue|vue-router|@vue_[^/?]+|@slidev_[^/?]+)\.js(?:[?:#]|$))|\/addons\/slidevideo\//.test(caller);
206
+ };
207
+ let internalDepth = 0;
208
+ window.setTimeout = ((handler, timeout, ...args) => {
209
+ if (internalDepth > 0 || isFrameworkCaller())
210
+ return nativeSetTimeout(handler, timeout, ...args);
211
+ let id = 0;
212
+ if (typeof handler === 'function') {
213
+ const wrapped = (...cbArgs) => { pendingTimeouts.delete(id); return handler.apply(window, cbArgs); };
214
+ id = nativeSetTimeout(wrapped, timeout, ...args);
215
+ pendingTimeouts.add(id);
216
+ }
217
+ else {
218
+ id = nativeSetTimeout(handler, timeout, ...args);
219
+ pendingTimeouts.add(id);
220
+ const delay = Math.max(0, Number(timeout) || 0) + 50;
221
+ const cleanupId = nativeSetTimeout(() => { pendingTimeouts.delete(id); stringTimeoutCleanups.delete(id); }, delay);
222
+ stringTimeoutCleanups.set(id, cleanupId);
223
+ }
224
+ return id;
225
+ });
226
+ const clearTrackedTimer = (id) => {
227
+ if (id === undefined || id === null)
228
+ return;
229
+ const numericId = Number(id);
230
+ if (!Number.isFinite(numericId))
231
+ return;
232
+ pendingTimeouts.delete(numericId);
233
+ activeIntervals.delete(numericId);
234
+ const cleanupId = stringTimeoutCleanups.get(numericId);
235
+ if (cleanupId !== undefined) {
236
+ nativeClearTimeout(cleanupId);
237
+ stringTimeoutCleanups.delete(numericId);
238
+ }
239
+ };
240
+ window.clearTimeout = ((id) => {
241
+ clearTrackedTimer(id);
242
+ return nativeClearTimeout(id);
243
+ });
244
+ window.setInterval = ((handler, timeout, ...args) => {
245
+ if (internalDepth > 0 || isFrameworkCaller())
246
+ return nativeSetInterval(handler, timeout, ...args);
247
+ const id = nativeSetInterval(handler, timeout, ...args);
248
+ activeIntervals.add(id);
249
+ return id;
250
+ });
251
+ window.clearInterval = ((id) => {
252
+ clearTrackedTimer(id);
253
+ return nativeClearInterval(id);
254
+ });
255
+ window.requestAnimationFrame = ((callback) => {
256
+ if (internalDepth > 0 || isFrameworkCaller())
257
+ return nativeRequestAnimationFrame(callback);
258
+ let id = 0;
259
+ id = nativeRequestAnimationFrame((time) => {
260
+ pendingAnimationFrames.delete(id);
261
+ return callback(time);
262
+ });
263
+ pendingAnimationFrames.add(id);
264
+ return id;
265
+ });
266
+ window.cancelAnimationFrame = ((id) => {
267
+ const numericId = Number(id);
268
+ if (Number.isFinite(numericId))
269
+ pendingAnimationFrames.delete(numericId);
270
+ return nativeCancelAnimationFrame(id);
271
+ });
272
+ if (typeof window.requestIdleCallback === 'function' && typeof window.cancelIdleCallback === 'function') {
273
+ const nativeRequestIdleCallback = window.requestIdleCallback.bind(window);
274
+ const nativeCancelIdleCallback = window.cancelIdleCallback.bind(window);
275
+ window.requestIdleCallback = ((callback, options) => {
276
+ if (internalDepth > 0 || isFrameworkCaller())
277
+ return nativeRequestIdleCallback(callback, options);
278
+ let id = 0;
279
+ id = nativeRequestIdleCallback((deadline) => {
280
+ pendingIdleCallbacks.delete(id);
281
+ return callback(deadline);
282
+ }, options);
283
+ pendingIdleCallbacks.add(id);
284
+ return id;
285
+ });
286
+ window.cancelIdleCallback = ((id) => {
287
+ const numericId = Number(id);
288
+ if (Number.isFinite(numericId))
289
+ pendingIdleCallbacks.delete(numericId);
290
+ return nativeCancelIdleCallback(id);
291
+ });
292
+ }
293
+ if (typeof window.fetch === 'function') {
294
+ const nativeFetch = window.fetch.bind(window);
295
+ const bodyMethods = ['arrayBuffer', 'blob', 'bytes', 'formData', 'json', 'text'];
296
+ const trackStream = (stream) => {
297
+ if (!stream)
298
+ return;
299
+ const record = stream;
300
+ if (typeof record.getReader === 'function') {
301
+ const origGetReader = record.getReader.bind(stream);
302
+ record.getReader = (...readerArgs) => {
303
+ const reader = origGetReader(...readerArgs);
304
+ if (reader && typeof reader.read === 'function') {
305
+ const origRead = reader.read.bind(reader);
306
+ reader.read = (...readArgs) => {
307
+ pendingAsync++;
308
+ return Promise.resolve(origRead(...readArgs)).finally(() => { pendingAsync--; });
309
+ };
310
+ }
311
+ return reader;
312
+ };
313
+ }
314
+ if (typeof record.pipeTo === 'function') {
315
+ const origPipeTo = record.pipeTo.bind(stream);
316
+ record.pipeTo = (...pipeArgs) => {
317
+ pendingAsync++;
318
+ return Promise.resolve(origPipeTo(...pipeArgs)).finally(() => { pendingAsync--; });
319
+ };
320
+ }
321
+ if (typeof record.pipeThrough === 'function') {
322
+ const origPipeThrough = record.pipeThrough.bind(stream);
323
+ record.pipeThrough = (...pipeArgs) => {
324
+ const derived = origPipeThrough(...pipeArgs);
325
+ trackStream(derived);
326
+ return derived;
327
+ };
328
+ }
329
+ if (typeof record.tee === 'function') {
330
+ const origTee = record.tee.bind(stream);
331
+ record.tee = () => {
332
+ const branches = origTee();
333
+ for (const branch of branches)
334
+ trackStream(branch);
335
+ return branches;
336
+ };
337
+ }
338
+ for (const key of [Symbol.asyncIterator, 'values']) {
339
+ if (typeof record[key] !== 'function')
340
+ continue;
341
+ const origIter = record[key].bind(stream);
342
+ record[key] = (...iterArgs) => {
343
+ const iterator = origIter(...iterArgs);
344
+ if (iterator && typeof iterator.next === 'function') {
345
+ const origNext = iterator.next.bind(iterator);
346
+ iterator.next = () => {
347
+ pendingAsync++;
348
+ return Promise.resolve(origNext()).finally(() => { pendingAsync--; });
349
+ };
350
+ }
351
+ return iterator;
352
+ };
353
+ }
354
+ };
355
+ const trackResponse = (response) => {
356
+ const record = response;
357
+ for (const method of bodyMethods) {
358
+ const orig = record[method];
359
+ if (typeof orig !== 'function')
360
+ continue;
361
+ record[method] = function (...bodyArgs) {
362
+ pendingAsync++;
363
+ return Promise.resolve(orig.apply(this, bodyArgs)).finally(() => { pendingAsync--; });
364
+ };
365
+ }
366
+ if (typeof record.clone === 'function') {
367
+ const origClone = record.clone.bind(response);
368
+ record.clone = () => trackResponse(origClone());
369
+ }
370
+ trackStream(response.body);
371
+ return response;
372
+ };
373
+ const isInternalEndpoint = (requestUrl) => {
374
+ try {
375
+ const parsed = new URL(requestUrl, location.href);
376
+ return parsed.origin === location.origin && (parsed.pathname === '/__slidevideo_capture' || parsed.pathname === '/__slidevideo_preview');
377
+ }
378
+ catch {
379
+ return false;
380
+ }
381
+ };
382
+ window.fetch = ((input, init) => {
383
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
384
+ if (internalDepth > 0 || isInternalEndpoint(url) || isFrameworkCaller())
385
+ return nativeFetch(input, init);
386
+ pendingAsync++;
387
+ return nativeFetch(input, init).then(trackResponse).finally(() => { pendingAsync--; });
388
+ });
389
+ }
390
+ if (typeof XMLHttpRequest !== 'undefined') {
391
+ const nativeSend = XMLHttpRequest.prototype.send;
392
+ XMLHttpRequest.prototype.send = function (body) {
393
+ if (internalDepth === 0 && !isFrameworkCaller()) {
394
+ let settled = false;
395
+ const release = () => { if (!settled) {
396
+ settled = true;
397
+ pendingAsync--;
398
+ } };
399
+ pendingAsync++;
400
+ this.addEventListener('loadend', release, { once: true });
401
+ try {
402
+ return nativeSend.call(this, body);
403
+ }
404
+ catch (error) {
405
+ this.removeEventListener('loadend', release);
406
+ release();
407
+ throw error;
408
+ }
409
+ }
410
+ return nativeSend.call(this, body);
411
+ };
412
+ }
413
+ if (typeof IDBFactory !== 'undefined') {
414
+ for (const method of ['open', 'deleteDatabase']) {
415
+ const orig = IDBFactory.prototype[method];
416
+ if (typeof orig !== 'function')
417
+ continue;
418
+ IDBFactory.prototype[method] = function (...idbArgs) {
419
+ const request = orig.apply(this, idbArgs);
420
+ if (!isFrameworkCaller() && request && typeof request.addEventListener === 'function') {
421
+ let settled = false;
422
+ const release = () => { if (!settled) {
423
+ settled = true;
424
+ pendingAsync--;
425
+ } };
426
+ pendingAsync++;
427
+ request.addEventListener('success', release, { once: true });
428
+ request.addEventListener('error', release, { once: true });
429
+ }
430
+ return request;
431
+ };
432
+ }
433
+ }
434
+ if (typeof IDBDatabase !== 'undefined' && typeof IDBDatabase.prototype.transaction === 'function') {
435
+ const origTx = IDBDatabase.prototype.transaction;
436
+ IDBDatabase.prototype.transaction = function (...txArgs) {
437
+ const tx = origTx.apply(this, txArgs);
438
+ if (!isFrameworkCaller() && tx && typeof tx.addEventListener === 'function') {
439
+ let settled = false;
440
+ const release = () => { if (!settled) {
441
+ settled = true;
442
+ pendingAsync--;
443
+ } };
444
+ pendingAsync++;
445
+ tx.addEventListener('complete', release, { once: true });
446
+ tx.addEventListener('abort', release, { once: true });
447
+ tx.addEventListener('error', release, { once: true });
448
+ }
449
+ return tx;
450
+ };
451
+ }
452
+ for (const name of ['Worker', 'WebSocket', 'EventSource']) {
453
+ const NativeCtor = window[name];
454
+ if (typeof NativeCtor !== 'function')
455
+ continue;
456
+ window[name] = new Proxy(NativeCtor, {
457
+ construct(target, args, newTarget) {
458
+ const track = !isFrameworkCaller();
459
+ const instance = Reflect.construct(target, args, newTarget);
460
+ if (track) {
461
+ activeExternalSources.add(instance);
462
+ const release = () => { activeExternalSources.delete(instance); };
463
+ if (name === 'Worker' && typeof instance.terminate === 'function') {
464
+ const orig = instance.terminate.bind(instance);
465
+ instance.terminate = () => { release(); return orig(); };
466
+ }
467
+ if (name === 'EventSource' && typeof instance.close === 'function') {
468
+ const orig = instance.close.bind(instance);
469
+ instance.close = (...closeArgs) => { release(); return orig(...closeArgs); };
470
+ }
471
+ if (name === 'WebSocket' && typeof instance.addEventListener === 'function') {
472
+ instance.addEventListener('close', release, { once: true });
473
+ }
474
+ }
475
+ return instance;
476
+ },
477
+ });
478
+ }
479
+ window.__slidevideoTimers = {
480
+ hasPending: () => pendingTimeouts.size > 0 || activeIntervals.size > 0 || pendingAnimationFrames.size > 0 || pendingIdleCallbacks.size > 0 || pendingAsync > 0 || activeExternalSources.size > 0,
481
+ hasShadowHost: (root) => {
482
+ if (root.shadowRoot || shadowHosts.has(root))
483
+ return true;
484
+ for (const element of root.querySelectorAll('*')) {
485
+ if (element.shadowRoot || shadowHosts.has(element))
486
+ return true;
487
+ }
488
+ return false;
489
+ },
490
+ setInternalTimeout: (callback, ms) => { internalDepth++; try {
491
+ return nativeSetTimeout(callback, ms);
492
+ }
493
+ finally {
494
+ internalDepth--;
495
+ } },
496
+ clearInternalTimeout: id => nativeClearTimeout(id),
497
+ setInternalInterval: (callback, ms) => { internalDepth++; try {
498
+ return nativeSetInterval(callback, ms);
499
+ }
500
+ finally {
501
+ internalDepth--;
502
+ } },
503
+ clearInternalInterval: id => nativeClearInterval(id),
504
+ };
162
505
  });
163
506
  await this.page.goto(`${url}/1?slidevideo=1`);
164
507
  await this.page.waitForFunction(() => Boolean(window.__slidevideo), { timeout: 120000 });
@@ -390,9 +733,20 @@ export class SlidevAdapter {
390
733
  try {
391
734
  progress?.('Recording presentation');
392
735
  const page = this.page;
736
+ const plannedSkips = this.production.verify_timing
737
+ ? []
738
+ : planStaticSkips(this.schedule.actions.reduce((windows, item) => {
739
+ if (item.action.type === 'slide' || item.action.type === 'reveal') {
740
+ windows.push({ start_ms: item.start_ms, end_ms: item.start_ms + Math.max(0, item.action.duration_ms) });
741
+ }
742
+ else if (item.action.type === 'play') {
743
+ windows.push({ start_ms: item.start_ms, end_ms: item.end_ms });
744
+ }
745
+ return windows;
746
+ }, []), geometryRequests(this.schedule).flatMap(request => [request.start_ms, request.end_ms]), this.schedule.duration_ms);
393
747
  let playbackError;
394
748
  try {
395
- await page.evaluate(verify => window.__slidevideo.play(verify), this.production.verify_timing);
749
+ await page.evaluate(({ verify, skips }) => window.__slidevideo.play(verify, skips), { verify: this.production.verify_timing, skips: plannedSkips });
396
750
  }
397
751
  catch (error) {
398
752
  playbackError = error;
@@ -403,7 +757,7 @@ export class SlidevAdapter {
403
757
  }
404
758
  let observed;
405
759
  try {
406
- observed = await page.evaluate(() => ({ events: window.__slidevideo.state.events, markers: window.__slidevideo.state.markers, failure: window.__slidevideo.state.failure, annotation_geometry: window.__slidevideo.state.annotation_geometry }));
760
+ observed = await page.evaluate(() => ({ events: window.__slidevideo.state.events, markers: window.__slidevideo.state.markers, failure: window.__slidevideo.state.failure, annotation_geometry: window.__slidevideo.state.annotation_geometry, applied_skips: window.__slidevideo.state.applied_skips }));
407
761
  }
408
762
  catch (error) {
409
763
  if (!playbackError)
@@ -466,7 +820,12 @@ export class SlidevAdapter {
466
820
  const timing = this.production.verify_timing
467
821
  ? await calibrate(file, observed.markers, this.references, this.schedule.duration_ms, this.directory)
468
822
  : await estimateOrigin(file, observed.markers, this.schedule.duration_ms, this.directory);
469
- const visual = { version: 1, file, ...(expectedGeometry ? { annotation_geometry: observed.annotation_geometry ?? [] } : {}), properties, events: observed.events, origin: { method: this.production.verify_timing ? 'decoded_markers' : 'opening_markers', uncertainty_ms: timing.uncertainty_ms, mapping: timing.mapping }, timing, provenance: { adapter: this.id, version: this.version, dependencies: { chromium: this.browser.version(), slidev: '53.1.0', playwright: '1.65.1' } } };
823
+ let finalProperties = properties;
824
+ if (!this.production.verify_timing && observed.applied_skips?.length) {
825
+ await remapCaptureTimestamps(file, timing.mapping.offset_ms, observed.applied_skips);
826
+ finalProperties = await probe(file);
827
+ }
828
+ const visual = { version: 1, file, ...(expectedGeometry ? { annotation_geometry: observed.annotation_geometry ?? [] } : {}), properties: finalProperties, events: observed.events, origin: { method: this.production.verify_timing ? 'decoded_markers' : 'opening_markers', uncertainty_ms: timing.uncertainty_ms, mapping: timing.mapping }, timing, provenance: { adapter: this.id, version: this.version, dependencies: { chromium: this.browser.version(), slidev: '53.1.0', playwright: '1.65.1' } } };
470
829
  await saveJson(join(this.directory, 'visual.json'), visual);
471
830
  requireCondition(!this.production.verify_timing || timing.status === 'accepted', 'TIMING_ACCEPTANCE', 'Capture completed but decoded timing evidence failed. See calibration.json.', 6);
472
831
  return visual;
package/dist/speech.js CHANGED
@@ -118,7 +118,7 @@ export async function generateSpeech(story, directory, adapters, cache, progress
118
118
  const cachedAudio = speechPath(resolve(cache), key, asset.format);
119
119
  await mkdir(resolve(cache), { recursive: true });
120
120
  await copyFile(asset.audio, cachedAudio);
121
- await saveJson(cached, { ...asset, audio: cachedAudio });
121
+ await saveJson(cached, { ...asset, audio: `${key}.${asset.format}` });
122
122
  }
123
123
  }
124
124
  assets.push(asset);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slidevideo/cli",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Turn a slide deck into a narrated video.",
5
5
  "license": "SEE LICENSE IN LICENSE-TERMS.md",
6
6
  "type": "module",
@@ -33,6 +33,8 @@
33
33
  "addons/slidevideo/preview.ts",
34
34
  "dist/adapters/browser-runtime.d.ts",
35
35
  "dist/adapters/browser-runtime.js",
36
+ "dist/adapters/capture-compression.d.ts",
37
+ "dist/adapters/capture-compression.js",
36
38
  "dist/adapters/edge.d.ts",
37
39
  "dist/adapters/edge.js",
38
40
  "dist/adapters/elevenlabs.d.ts",
@@ -37,6 +37,10 @@ $locked = $false
37
37
  $createdApplication = $false
38
38
  $clock = [Diagnostics.Stopwatch]::StartNew()
39
39
  $origin = 0.0
40
+ $skippedMs = 0.0
41
+ $plannedSkips = @()
42
+ $nextSkipIndex = 0
43
+ $appliedSkips = [Collections.Generic.List[object]]::new()
40
44
  $events = [Collections.Generic.List[object]]::new()
41
45
  $markers = [Collections.Generic.List[object]]::new()
42
46
  $references = [Collections.Generic.List[object]]::new()
@@ -71,6 +75,9 @@ function Check-Cancel {
71
75
  if ($null -ne $parentStartedTicks -and $parent.StartTime.ToUniversalTime().Ticks -ne $parentStartedTicks) { Fail 'INTERRUPTED' 'The CLI process identity changed.' }
72
76
  }
73
77
  }
78
+ function Schedule-Now {
79
+ return ($clock.Elapsed.TotalMilliseconds - $origin) + $script:skippedMs
80
+ }
74
81
  function Wait-Until([double]$deadline) {
75
82
  while ($clock.Elapsed.TotalMilliseconds -lt $deadline) {
76
83
  Check-Cancel
@@ -80,7 +87,41 @@ function Wait-Until([double]$deadline) {
80
87
  $remaining = $deadline - $clock.Elapsed.TotalMilliseconds
81
88
  if ($collectAnnotations) {
82
89
  foreach ($monitor in $annotationMonitors) {
83
- if (!$monitor.complete) { $remaining = [Math]::Min($remaining, $origin + $monitor.next_sample_ms - $clock.Elapsed.TotalMilliseconds) }
90
+ if (!$monitor.complete) { $remaining = [Math]::Min($remaining, $monitor.next_sample_ms - (Schedule-Now)) }
91
+ }
92
+ }
93
+ if ($remaining -gt 4) { Start-Sleep -Milliseconds ([Math]::Min(20, [int]($remaining - 1))) }
94
+ else { [Threading.Thread]::Sleep(1) }
95
+ }
96
+ if ($collectAnnotations) { Check-Annotations }
97
+ }
98
+ function Wait-UntilSchedule([double]$targetMs) {
99
+ while ((Schedule-Now) -lt $targetMs) {
100
+ Check-Cancel
101
+ if ($null -ne $recorder -and $recorder.HasExited) { Fail 'POWERPOINT_CAPTURE' 'FFmpeg exited during native playback.' }
102
+ if ($activeMedia.Count -gt 0) { Check-Media }
103
+ if ($collectAnnotations) { Check-Annotations }
104
+ $now = Schedule-Now
105
+ if ($now -ge $targetMs) { break }
106
+ if ($script:nextSkipIndex -lt $script:plannedSkips.Count) {
107
+ $nextSkip = $script:plannedSkips[$script:nextSkipIndex]
108
+ if ([double]$nextSkip.schedule_start_ms -le $targetMs -and $now -ge [double]$nextSkip.schedule_start_ms) {
109
+ $script:nextSkipIndex++
110
+ $remainingSkip = [double]$nextSkip.schedule_end_ms - (Schedule-Now)
111
+ if ($remainingSkip -gt 0) {
112
+ $appliedSkips.Add(@{ record_at_ms = ($clock.Elapsed.TotalMilliseconds - $origin); skip_ms = $remainingSkip })
113
+ $script:skippedMs += $remainingSkip
114
+ }
115
+ continue
116
+ }
117
+ }
118
+ $remaining = $targetMs - $now
119
+ if ($script:nextSkipIndex -lt $script:plannedSkips.Count -and [double]$script:plannedSkips[$script:nextSkipIndex].schedule_start_ms -le $targetMs) {
120
+ $remaining = [Math]::Min($remaining, [double]$script:plannedSkips[$script:nextSkipIndex].schedule_start_ms - $now)
121
+ }
122
+ if ($collectAnnotations) {
123
+ foreach ($monitor in $annotationMonitors) {
124
+ if (!$monitor.complete) { $remaining = [Math]::Min($remaining, $monitor.next_sample_ms - $now) }
84
125
  }
85
126
  }
86
127
  if ($remaining -gt 4) { Start-Sleep -Milliseconds ([Math]::Min(20, [int]($remaining - 1))) }
@@ -243,9 +284,12 @@ function Find-ShapeById($shapes, [int]$targetId, [bool]$ancestorInvalid = $false
243
284
  }
244
285
  return @($found.ToArray())
245
286
  }
246
- function Inspect-Shapes($slide, $shapes, $package, [bool]$ancestorTransformed, [int]$ancestorVisibleFromClick = 0, [string[]]$ancestorAnimReasons = @()) {
287
+ function Inspect-Shapes([int]$slideId, [double]$slideWidth, [double]$slideHeight, $shapes, $targetsByKey, $effectsByShape, [bool]$ancestorTransformed, [int]$ancestorVisibleFromClick = 0, [string[]]$ancestorAnimReasons = @()) {
247
288
  foreach ($shape in $shapes) {
248
289
  Check-Cancel
290
+ $shapeId = [int]$shape.Id
291
+ $shapeName = [string]$shape.Name
292
+ $shapeType = [int]$shape.Type
249
293
  $reasons = [Collections.Generic.List[string]]::new()
250
294
  $animReasons = [Collections.Generic.List[string]]::new()
251
295
  $bounds = @{ x = 0.0; y = 0.0; width = 0.0; height = 0.0 }
@@ -256,7 +300,8 @@ function Inspect-Shapes($slide, $shapes, $package, [bool]$ancestorTransformed, [
256
300
  $animReasons.Add($inherited)
257
301
  }
258
302
  try {
259
- $metadata = @($package.targets | Where-Object { $_.native_id -eq $slide.SlideID -and $_.id -eq $shape.Id })
303
+ $targetKey = [string]$slideId + ':' + [string]$shapeId
304
+ $metadata = $(if ($targetsByKey.ContainsKey($targetKey)) { @($targetsByKey[$targetKey].ToArray()) } else { @() })
260
305
  if ($metadata.Count -ne 1) { $reasons.Add('shape identity is absent or ambiguous in the original slide package') }
261
306
  else {
262
307
  foreach ($reason in $metadata[0].unsupported) {
@@ -269,20 +314,21 @@ function Inspect-Shapes($slide, $shapes, $package, [bool]$ancestorTransformed, [
269
314
  if ([int]$shape.Visible -ne -1) { $reasons.Add('hidden shape'); $isTransformed = $true }
270
315
  if ([Math]::Abs([double]$shape.Rotation % 360) -gt 0.001 -or [int]$shape.ThreeD.Visible -ne 0) { $reasons.Add('rotated or three-dimensional shape'); $isTransformed = $true }
271
316
  if ([int]$shape.HorizontalFlip -ne 0 -or [int]$shape.VerticalFlip -ne 0) { $reasons.Add('flipped shape'); $isTransformed = $true }
272
- $bounds = @{ x = [double]$shape.Left / $presentation.PageSetup.SlideWidth; y = [double]$shape.Top / $presentation.PageSetup.SlideHeight; width = [double]$shape.Width / $presentation.PageSetup.SlideWidth; height = [double]$shape.Height / $presentation.PageSetup.SlideHeight }
317
+ $bounds = @{ x = [double]$shape.Left / $slideWidth; y = [double]$shape.Top / $slideHeight; width = [double]$shape.Width / $slideWidth; height = [double]$shape.Height / $slideHeight }
273
318
  if ($bounds.width -le 0 -or $bounds.height -le 0 -or $bounds.x -lt 0 -or $bounds.y -lt 0 -or $bounds.x + $bounds.width -gt 1.000001 -or $bounds.y + $bounds.height -gt 1.000001) { $reasons.Add('degenerate shape or shape clipped by slide bounds') }
274
- foreach ($effect in $slide.TimeLine.MainSequence) {
275
- if ([int]$effect.Shape.Id -ne [int]$shape.Id) { continue }
276
- if ([int]$effect.Exit -ne 0 -or [int]$effect.Timing.TriggerType -notin @(1, 2, 3) -or [int]$effect.Paragraph -gt 0 -or [int]$effect.EffectInformation.AfterEffect -ne 0 -or [double]$effect.Timing.RepeatCount -lt 0 -or [double]$effect.Timing.RepeatCount -gt 100 -or [double]$effect.Timing.RepeatDuration -lt 0) {
277
- $reason = 'exited, partial-text, hidden-after-animation or unbounded animated target'
278
- $reasons.Add($reason)
279
- $animReasons.Add($reason)
319
+ if ($effectsByShape.ContainsKey($shapeId)) {
320
+ foreach ($effect in $effectsByShape[$shapeId]) {
321
+ if ([int]$effect.exit -ne 0 -or [int]$effect.trigger -notin @(1, 2, 3) -or [int]$effect.paragraph -gt 0 -or [int]$effect.after_effect -ne 0 -or [double]$effect.repeat_count -lt 0 -or [double]$effect.repeat_count -gt 100 -or [double]$effect.repeat_duration_ms -lt 0) {
322
+ $reason = 'exited, partial-text, hidden-after-animation or unbounded animated target'
323
+ $reasons.Add($reason)
324
+ $animReasons.Add($reason)
325
+ }
280
326
  }
281
327
  }
282
328
  } catch { $reasons.Add('native target geometry is unavailable: ' + $_.Exception.Message) }
283
329
  $children = @()
284
- if ([int]$shape.Type -eq 6) {
285
- $children = @(Inspect-Shapes $slide $shape.GroupItems $package $isTransformed $visibleFromClick @($animReasons.ToArray() | Select-Object -Unique))
330
+ if ($shapeType -eq 6) {
331
+ $children = @(Inspect-Shapes $slideId $slideWidth $slideHeight $shape.GroupItems $targetsByKey $effectsByShape $isTransformed $visibleFromClick @($animReasons.ToArray() | Select-Object -Unique))
286
332
  foreach ($child in $children) {
287
333
  $visibleFromClick = [Math]::Max($visibleFromClick, [int]$child.visible_from_click)
288
334
  foreach ($childReason in $child.unsupported) {
@@ -292,44 +338,61 @@ function Inspect-Shapes($slide, $shapes, $package, [bool]$ancestorTransformed, [
292
338
  }
293
339
  }
294
340
  }
295
- @{ id = [int]$shape.Id; name = [string]$shape.Name; bounds = $bounds; unsupported = @($reasons.ToArray() | Select-Object -Unique); visible_from_click = $visibleFromClick }
341
+ @{ id = $shapeId; name = $shapeName; bounds = $bounds; unsupported = @($reasons.ToArray() | Select-Object -Unique); visible_from_click = $visibleFromClick }
296
342
  foreach ($child in $children) { $child }
297
343
  }
298
344
  }
299
345
  function Inspect-Native($package) {
346
+ $slideWidth = [double]$presentation.PageSetup.SlideWidth
347
+ $slideHeight = [double]$presentation.PageSetup.SlideHeight
348
+ $targetsByKey = @{}
349
+ foreach ($target in $package.targets) {
350
+ $key = [string]$target.native_id + ':' + [string]$target.id
351
+ if (!$targetsByKey.ContainsKey($key)) { $targetsByKey[$key] = [Collections.Generic.List[object]]::new() }
352
+ $targetsByKey[$key].Add($target)
353
+ }
300
354
  $slides = [Collections.Generic.List[object]]::new()
301
355
  foreach ($slide in $presentation.Slides) {
302
356
  Check-Cancel
357
+ $slideId = [int]$slide.SlideID
358
+ $slideName = [string]$slide.Name
303
359
  $effects = [Collections.Generic.List[object]]::new()
360
+ $effectsByShape = @{}
304
361
  foreach ($effect in $slide.TimeLine.MainSequence) {
305
362
  $timing = $effect.Timing
306
- $effects.Add(@{ type = [int]$effect.EffectType; trigger = [int]$timing.TriggerType; duration_ms = [double]$timing.Duration * 1000; delay_ms = [double]$timing.TriggerDelayTime * 1000; repeat_count = [double]$timing.RepeatCount; repeat_duration_ms = [double]$timing.RepeatDuration * 1000; auto_reverse = [int]$timing.AutoReverse; exit = [int]$effect.Exit; shape = [int]$effect.Shape.Id; paragraph = [int]$effect.Paragraph })
363
+ $effectShapeId = [int]$effect.Shape.Id
364
+ $entry = @{ type = [int]$effect.EffectType; trigger = [int]$timing.TriggerType; duration_ms = [double]$timing.Duration * 1000; delay_ms = [double]$timing.TriggerDelayTime * 1000; repeat_count = [double]$timing.RepeatCount; repeat_duration_ms = [double]$timing.RepeatDuration * 1000; auto_reverse = [int]$timing.AutoReverse; exit = [int]$effect.Exit; shape = $effectShapeId; paragraph = [int]$effect.Paragraph }
365
+ $effects.Add($entry)
366
+ if (!$effectsByShape.ContainsKey($effectShapeId)) { $effectsByShape[$effectShapeId] = [Collections.Generic.List[object]]::new() }
367
+ $effectsByShape[$effectShapeId].Add(@{ trigger = $entry.trigger; repeat_count = $entry.repeat_count; repeat_duration_ms = $entry.repeat_duration_ms; exit = $entry.exit; paragraph = $entry.paragraph; after_effect = [int]$effect.EffectInformation.AfterEffect })
307
368
  }
308
- $shapes = @(Inspect-Shapes $slide $slide.Shapes $package $false)
369
+ $shapes = @(Inspect-Shapes $slideId $slideWidth $slideHeight $slide.Shapes $targetsByKey $effectsByShape $false)
309
370
  $transitionEffect = [int]$slide.SlideShowTransition.EntryEffect
310
371
  $transitionDurationMs = $(if ($transitionEffect -ne 0) { [Math]::Round([double]$slide.SlideShowTransition.Duration * 1000) } else { 0 })
311
- $slides.Add(@{ id = [string]$slide.Name; native_id = [int]$slide.SlideID; index = [int]$slide.SlideIndex; effects = @($effects.ToArray()); shapes = $shapes; transition = $transitionEffect; transition_duration_ms = $transitionDurationMs; auto_advance = [int]$slide.SlideShowTransition.AdvanceOnTime; hidden = [int]$slide.SlideShowTransition.Hidden; interactive = [int]$slide.TimeLine.InteractiveSequences.Count })
372
+ $slides.Add(@{ id = $slideName; native_id = $slideId; index = [int]$slide.SlideIndex; effects = @($effects.ToArray()); shapes = $shapes; transition = $transitionEffect; transition_duration_ms = $transitionDurationMs; auto_advance = [int]$slide.SlideShowTransition.AdvanceOnTime; hidden = [int]$slide.SlideShowTransition.Hidden; interactive = [int]$slide.TimeLine.InteractiveSequences.Count })
312
373
  foreach ($shape in $slide.Shapes) {
313
374
  if ([int]$shape.Type -eq 16) {
314
- if ([int]$shape.MediaType -ne 3) { $package.unsupported += @{ slide = [string]$slide.Name; reason = ('Only native video media shapes are supported: ' + $shape.Name) }; continue }
315
- $matches = @($package.media | Where-Object { $_.native_id -eq $slide.SlideID -and $_.shape -eq $shape.Id })
316
- if ($matches.Count -ne 1) { $package.unsupported += @{ slide = [string]$slide.Name; reason = ('Cannot identify exact embedded video bytes: ' + $shape.Name) }; continue }
375
+ $videoShapeId = [int]$shape.Id
376
+ $videoShapeName = [string]$shape.Name
377
+ if ([int]$shape.MediaType -ne 3) { $package.unsupported += @{ slide = $slideName; reason = ('Only native video media shapes are supported: ' + $videoShapeName) }; continue }
378
+ $matches = @($package.media | Where-Object { $_.native_id -eq $slideId -and $_.shape -eq $videoShapeId })
379
+ if ($matches.Count -ne 1) { $package.unsupported += @{ slide = $slideName; reason = ('Cannot identify exact embedded video bytes: ' + $videoShapeName) }; continue }
317
380
  $media = $matches[0]
318
- $media.id = [string]$shape.Name
381
+ $media.id = $videoShapeName
319
382
  $media.duration_ms = [double]$shape.MediaFormat.Length
320
383
  $media.start_ms = [double]$shape.MediaFormat.StartPoint
321
384
  $media.end_ms = [double]$shape.MediaFormat.EndPoint
322
385
  $media.autoplay = [int]$shape.AnimationSettings.PlaySettings.PlayOnEntry
323
386
  $media.loop = [int]$shape.AnimationSettings.PlaySettings.LoopUntilStopped
324
387
  $media.rewind = [int]$shape.AnimationSettings.PlaySettings.RewindMovie
325
- $media.left = [double]$shape.Left / $presentation.PageSetup.SlideWidth
326
- $media.top = [double]$shape.Top / $presentation.PageSetup.SlideHeight
327
- $media.right = ([double]$shape.Left + $shape.Width) / $presentation.PageSetup.SlideWidth
328
- $media.bottom = ([double]$shape.Top + $shape.Height) / $presentation.PageSetup.SlideHeight
388
+ $media.left = [double]$shape.Left / $slideWidth
389
+ $media.top = [double]$shape.Top / $slideHeight
390
+ $media.right = ([double]$shape.Left + $shape.Width) / $slideWidth
391
+ $media.bottom = ([double]$shape.Top + $shape.Height) / $slideHeight
329
392
  }
330
393
  }
331
394
  }
332
- return @{ version = 1; kind = 'inspection'; deck_sha256 = $job.deck_sha256; width = [double]$presentation.PageSetup.SlideWidth; height = [double]$presentation.PageSetup.SlideHeight; slides = @($slides.ToArray()); media = $package.media; unsupported = $package.unsupported; dependencies = (Dependencies) }
395
+ return @{ version = 1; kind = 'inspection'; deck_sha256 = $job.deck_sha256; width = $slideWidth; height = $slideHeight; slides = @($slides.ToArray()); media = $package.media; unsupported = $package.unsupported; dependencies = (Dependencies) }
333
396
  }
334
397
  function Dependencies {
335
398
  $office = [Diagnostics.Process]::GetProcessById($officeProcess).MainModule.FileVersionInfo.FileVersion
@@ -352,8 +415,11 @@ function Apply-Operation($operation) {
352
415
  if ($operation.type -eq 'slide') { Select-Slide $operation.native_id; $script:activeVisit = [string]$operation.id; $script:activeScene = [string]$operation.scene }
353
416
  elseif ($operation.type -eq 'reveal') {
354
417
  if ([int]$show.View.Slide.SlideID -ne $operation.native_id) { Fail 'POWERPOINT_NAVIGATION' ('Wrong native slide for reveal ' + $operation.id) }
355
- $show.View.GotoClick([int]$operation.click)
356
- if ([int]$show.View.GetClickIndex() -ne $operation.click) { Fail 'POWERPOINT_REVEAL' ('Native click did not execute: ' + $operation.id) }
418
+ $currentClick = [int]$show.View.GetClickIndex()
419
+ $targetClick = [int]$operation.click
420
+ if ($targetClick -eq $currentClick + 1) { $show.View.Next() }
421
+ else { $show.View.GotoClick($targetClick) }
422
+ if ([int]$show.View.Slide.SlideID -ne $operation.native_id -or [int]$show.View.GetClickIndex() -ne $targetClick) { Fail 'POWERPOINT_REVEAL' ('Native click did not execute: ' + $operation.id) }
357
423
  } elseif ($operation.type -eq 'play') {
358
424
  if ([int]$show.View.Slide.SlideID -ne $operation.native_id) { Fail 'POWERPOINT_MEDIA' ('Wrong native slide for media ' + $operation.id) }
359
425
  $player = $show.View.Player([int]$operation.shape)
@@ -419,11 +485,11 @@ function Check-Annotations {
419
485
  $request = $monitor.request
420
486
  $context = Request-Context $request $true
421
487
  if ($null -eq $monitor.geometry -and $request.start_ms -ge $annotationStartBeforeMs) { continue }
422
- $now = $clock.Elapsed.TotalMilliseconds - $origin
488
+ $now = Schedule-Now
423
489
  if ($now -lt $monitor.next_sample_ms -and $now -lt $request.end_ms) { continue }
424
490
  if ($null -eq $monitor.geometry -and $now -ge $request.end_ms) { Fail 'ANNOTATION_INTERVAL' ($context + ': native playback missed the entire interval.') }
425
491
  $fragments = @(Measure-Annotation $request)
426
- $observed = $clock.Elapsed.TotalMilliseconds - $origin
492
+ $observed = Schedule-Now
427
493
  if ($null -eq $monitor.geometry) {
428
494
  if ($observed -ge $request.end_ms) { Fail 'ANNOTATION_INTERVAL' ($context + ': initial measurement completed after the interval.') }
429
495
  if ($observed - $request.start_ms -gt 100) { Fail 'ANNOTATION_INTERVAL' ($context + ': initial native measurement exceeded the interval boundary by 100 ms.') }
@@ -448,7 +514,7 @@ function Check-Annotations {
448
514
  }
449
515
  }
450
516
  function Check-Media {
451
- $now = $clock.Elapsed.TotalMilliseconds - $origin
517
+ $now = Schedule-Now
452
518
  foreach ($monitor in @($activeMedia.ToArray())) {
453
519
  $position = [double]$monitor.player.CurrentPosition
454
520
  $state = [int]$monitor.player.State
@@ -567,6 +633,25 @@ function Rehearse {
567
633
  foreach ($slide in $presentation.Slides) { foreach ($shape in $slide.Shapes) { if ([int]$shape.Type -eq 16) { try { $show.View.Player([int]$shape.Id).Stop() } catch {} } } }
568
634
  Write-Json 'references.json' @{ version = 1; references = @($references.ToArray()) }
569
635
  }
636
+ function Wait-ShowView([double]$deadline) {
637
+ $lastError = ''
638
+ do {
639
+ Check-Cancel
640
+ try {
641
+ if ($null -eq $script:show) { $script:show = $presentation.SlideShowWindow }
642
+ $view = $script:show.View
643
+ if ($null -ne $view) { return [int]$view.State }
644
+ } catch {
645
+ $lastError = $_.Exception.Message
646
+ }
647
+ try {
648
+ if ($null -ne $presentation.SlideShowWindow) { $script:show = $presentation.SlideShowWindow }
649
+ } catch {}
650
+ Start-Sleep -Milliseconds 20
651
+ } while ($clock.Elapsed.TotalMilliseconds -lt $deadline)
652
+ if ($lastError) { Fail 'POWERPOINT_WINDOW' ('The slideshow view did not initialize: ' + $lastError) }
653
+ Fail 'POWERPOINT_WINDOW' 'The slideshow view did not initialize.'
654
+ }
570
655
  function Stop-Recorder {
571
656
  if ($null -eq $recorder) { return }
572
657
  if (!$recorder.HasExited) {
@@ -635,7 +720,7 @@ try {
635
720
  $deadline = $clock.Elapsed.TotalMilliseconds + 10000
636
721
  do { Check-Cancel; $window = [SlideVideo.Native]::FindShow($officeProcess, [IO.Path]::GetFileNameWithoutExtension($privateDeck), $editorWindow); if ($window -eq 0) { Start-Sleep -Milliseconds 20 } } while ($window -eq 0 -and $clock.Elapsed.TotalMilliseconds -lt $deadline)
637
722
  if ($window -eq 0) { Fail 'POWERPOINT_WINDOW' 'Cannot identify one audience window owned by the private deck.' }
638
- $initialViewState = [int]$show.View.State
723
+ $initialViewState = Wait-ShowView ($clock.Elapsed.TotalMilliseconds + 10000)
639
724
  $show.View.State = 1
640
725
  $show.View.AcceleratorsEnabled = 0
641
726
  $windowMode = [SlideVideo.Native]::PlaceForAudience($window, [int]$job.output.width, [int]$job.output.height, $deckAspect, $true, $true)
@@ -732,17 +817,21 @@ try {
732
817
  foreach ($marker in $markers) { $marker.observed_ms -= $origin; $marker.rendered_by_ms -= $origin }
733
818
  $script:activeVisit = [string]$firstOperation.id
734
819
  $script:activeScene = [string]$firstOperation.scene
820
+ $script:skippedMs = 0.0
821
+ $script:nextSkipIndex = 0
822
+ $appliedSkips.Clear()
823
+ $script:plannedSkips = $(if (!$job.verify_timing -and $null -ne $job.PSObject.Properties['static_skips'] -and $null -ne $job.static_skips) { @($job.static_skips) } else { @() })
735
824
  $script:collectAnnotations = $job.geometry_requests.Count -gt 0
736
825
  $initial = $true
737
826
  for ($operationIndex = 0; $operationIndex -lt $job.operations.Count; $operationIndex++) {
738
827
  $operation = $job.operations[$operationIndex]
739
828
  $script:annotationStartBeforeMs = [double]$operation.at_ms
740
- Wait-Until ($origin + $operation.at_ms)
829
+ Wait-UntilSchedule ([double]$operation.at_ms)
741
830
  Check-Media
742
831
  if (!$initial -and $operation.type -in @('slide', 'play')) { Wait-MediaCompletion }
743
832
  [SlideVideo.Native]::EnsureGeometry($window, $geometry)
744
833
  if ($initial) { $player = $null; $now = 0.0; $initial = $false }
745
- else { $player = Apply-Operation $operation; $now = $clock.Elapsed.TotalMilliseconds - $origin }
834
+ else { $player = Apply-Operation $operation; $now = Schedule-Now }
746
835
  $entry = @{ id = $operation.id; type = $operation.type; scheduled_ms = $operation.at_ms; observed_ms = $now }
747
836
  if ($operation.type -eq 'play') {
748
837
  $entry.media_ms = [double]$player.CurrentPosition
@@ -756,7 +845,7 @@ try {
756
845
  Check-Annotations
757
846
  }
758
847
  }
759
- Wait-Until ($origin + $job.duration_ms)
848
+ Wait-UntilSchedule ([double]$job.duration_ms)
760
849
  Check-Annotations
761
850
  if (@($annotationMonitors | Where-Object { !$_.complete }).Count -gt 0) { Fail 'ANNOTATION_GEOMETRY' 'Native playback did not complete every annotation interval.' }
762
851
  $script:collectAnnotations = $false
@@ -773,7 +862,7 @@ try {
773
862
  Wait-Until ($clock.Elapsed.TotalMilliseconds + 200)
774
863
  Stop-Recorder
775
864
  if ($recorder.ExitCode -ne 0) { Fail 'POWERPOINT_CAPTURE' ('FFmpeg exited ' + $recorder.ExitCode + '. See ffmpeg.log.') }
776
- $result = @{ version = 1; kind = 'recording'; file = $file; events = @($events.ToArray()); markers = @($markers.ToArray()); references = @($references.ToArray()); annotation_geometry = @($annotationGeometry.ToArray()); dependencies = (Dependencies) }
865
+ $result = @{ version = 1; kind = 'recording'; file = $file; events = @($events.ToArray()); markers = @($markers.ToArray()); references = @($references.ToArray()); annotation_geometry = @($annotationGeometry.ToArray()); applied_skips = @($appliedSkips.ToArray()); dependencies = (Dependencies) }
777
866
  }
778
867
  } catch {
779
868
  $message = $_.Exception.Message
@@ -14,6 +14,7 @@ function Run-Preview {
14
14
  if ($window -eq 0) { Start-Sleep -Milliseconds 20 }
15
15
  } while ($window -eq 0 -and $clock.Elapsed.TotalMilliseconds -lt $deadline)
16
16
  if ($window -eq 0) { Fail 'POWERPOINT_WINDOW' 'Cannot identify the slideshow owned by the private preview deck.' }
17
+ [void](Wait-ShowView ($clock.Elapsed.TotalMilliseconds + 10000))
17
18
  $show.View.AcceleratorsEnabled = 0
18
19
  [void][SlideVideo.Native]::PlaceForAudience($window, [int]$job.output.width, [int]$job.output.height, $deckAspect, $false, $false)
19
20
  $first = $job.operations[0]