Skip to content

🎥 Make videos programmatically with React

Rework buffering state with Safari

Jonny Burger435a9b3a9032
diff --git a/packages/core/src/audio/AudioForPreview.tsx b/packages/core/src/audio/AudioForPreview.tsx
index 350d6d61fc..37b4add1d7 100644
--- a/packages/core/src/audio/AudioForPreview.tsx
+++ b/packages/core/src/audio/AudioForPreview.tsx
@@ -11,7 +11,6 @@ import {SequenceContext} from '../SequenceContext.js';
import {SequenceVisibilityToggleContext} from '../SequenceManager.js';
import {usePreload} from '../prefetch.js';
import {random} from '../random.js';
-import {useMediaBuffering} from '../use-media-buffering.js';
import {useMediaInTimeline} from '../use-media-in-timeline.js';
import {
DEFAULT_ACCEPTABLE_TIMESHIFT,
@@ -169,12 +168,8 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
onlyWarnForMediaSeekingError: false,
acceptableTimeshift:
acceptableTimeShiftInSeconds ?? DEFAULT_ACCEPTABLE_TIMESHIFT,
- });
-
- useMediaBuffering({
- element: audioRef,
- shouldBuffer: pauseWhenBuffering,
isPremounting: Boolean(sequenceContext?.premounting),
+ pauseWhenBuffering,
});
useImperativeHandle(
diff --git a/packages/core/src/use-media-buffering.ts b/packages/core/src/use-media-buffering.ts
index 758ddb23b6..cee1e714be 100644
--- a/packages/core/src/use-media-buffering.ts
+++ b/packages/core/src/use-media-buffering.ts
@@ -1,5 +1,4 @@
-import type React from 'react';
-import {useEffect} from 'react';
+import {useEffect, useState} from 'react';
import {useBufferState} from './use-buffer-state';
export const useMediaBuffering = ({
@@ -12,6 +11,7 @@ export const useMediaBuffering = ({
isPremounting: boolean;
}) => {
const buffer = useBufferState();
+ const [isBuffering, setIsBuffering] = useState(false);
useEffect(() => {
let cleanupFns: Function[] = [];
@@ -32,9 +32,11 @@ export const useMediaBuffering = ({
const cleanup = () => {
cleanupFns.forEach((fn) => fn());
cleanupFns = [];
+ setIsBuffering(false);
};
const onWaiting = () => {
+ setIsBuffering(true);
const {unblock} = buffer.delayPlayback();
const onCanPlay = () => {
cleanup();
@@ -96,4 +98,6 @@ export const useMediaBuffering = ({
cleanup();
};
}, [buffer, element, isPremounting, shouldBuffer]);
+
+ return isBuffering;
};
diff --git a/packages/core/src/use-media-playback.ts b/packages/core/src/use-media-playback.ts
index 716ea53969..7379685637 100644
--- a/packages/core/src/use-media-playback.ts
+++ b/packages/core/src/use-media-playback.ts
@@ -1,5 +1,5 @@
import type {RefObject} from 'react';
-import {useContext, useEffect} from 'react';
+import {useContext, useEffect, useRef} from 'react';
import {useMediaStartsAt} from './audio/use-audio-frame.js';
import {BufferingContextReact} from './buffering.js';
import {playAndHandleNotAllowedError} from './play-and-handle-not-allowed-error.js';
@@ -8,7 +8,9 @@ import {
usePlayingState,
useTimelinePosition,
} from './timeline-position-state.js';
+import {useBufferState} from './use-buffer-state.js';
import {useCurrentFrame} from './use-current-frame.js';
+import {useMediaBuffering} from './use-media-buffering.js';
import {useVideoConfig} from './use-video-config.js';
import {getMediaTime} from './video/get-current-time.js';
import {isIosSafari} from './video/video-fragment.js';
@@ -19,18 +21,47 @@ export const DEFAULT_ACCEPTABLE_TIMESHIFT = 0.45;
const seek = (
mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>,
time: number,
-) => {
+ type: 'video' | 'audio',
+ playing: boolean,
+): Promise<number | null> => {
if (!mediaRef.current) {
- return;
+ return Promise.resolve(null);
}
+ console.log('gonna seek', playing);
+
+ const returnPromise = () => {
+ if (
+ type === 'video' &&
+ (mediaRef.current as HTMLVideoElement).requestVideoFrameCallback
+ ) {
+ return new Promise<number>((resolve) => {
+ (mediaRef.current as HTMLVideoElement).requestVideoFrameCallback(
+ (_, i) => {
+ resolve(i.mediaTime);
+ },
+ );
+ });
+ }
+
+ return Promise.resolve(null);
+ };
+
// iOS seeking does not support multiple decimals
if (isIosSafari()) {
mediaRef.current.currentTime = Number(time.toFixed(1));
- return;
+ if (
+ type === 'video' &&
+ (mediaRef.current as HTMLVideoElement).requestVideoFrameCallback
+ ) {
+ return returnPromise();
+ }
+
+ return Promise.resolve(null);
}
mediaRef.current.currentTime = time;
+ return returnPromise();
};
export const useMediaPlayback = ({
@@ -40,6 +71,8 @@ export const useMediaPlayback = ({
playbackRate: localPlaybackRate,
onlyWarnForMediaSeekingError,
acceptableTimeshift,
+ pauseWhenBuffering,
+ isPremounting,
}: {
mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>;
src: string | undefined;
@@ -47,6 +80,8 @@ export const useMediaPlayback = ({
playbackRate: number;
onlyWarnForMediaSeekingError: boolean;
acceptableTimeshift: number;
+ pauseWhenBuffering: boolean;
+ isPremounting: boolean;
}) => {
const {playbackRate: globalPlaybackRate} = useContext(TimelineContext);
const frame = useCurrentFrame();
@@ -55,6 +90,19 @@ export const useMediaPlayback = ({
const buffering = useContext(BufferingContextReact);
const {fps} = useVideoConfig();
const mediaStartsAt = useMediaStartsAt();
+ const {delayPlayback} = useBufferState();
+
+ if (!buffering) {
+ throw new Error(
+ 'useMediaPlayback must be used inside a <BufferingContext>',
+ );
+ }
+
+ const isMediaTagBuffering = useMediaBuffering({
+ element: mediaRef,
+ shouldBuffer: pauseWhenBuffering,
+ isPremounting,
+ });
const playbackRate = localPlaybackRate * globalPlaybackRate;
@@ -70,14 +118,51 @@ export const useMediaPlayback = ({
return acceptableTimeshift;
})();
- const pausedOrBuffering =
- !playing || (buffering && buffering.buffering.current);
-
useEffect(() => {
- if (pausedOrBuffering) {
+ if (!playing) {
mediaRef.current?.pause();
+ return;
}
- }, [mediaRef, mediaType, pausedOrBuffering]);
+
+ const isPlayerBuffering = buffering.buffering.current;
+ if (isPlayerBuffering && !isMediaTagBuffering) {
+ mediaRef.current?.pause();
+ }
+ }, [buffering.buffering, isMediaTagBuffering, mediaRef, playing]);
+
+ const currentTime = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (!mediaRef.current) {
+ currentTime.current = null;
+ }
+
+ if (mediaType !== 'video') {
+ currentTime.current = null;
+ }
+
+ let cancel = () => undefined;
+
+ const request = () => {
+ const cb = (
+ mediaRef.current as HTMLVideoElement
+ ).requestVideoFrameCallback((_, info) => {
+ currentTime.current = info.mediaTime;
+ request();
+ });
+
+ cancel = () => {
+ (mediaRef.current as HTMLVideoElement)?.cancelVideoFrameCallback(cb);
+ cancel = () => undefined;
+ };
+ };
+
+ request();
+
+ return () => {
+ cancel();
+ };
+ }, [mediaRef, mediaType]);
useEffect(() => {
const tagName = mediaType === 'audio' ? '<Audio>' : '<Video>';
@@ -108,13 +193,31 @@ export const useMediaPlayback = ({
? Math.min(duration, desiredUnclampedTime)
: desiredUnclampedTime;
const isTime = mediaRef.current.currentTime;
- const timeShift = Math.abs(shouldBeTime - isTime);
+ const rvcTime = currentTime.current ?? Infinity;
+
+ const timeShiftMediaTag = Math.abs(shouldBeTime - isTime);
+ const timeShiftRvcTag = Math.abs(shouldBeTime - rvcTime);
+ const timeShift = Math.min(timeShiftMediaTag, timeShiftRvcTag);
+
+ console.log({
+ isTime,
+ rvcTime,
+ shouldBeTime,
+ state: mediaRef.current.readyState,
+ playing: !mediaRef.current.paused,
+ });
if (timeShift > acceptableTimeShiftButLessThanDuration) {
// If scrubbing around, adjust timing
// or if time shift is bigger than 0.45sec
- seek(mediaRef, shouldBeTime);
+ console.log('Seeking', shouldBeTime, isTime, rvcTime, timeShift);
+ const {unblock} = delayPlayback();
+ seek(mediaRef, shouldBeTime, mediaType, playing).then((num) => {
+ console.log('seeking done unblock', num);
+ unblock();
+ });
+
if (!onlyWarnForMediaSeekingError) {
warnAboutNonSeekableMedia(
mediaRef.current,
@@ -125,27 +228,46 @@ export const useMediaPlayback = ({
return;
}
+ const seekThreshold = playing ? 0.15 : 0.00001;
+
+ if (buffering.buffering.current) {
+ const shouldSeek =
+ Math.abs(mediaRef.current.currentTime - shouldBeTime) > seekThreshold;
+ if (shouldSeek) {
+ seek(mediaRef, shouldBeTime, mediaType, playing).then(() => {
+ console.log('seeking done (buffered)');
+ });
+ }
+
+ return;
+ }
+
// Only perform a seek if the time is not already the same.
// Chrome rounds to 6 digits, so 0.033333333 -> 0.033333,
// therefore a threshold is allowed.
// Refer to the https://github.com/remotion-dev/video-buffering-example
// which is fixed by only seeking conditionally.
const makesSenseToSeek =
- Math.abs(mediaRef.current.currentTime - shouldBeTime) > 0.00001;
+ Math.abs(mediaRef.current.currentTime - shouldBeTime) > seekThreshold;
- if (pausedOrBuffering || absoluteFrame === 0) {
+ if (!playing) {
if (makesSenseToSeek) {
- seek(mediaRef, shouldBeTime);
+ seek(mediaRef, shouldBeTime, mediaType, playing).then(() => {});
}
+
+ return;
}
+ // We assured we are in playing state
if (
- mediaRef.current.paused &&
- !mediaRef.current.ended &&
- !pausedOrBuffering
+ (mediaRef.current.paused && !mediaRef.current.ended) ||
+ absoluteFrame === 0
) {
if (makesSenseToSeek) {
- seek(mediaRef, shouldBeTime);
+ console.log('playing', mediaRef.current.currentTime, shouldBeTime);
+ seek(mediaRef, shouldBeTime, mediaType, playing).then(() => {
+ console.log('seeking done (playing)');
+ });
}
playAndHandleNotAllowedError(mediaRef, mediaType);
@@ -163,6 +285,8 @@ export const useMediaPlayback = ({
onlyWarnForMediaSeekingError,
acceptableTimeshift,
acceptableTimeShiftButLessThanDuration,
- pausedOrBuffering,
+ playing,
+ delayPlayback,
+ buffering.buffering,
]);
};
diff --git a/packages/core/src/video/VideoForPreview.tsx b/packages/core/src/video/VideoForPreview.tsx
index 640ba2a5df..08583daaa0 100644
--- a/packages/core/src/video/VideoForPreview.tsx
+++ b/packages/core/src/video/VideoForPreview.tsx
@@ -11,7 +11,6 @@ import {SequenceContext} from '../SequenceContext.js';
import {SequenceVisibilityToggleContext} from '../SequenceManager.js';
import {useFrameForVolumeProp} from '../audio/use-audio-frame.js';
import {usePreload} from '../prefetch.js';
-import {useMediaBuffering} from '../use-media-buffering.js';
import {useMediaInTimeline} from '../use-media-in-timeline.js';
import {
DEFAULT_ACCEPTABLE_TIMESHIFT,
@@ -114,12 +113,8 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<
onlyWarnForMediaSeekingError,
acceptableTimeshift:
acceptableTimeShiftInSeconds ?? DEFAULT_ACCEPTABLE_TIMESHIFT,
- });
-
- useMediaBuffering({
- element: videoRef,
- shouldBuffer: pauseWhenBuffering,
isPremounting: Boolean(parentSequence?.premounting),
+ pauseWhenBuffering,
});
const actualFrom = parentSequence ? parentSequence.relativeFrom : 0;
diff --git a/packages/player-example/pages/index.tsx b/packages/player-example/pages/index.tsx
index afb09fa4d8..2dae5b8154 100644
--- a/packages/player-example/pages/index.tsx
+++ b/packages/player-example/pages/index.tsx
@@ -19,28 +19,8 @@ function Index() {
justifyContent: 'center',
}}
>
- <App component={CarSlideshow} durationInFrames={500} />
- <App component={VideoautoplayDemo} durationInFrames={2700} />
- <App component={NativeBufferState} durationInFrames={2700} />
+ <App component={CarSlideshow} durationInFrames={100} />
</div>
- <h2>Thumbnail</h2>
- <Thumbnail
- component={CarSlideshow}
- frameToDisplay={480}
- compositionHeight={200}
- compositionWidth={500}
- durationInFrames={5000}
- fps={30}
- style={{
- border: '4px solid red',
- }}
- inputProps={{
- title: 'Hi there',
- bgColor: 'black',
- color: 'white',
- }}
- />
- <ThumbnailDemo />
</React.StrictMode>
);
}
diff --git a/packages/player-example/public/ai.mp4 b/packages/player-example/public/ai.mp4
new file mode 100644
index 0000000000..ab09e8ded1
Binary files /dev/null and b/packages/player-example/public/ai.mp4 differ
diff --git a/packages/player-example/src/App.tsx b/packages/player-example/src/App.tsx
index aae7e21956..b0d0983c8f 100644
--- a/packages/player-example/src/App.tsx
+++ b/packages/player-example/src/App.tsx
@@ -713,9 +713,9 @@ export default ({
playbackRate={playbackRate}
spaceKeyToPlayOrPause={spaceKeyToPlayOrPause}
playerRef={ref}
- showPosterWhenEnded={showPosterWhenEnded}
- showPosterWhenPaused={showPosterWhenPaused}
- showPosterWhenUnplayed={showPosterWhenUnplayed}
+ showPosterWhenEnded={false}
+ showPosterWhenPaused={false}
+ showPosterWhenUnplayed={false}
showPosterWhenBuffering={showPosterWhenBuffering}
showVolumeControls={showVolumeControls}
showPlaybackRateControl={showPlaybackRateControl}
diff --git a/packages/player-example/src/CarSlideshow.tsx b/packages/player-example/src/CarSlideshow.tsx
index d920253885..99a3c05bf6 100644
--- a/packages/player-example/src/CarSlideshow.tsx
+++ b/packages/player-example/src/CarSlideshow.tsx
@@ -8,6 +8,7 @@ import {
staticFile,
Sequence,
Experimental,
+ OffthreadVideo,
} from 'remotion';
type Props = {
@@ -21,30 +22,7 @@ export const playerExampleComp = createRef<{
}>();
const CarSlideshow = ({title, bgColor, color}: Props) => {
- const frame = useCurrentFrame();
- const {width, height, durationInFrames} = useVideoConfig();
- const left = interpolate(frame, [0, durationInFrames], [width, width * -1]);
-
- const [shouldThrowError, setThrowError] = useState(false);
-
- const dummyText = useCallback(() => {
- if (shouldThrowError) {
- throw new Error('some error');
- }
- return '';
- }, [shouldThrowError]);
-
- useImperativeHandle(
- playerExampleComp,
- () => {
- return {
- triggerError: () => {
- setThrowError(true);
- },
- };
- },
- [],
- );
+ const {width, height} = useVideoConfig();
return (
<div
@@ -57,36 +35,8 @@ const CarSlideshow = ({title, bgColor, color}: Props) => {
top: 0,
}}
>
- <Experimental.Clipper height={100} width={100} x={0} y={0} />
- <Sequence>
- <h1
- style={{
- fontSize: '5em',
- fontWeight: 'bold',
- position: 'absolute',
- top: height / 2 - 100,
- left,
- color,
- whiteSpace: 'nowrap',
- }}
- >
- {title} {dummyText()}
- </h1>
- </Sequence>
- <Img
- src={staticFile('/logo.png')}
- style={{
- height: 40,
- width: 40,
- }}
- />
- <Sequence from={10}>
- <Video
- style={{
- height: 200,
- }}
- src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
- />
+ <Sequence premountFor={100}>
+ <OffthreadVideo pauseWhenBuffering src={staticFile('ai.mp4')} />
</Sequence>
</div>
);