-
-
Notifications
You must be signed in to change notification settings - Fork 176
Expand file tree
/
Copy pathvideo-content.tsx
More file actions
819 lines (737 loc) · 30.5 KB
/
video-content.tsx
File metadata and controls
819 lines (737 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import React, { useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
import { useSequenceContext } from '@/features/composition-runtime/deps/player';
import { usePlaybackStore } from '@/features/composition-runtime/deps/stores';
import { useGizmoStore } from '@/features/composition-runtime/deps/stores';
import { useVideoConfig, useIsPlaying } from '../hooks/use-player-compat';
import { useClock } from '@/features/composition-runtime/deps/player';
import type { VideoItem } from '@/types/timeline';
import { useVideoSourcePool } from '@/features/composition-runtime/deps/player';
import { isVideoPoolAbortError } from '@/features/composition-runtime/deps/player';
import { createLogger } from '@/shared/logging/logger';
import { getVideoTargetTimeSeconds } from '../utils/video-timing';
import {
registerDomVideoElement,
unregisterDomVideoElement,
} from '../utils/dom-video-element-registry';
import {
applyVideoElementAudioVolume,
useVideoAudioVolume,
connectedVideoElements,
videoAudioContexts,
ensureAudioContextResumed,
} from './video-audio-context';
const videoLog = createLogger('NativePreviewVideo');
const contentLog = createLogger('VideoContent');
videoLog.setLevel(2); // WARN — suppress noisy per-frame debug logs
// Feature detection for requestVideoFrameCallback (avoids per-frame React sync)
const supportsRVFC = typeof HTMLVideoElement !== 'undefined' &&
'requestVideoFrameCallback' in HTMLVideoElement.prototype;
/**
* Native HTML5 video component for preview mode using VideoSourcePool.
* Uses pooled video elements instead of creating new ones per clip.
* Split clips from the same source share video elements for efficiency.
*/
const NativePreviewVideo: React.FC<{
poolClipId: string;
itemId: string;
src: string;
safeTrimBefore: number;
sequenceFrameOffset?: number;
sourceFps: number;
playbackRate: number;
audioVolume: number;
onError: (error: Error) => void;
containerRef: React.RefObject<HTMLDivElement | null>;
forceCssComposite?: boolean;
}> = ({
poolClipId,
itemId,
src,
safeTrimBefore,
sequenceFrameOffset = 0,
sourceFps,
playbackRate,
audioVolume,
onError,
containerRef,
forceCssComposite = false,
}) => {
// Get local frame from Sequence context (not global frame from Clock)
// The Sequence provides localFrame which is 0-based within this sequence
const sequenceContext = useSequenceContext();
const frame = sequenceContext?.localFrame ?? 0;
const { fps } = useVideoConfig();
const pool = useVideoSourcePool();
const elementRef = useRef<HTMLVideoElement | null>(null);
const forceRenderTimeoutRef = useRef<number | null>(null);
const preWarmTimerRef = useRef<number | null>(null);
const preWarmGenRef = useRef(0);
const audioVolumeRef = useRef(audioVolume);
const onErrorRef = useRef(onError);
const lastSyncTimeRef = useRef<number>(Date.now());
const needsInitialSyncRef = useRef<boolean>(true);
const lastFrameRef = useRef<number>(-1);
const registeredElementRef = useRef<HTMLVideoElement | null>(null);
const registeredItemIdRef = useRef<string | null>(null);
audioVolumeRef.current = audioVolume;
onErrorRef.current = onError;
// Clock instance for imperative access in rVFC callback
const clock = useClock();
const sequenceFromRef = useRef(0);
// Stable refs for rVFC callback (avoids stale closures)
const safeTrimBeforeRef = useRef(safeTrimBefore);
const sourceFpsRef = useRef(sourceFps);
const playbackRateRef = useRef(playbackRate);
const fpsRef = useRef(fps);
const sequenceFrameOffsetRef = useRef(sequenceFrameOffset);
safeTrimBeforeRef.current = safeTrimBefore;
sourceFpsRef.current = sourceFps;
playbackRateRef.current = playbackRate;
fpsRef.current = fps;
sequenceFrameOffsetRef.current = sequenceFrameOffset;
// Get playing state from our clock
const isPlaying = useIsPlaying();
// Calculate target time in the source video
// safeTrimBefore is in SOURCE frames (where playback starts in the source)
// frame is in TIMELINE frames (current position within the Sequence)
// For seeking, convert source start to seconds using source FPS.
const targetTime = getVideoTargetTimeSeconds(
safeTrimBefore,
sourceFps,
frame,
playbackRate,
fps,
sequenceFrameOffset
);
const shortId = poolClipId?.slice(0, 8) ?? 'no-id';
// Segment boundary resync:
// With stable pool identities, split clips no longer remount/reacquire.
// When the active segment switches (itemId changes), source mapping can jump
// discontinuously (especially around transition overlaps), so force an
// immediate sync on the next playback tick.
useEffect(() => {
needsInitialSyncRef.current = true;
lastSyncTimeRef.current = 0;
}, [itemId]);
const syncRegisteredVideoElement = useCallback((nextItemId: string, nextElement: HTMLVideoElement | null) => {
const prevElement = registeredElementRef.current;
const prevItemId = registeredItemIdRef.current;
if (prevElement && prevItemId && (prevElement !== nextElement || prevItemId !== nextItemId)) {
unregisterDomVideoElement(prevItemId, prevElement);
}
if (nextElement && (prevElement !== nextElement || prevItemId !== nextItemId)) {
registerDomVideoElement(nextItemId, nextElement);
}
registeredElementRef.current = nextElement;
registeredItemIdRef.current = nextElement ? nextItemId : null;
}, []);
const clearRegisteredVideoElement = useCallback(() => {
const prevElement = registeredElementRef.current;
const prevItemId = registeredItemIdRef.current;
if (prevElement && prevItemId) {
unregisterDomVideoElement(prevItemId, prevElement);
}
registeredElementRef.current = null;
registeredItemIdRef.current = null;
}, []);
useLayoutEffect(() => {
syncRegisteredVideoElement(itemId, elementRef.current);
}, [itemId, syncRegisteredVideoElement]);
// Acquire element from pool on mount
useEffect(() => {
// Guard: poolClipId and src are required
if (!poolClipId || !src) {
videoLog.error('Missing poolClipId or src');
return;
}
let cancelled = false;
// Reset sync state for the new clip. The component doesn't unmount when
// crossing split boundaries (React reconciles with new props), so refs
// retain stale values from the previous clip. Without this reset, the
// sync effect skips the initial seek for the new clip because it thinks
// initial sync already happened.
needsInitialSyncRef.current = true;
lastSyncTimeRef.current = 0;
videoLog.debug(`[${shortId}] acquiring element for:`, src);
// Ensure source is preloaded
pool.preloadSource(src).catch((error) => {
if (cancelled || isVideoPoolAbortError(error)) {
return;
}
videoLog.warn(`Failed to preload ${src}:`, error);
});
// Acquire element for this clip
const element = pool.acquireForClip(poolClipId, src);
if (!element) {
videoLog.error(`Failed to acquire element for ${poolClipId}`);
return;
}
videoLog.debug(`[${shortId}] acquired:`, element.readyState);
// CRITICAL: Unmute video element immediately after acquisition
// Pool creates elements muted, and we need audio to work.
// This must happen here (not just in volume effect) because when crossing
// split boundaries, itemId changes causing this effect to re-run, but
// the volume effect won't re-run if audioVolume hasn't changed.
element.muted = false;
// Also resume AudioContext if this element was previously connected
// (e.g., when crossing split boundary and reusing the same video element)
if (connectedVideoElements.has(element)) {
const audioContext = videoAudioContexts.get(element);
if (audioContext?.state === 'suspended') {
audioContext.resume();
}
}
// Check if this is a split boundary crossing during playback.
// The pool may return the same element that was just released by cleanup.
// If the element is already near the correct position, keep it playing
// to avoid a decode restart stutter.
const initialTargetTime = getVideoTargetTimeSeconds(
safeTrimBefore,
sourceFps,
frame,
playbackRate,
fps,
sequenceFrameOffset
);
const clampedInitial = Math.min(initialTargetTime, (element.duration || Infinity) - 0.1);
const currentlyPlaying = usePlaybackStore.getState().isPlaying;
const isNearTarget = Math.abs(element.currentTime - clampedInitial) < 0.2;
const isContinuousPlayback = currentlyPlaying && isNearTarget && element.readyState >= 2;
elementRef.current = element;
syncRegisteredVideoElement(itemId, element);
applyVideoElementAudioVolume(element, audioVolumeRef.current);
if (isContinuousPlayback) {
// Split boundary during playback: element was just paused by cleanup
// but is at the right position. Resume immediately to minimize the
// decode pipeline interruption (pause→play in same synchronous batch).
element.playbackRate = playbackRate;
element.play().catch(() => {});
needsInitialSyncRef.current = false;
} else if (currentlyPlaying) {
// Playback is active but element isn’t at position (transition mount,
// shadow mount, or resume near a boundary). Seek and play immediately
// instead of pausing and waiting for the sync effect next frame.
// This eliminates ~16-50ms of React scheduling + readyState gate delay.
element.playbackRate = playbackRate;
element.currentTime = clampedInitial;
if (element.readyState >= 2) {
element.play().catch(() => {});
}
needsInitialSyncRef.current = false;
} else {
// Not playing (scrubbing, paused) — pause and seek
element.pause();
}
// Set up event listeners
const handleCanPlay = () => {
videoLog.debug(`[${shortId}] canplay:`, element.readyState);
};
const handleSeeked = () => {
videoLog.debug(`[${shortId}] seeked:`, element.currentTime);
};
const handleError = () => {
const error = new Error(`Video error: ${element.error?.message || 'Unknown'}`);
onErrorRef.current(error);
};
// Prevent black frames when video reaches its natural end
// Seek back slightly to show the last frame
const handleEnded = () => {
videoLog.debug(`[${shortId}] ended, seeking to last frame`);
if (element.duration && element.duration > 0.1) {
element.currentTime = element.duration - 0.05;
}
};
element.addEventListener('canplay', handleCanPlay);
element.addEventListener('seeked', handleSeeked);
element.addEventListener('error', handleError);
element.addEventListener('ended', handleEnded);
// Mount element into container
const container = containerRef.current;
if (container && element.parentElement !== container) {
element.style.width = '100%';
element.style.height = '100%';
element.style.objectFit = 'contain';
element.style.display = 'block';
element.style.position = 'absolute';
element.style.top = '0';
element.style.left = '0';
if (forceCssComposite) {
element.style.transform = 'translateZ(0)';
element.style.backfaceVisibility = 'hidden';
element.style.willChange = 'transform, opacity';
} else {
element.style.transform = '';
element.style.backfaceVisibility = '';
element.style.willChange = '';
}
element.id = `pooled-video-${poolClipId}`;
container.appendChild(element);
videoLog.debug(`[${shortId}] mounted to container`);
}
// Seek to initial position (skip for continuous playback - already at position)
if (!isContinuousPlayback) {
videoLog.debug(`[${shortId}] initial seek to:`, clampedInitial.toFixed(3),
'safeTrimBefore:', safeTrimBefore, 'frame:', frame, 'playbackRate:', playbackRate,
'fps:', fps,
'videoDuration:', element.duration?.toFixed(3),
'seekPastEnd:', initialTargetTime > element.duration);
element.currentTime = clampedInitial;
} else {
videoLog.debug(`[${shortId}] continuous playback, skipping seek (drift: ${(element.currentTime - clampedInitial).toFixed(3)}s)`);
}
// Force a frame render by doing a quick play/pause - some browsers need this
// to actually display the video frame after seeking.
// Only when NOT playing — during playback, the sync effect handles play()
// and this timeout’s play→pause sequence would race with it.
if (!currentlyPlaying) {
const forceFrameRender = () => {
if (element.paused && element.readyState >= 2 && !usePlaybackStore.getState().isPlaying) {
element.play().then(() => {
element.pause();
}).catch(() => {});
}
};
forceRenderTimeoutRef.current = window.setTimeout(forceFrameRender, 100);
}
// Stall watchdog: if the element is stuck at readyState 0 for too long
// (e.g., slow OPFS read, browser decoder init, broken file), retry load.
// For stale blob URLs after inactivity, the visibilitychange handler in
// video-preview.tsx refreshes all proxy/source URLs and triggers a full
// re-render with fresh src props, which remounts this component.
let stallTimerId: number | null = null;
if (element.readyState === 0) {
stallTimerId = window.setTimeout(() => {
stallTimerId = null;
if (elementRef.current === element && element.readyState === 0) {
videoLog.warn(`Video stalled at readyState 0 for ${shortId}, retrying load`);
try {
element.load();
} catch {
// load() can throw if element is in a bad state
}
}
}, 3000);
}
return () => {
cancelled = true;
element.removeEventListener('canplay', handleCanPlay);
element.removeEventListener('seeked', handleSeeked);
element.removeEventListener('error', handleError);
element.removeEventListener('ended', handleEnded);
// Pause and remove from DOM
element.pause();
if (forceRenderTimeoutRef.current !== null) {
clearTimeout(forceRenderTimeoutRef.current);
forceRenderTimeoutRef.current = null;
}
if (preWarmTimerRef.current !== null) {
clearTimeout(preWarmTimerRef.current);
preWarmTimerRef.current = null;
}
if (stallTimerId !== null) {
clearTimeout(stallTimerId);
stallTimerId = null;
}
if (element.parentElement) {
element.parentElement.removeChild(element);
}
// Release back to pool
clearRegisteredVideoElement();
pool.releaseClip(poolClipId);
elementRef.current = null;
videoLog.debug(`[${shortId}] released`);
};
// Note: frame, fps, targetTime intentionally NOT in deps - we only want to acquire once on mount
// Ongoing seeking is handled by the separate sync effect
}, [poolClipId, src, pool, containerRef, shortId, itemId, syncRegisteredVideoElement, clearRegisteredVideoElement]);
useEffect(() => {
const element = elementRef.current;
if (!element) return;
if (forceCssComposite) {
element.style.transform = 'translateZ(0)';
element.style.backfaceVisibility = 'hidden';
element.style.willChange = 'transform, opacity';
return;
}
element.style.transform = '';
element.style.backfaceVisibility = '';
element.style.willChange = '';
}, [forceCssComposite]);
// Sync video playback with timeline
// Layout pass handles immediate seeks before paint to avoid one-frame stale
// content during segment/transition boundary handoffs.
useLayoutEffect(() => {
const video = elementRef.current;
if (!video) return;
// Only set playbackRate from React when RVFC isn't managing drift correction.
// During playback with RVFC, the callback owns video.playbackRate and applies
// small rate adjustments for smooth drift correction. Overwriting here would
// undo those adjustments every frame.
if (!isPlaying || !supportsRVFC) {
video.playbackRate = playbackRate;
}
const relativeFrame = frame - sequenceFrameOffset;
const isPremounted = relativeFrame < 0;
const canSeek = video.readyState >= 1;
const effectiveTargetTime = isPremounted
? (safeTrimBefore / sourceFps)
: targetTime;
const videoDuration = video.duration || Infinity;
const clampedTargetTime = Math.min(Math.max(0, effectiveTargetTime), videoDuration - 0.05);
if (!canSeek) return;
if (isPremounted) {
if (!video.paused) {
video.pause();
}
if (Math.abs(video.currentTime - clampedTargetTime) > 0.016) {
try {
video.currentTime = clampedTargetTime;
} catch {
// Seek failed - element may still be initializing
}
}
return;
}
const mustHardSync = needsInitialSyncRef.current;
if (mustHardSync || (!isPlaying && Math.abs(video.currentTime - clampedTargetTime) > 0.016)) {
try {
video.currentTime = clampedTargetTime;
lastSyncTimeRef.current = Date.now();
if (mustHardSync) {
needsInitialSyncRef.current = false;
}
} catch {
// Seek failed - element may still be initializing
}
}
}, [frame, isPlaying, playbackRate, safeTrimBefore, sourceFps, targetTime, sequenceFrameOffset]);
// Runtime playback control + drift correction
useEffect(() => {
const video = elementRef.current;
if (!video) return;
// Only set playbackRate from React when RVFC isn't active.
// RVFC owns the rate during playback for smooth drift correction.
if (!isPlaying || !supportsRVFC) {
video.playbackRate = playbackRate;
}
// Update sequenceFrom for rVFC callback (global frame minus local frame)
sequenceFromRef.current = clock.currentFrame - frame;
// Detect if frame actually changed (for scrub detection)
const frameChanged = frame !== lastFrameRef.current;
lastFrameRef.current = frame;
// Check if we're in premount phase (frame < 0 means clip hasn't started yet)
// During premount, we should NOT play - just prepare the video at the start position
const relativeFrame = frame - sequenceFrameOffset;
const isPremounted = relativeFrame < 0;
// Guard: Only seek if video has enough data loaded
const canSeek = video.readyState >= 1;
// During premount, seek to the start of the clip (frame 0 position), not negative time
// This ensures the video is ready at the correct starting frame when playback reaches this clip
const effectiveTargetTime = isPremounted
? (safeTrimBefore / sourceFps)
: targetTime;
// Clamp target time to video duration to prevent seeking past the end
// This prevents black frames when the clip extends to the edge of the source
const videoDuration = video.duration || Infinity;
const clampedTargetTime = Math.min(Math.max(0, effectiveTargetTime), videoDuration - 0.05);
if (targetTime > videoDuration - 1) {
videoLog.debug(`[${shortId}] NEAR END:`, {
targetTime: targetTime.toFixed(2),
videoDuration: videoDuration.toFixed(2),
clampedTargetTime: clampedTargetTime.toFixed(2),
frame,
playbackRate,
safeTrimBefore,
fps,
});
}
// During premount, always pause - don't play until clip is actually visible
if (isPremounted) {
if (!video.paused) {
video.pause();
}
// Seek to start position so video is ready when playback reaches this clip
if (canSeek && Math.abs(video.currentTime - clampedTargetTime) > 0.1) {
video.currentTime = clampedTargetTime;
}
return;
}
if (isPlaying) {
// Cancel any pending pre-warm since we're about to play
if (preWarmTimerRef.current !== null) {
clearTimeout(preWarmTimerRef.current);
preWarmTimerRef.current = null;
}
// Invalidate any in-flight pre-warm promise so its .then()/.catch() no-ops
preWarmGenRef.current += 1;
// Initial sync on first play after mount/seek.
// Skip the seek if element is already at the target (avoids readyState
// drop from redundant seeks, which delays play start by 100-300ms).
if (needsInitialSyncRef.current && canSeek) {
if (Math.abs(video.currentTime - clampedTargetTime) > 0.016) {
try {
video.currentTime = clampedTargetTime;
} catch {
// Seek failed - video may not be ready yet
}
}
lastSyncTimeRef.current = Date.now();
needsInitialSyncRef.current = false;
}
// Drift correction: only run from React effect when rVFC is NOT available.
// When rVFC is supported, the callback below handles drift correction
// directly from the video's presentation callback, avoiding per-frame
// React scheduling overhead.
if (!supportsRVFC) {
const currentTime = video.currentTime;
const now = Date.now();
const drift = currentTime - clampedTargetTime;
const timeSinceLastSync = now - lastSyncTimeRef.current;
const videoBehind = drift < -0.2;
const videoFarAhead = drift > 0.5;
// Keep correction responsive for segment/transition boundaries.
// A 500ms backoff can leak stale frames in preview.
if ((videoFarAhead || (videoBehind && timeSinceLastSync > 80)) && canSeek) {
try {
video.currentTime = clampedTargetTime;
lastSyncTimeRef.current = now;
} catch {
// Seek failed - video may not be ready yet
}
}
}
// Play if paused and video has current frame data (HAVE_CURRENT_DATA).
// >= 2 is sufficient — the browser buffers ahead during playback.
// Previous >= 3 gate added 100-300ms of unnecessary cold start delay
// waiting for HAVE_FUTURE_DATA after every seek.
if (video.paused && video.readyState >= 2) {
video.play().catch(() => {
// Autoplay might be blocked - this is fine
});
}
} else {
// Pause video when not playing
if (!video.paused) {
video.pause();
}
const playbackState = usePlaybackStore.getState();
const isPreviewScrubbing =
!playbackState.isPlaying
&& playbackState.previewFrame !== null
&& useGizmoStore.getState().activeGizmo === null;
// Only seek when paused if frame actually changed (user is scrubbing)
if (frameChanged && canSeek) {
// Layout sync already applies seeks before paint; skip duplicate runtime seek
// unless the element still has meaningful drift.
if (Math.abs(video.currentTime - clampedTargetTime) > 0.016) {
try {
video.currentTime = clampedTargetTime;
} catch {
// Seek failed - video may not be ready yet
}
}
// Pre-warm decoder at the new position (debounced). A brief muted
// play/pause fills the decode buffer so playback starts without
// stutter when the user presses play. Short debounce avoids
// thrashing during rapid scrubbing while keeping warm-up fast.
if (!isPreviewScrubbing) {
if (preWarmTimerRef.current !== null) {
clearTimeout(preWarmTimerRef.current);
}
preWarmGenRef.current += 1;
const gen = preWarmGenRef.current;
preWarmTimerRef.current = window.setTimeout(() => {
preWarmTimerRef.current = null;
const v = elementRef.current;
if (v && v.paused && v.readyState >= 2 && !usePlaybackStore.getState().isPlaying) {
v.muted = true;
v.play().then(() => {
// Only pause if this pre-warm is still current and playback hasn't started
if (gen === preWarmGenRef.current && !usePlaybackStore.getState().isPlaying) {
v.pause();
}
// Always unmute — if playback started or another scrub superseded
// this pre-warm, leaving muted=true causes silent playback.
v.muted = false;
}).catch(() => {
v.muted = false;
});
}
}, 50);
}
}
}
}, [frame, fps, isPlaying, playbackRate, safeTrimBefore, sourceFps, targetTime, sequenceFrameOffset]);
// requestVideoFrameCallback-based drift correction.
// Runs outside React's render cycle — the browser calls us exactly when a
// video frame is presented. Uses rate-based correction for small drifts
// (adjusts playbackRate ±2-5% to smoothly converge) and hard seeks only
// for large drifts (>200ms). This eliminates the visible “drift then jump”
// jitter pattern that hard-seek-only correction causes.
useEffect(() => {
const video = elementRef.current;
if (!video || !isPlaying || !supportsRVFC) return;
// Pre-resume AudioContext so audio starts immediately with video.
// Without this, suspended AudioContext adds 50-100ms audio delay on cold resume.
ensureAudioContextResumed();
// Set initial playbackRate when RVFC takes over
video.playbackRate = playbackRateRef.current;
let handle: number;
const onVideoFrame = () => {
const v = elementRef.current;
if (!v) return;
// Read current clock frame imperatively (no React re-render needed)
const globalFrame = clock.currentFrame;
const localFrame = globalFrame - sequenceFromRef.current;
const relativeFrame = localFrame - sequenceFrameOffsetRef.current;
// During premount, just keep listening
if (relativeFrame < 0) {
handle = v.requestVideoFrameCallback(onVideoFrame);
return;
}
const nominalRate = playbackRateRef.current;
const timelineFps = fpsRef.current;
const clipSourceFps = sourceFpsRef.current;
const trim = safeTrimBeforeRef.current;
const target = getVideoTargetTimeSeconds(
trim,
clipSourceFps,
localFrame,
nominalRate,
timelineFps,
sequenceFrameOffsetRef.current
);
const dur = v.duration || Infinity;
const clamped = Math.min(Math.max(0, target), dur - 0.05);
const drift = v.currentTime - clamped;
const absDrift = Math.abs(drift);
if (absDrift > 0.2) {
// Large drift (>200ms) — hard seek, reset rate
if (v.readyState >= 1) {
try {
v.currentTime = clamped;
lastSyncTimeRef.current = Date.now();
} catch {
// Seek may fail if element isn't fully loaded
}
}
v.playbackRate = nominalRate;
} else if (absDrift > 0.016) {
// Small drift (16-200ms) — smooth rate-based correction.
// Proportional: larger drift → stronger correction (up to ±5%).
// Converges in ~0.3-0.5s without visible jumps.
const correction = Math.min(0.05, absDrift * 0.3);
v.playbackRate = drift > 0
? nominalRate * (1 - correction) // ahead → slow down
: nominalRate * (1 + correction); // behind → speed up
} else {
// In sync (within ~1 frame) — nominal rate
v.playbackRate = nominalRate;
}
handle = v.requestVideoFrameCallback(onVideoFrame);
};
handle = video.requestVideoFrameCallback(onVideoFrame);
return () => {
video.cancelVideoFrameCallback(handle);
// Reset to nominal rate when RVFC stops managing
if (elementRef.current) {
elementRef.current.playbackRate = playbackRateRef.current;
}
};
}, [isPlaying, poolClipId, clock]);
// Keep volume/gain in sync for pooled element.
useEffect(() => {
const video = elementRef.current;
if (!video) return;
applyVideoElementAudioVolume(video, audioVolume);
}, [audioVolume]);
// Guard: itemId is required for rendering
if (!itemId) {
return <div style={{ width: '100%', height: '100%', backgroundColor: '#1a1a1a' }} />;
}
// DEBUG: Give container a unique ID so we can verify in DOM
const containerId = `video-container-${itemId}`;
// When premounted, frame will be negative. Hide the video until it's visible.
// In shared Sequences, local frame is offset by _sequenceFrameOffset.
const isVisible = frame - sequenceFrameOffset >= 0;
return (
<div
ref={containerRef}
id={containerId}
data-item-id={itemId}
style={{
width: '100%',
height: '100%',
position: 'relative',
// Hide when premounted (frame < 0), otherwise inherit parent visibility
visibility: isVisible ? undefined : 'hidden',
...(forceCssComposite ? {
transform: 'translateZ(0)',
backfaceVisibility: 'hidden' as const,
willChange: 'transform, opacity',
contain: 'paint',
} : {}),
}}
>
{/* Video element is mounted here by the useEffect */}
</div>
);
};
/**
* Video content with audio volume/fades support.
* Separate component so we can use hooks for audio calculation.
*
* Uses native HTML5 video for both preview and export (via Canvas + WebCodecs).
*/
export const VideoContent: React.FC<{
item: VideoItem & { _sequenceFrameOffset?: number; _poolClipId?: string };
muted: boolean;
safeTrimBefore: number;
playbackRate: number;
sourceFps: number;
forceCssComposite?: boolean;
}> = ({ item, muted, safeTrimBefore, playbackRate, sourceFps, forceCssComposite = false }) => {
const audioVolume = useVideoAudioVolume(item, muted);
const [hasError, setHasError] = useState(false);
// NativePreviewVideo mounts pooled <video> into this container.
const containerRef = useRef<HTMLDivElement | null>(null);
// Handle media errors (e.g., invalid blob URL after HMR or cache cleanup)
const handleError = useCallback((error: Error) => {
contentLog.warn(`Media error for item ${item.id}:`, error.message);
setHasError(true);
}, [item.id]);
// Show error state if media failed to load
if (hasError) {
return (
<div
style={{
width: '100%',
height: '100%',
backgroundColor: '#1a1a1a',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<p style={{ color: '#666', fontSize: 14 }}>Media unavailable</p>
</div>
);
}
// Use native HTML5 video with VideoSourcePool for element reuse
// Export uses Canvas + WebCodecs (client-render-engine.ts), not Composition's renderer
return (
<NativePreviewVideo
poolClipId={item._poolClipId ?? item.id}
itemId={item.id}
src={item.src!}
safeTrimBefore={safeTrimBefore}
sequenceFrameOffset={item._sequenceFrameOffset ?? 0}
sourceFps={sourceFps}
playbackRate={playbackRate}
audioVolume={audioVolume}
onError={handleError}
containerRef={containerRef}
forceCssComposite={forceCssComposite}
/>
);
};