Skip to content

🎥 Make videos programmatically with React

new approach to frame seeking

Jonny Burgercc73b1c96aec
diff --git a/packages/core/src/test/get-current-time.test.ts b/packages/core/src/test/get-current-time.test.ts
index f7a4f9a579..f056903234 100644
--- a/packages/core/src/test/get-current-time.test.ts
+++ b/packages/core/src/test/get-current-time.test.ts
@@ -9,12 +9,10 @@ describe('correctly calculate media time of video element', () => {
test('mp4 - Should correctly calculate the media time of a video element', () => {
expect(
getMediaTime({
- fps: 30,
frame: 30,
playbackRate: 1,
- src: 'video.mp4',
startFrom: 0,
- mediaType: 'video',
+ fps: 30,
}),
).toBeCloseTo(1, mp4Precision);
});
@@ -22,12 +20,10 @@ describe('correctly calculate media time of video element', () => {
test('mp4 - Should correctly calculate the media time of a video element with faster framerate', () => {
expect(
getMediaTime({
- fps: 30,
frame: 30,
playbackRate: 2,
- src: 'video.mp4',
startFrom: 0,
- mediaType: 'video',
+ fps: 30,
}),
).toBeCloseTo(2, mp4Precision);
});
@@ -36,12 +32,10 @@ describe('correctly calculate media time of video element', () => {
// If playbackrate is 2, but the video only starts after 1 second, at 2sec, the video position should be 3sec
expect(
getMediaTime({
- fps: 30,
frame: 60,
playbackRate: 2,
- src: 'video.mp4',
startFrom: 30,
- mediaType: 'video',
+ fps: 30,
}),
).toBeCloseTo(3, mp4Precision);
});
@@ -51,12 +45,11 @@ describe('correctly calculate media time of video element', () => {
test('webm - Should correctly calculate the media time of a video element', () => {
expect(
getMediaTime({
- fps: 30,
frame: 30,
playbackRate: 1,
- src: 'video.webm',
+ fps: 30,
+
startFrom: 0,
- mediaType: 'video',
}),
).toBeCloseTo(1, webmPrecision);
});
@@ -64,12 +57,10 @@ describe('correctly calculate media time of video element', () => {
test('webm - Should correctly calculate the media time of a video element with faster framerate', () => {
expect(
getMediaTime({
- fps: 30,
frame: 30,
playbackRate: 2,
- src: 'video.webm',
+ fps: 30,
startFrom: 0,
- mediaType: 'video',
}),
).toBeCloseTo(2, webmPrecision);
});
@@ -78,12 +69,10 @@ describe('correctly calculate media time of video element', () => {
// If playbackrate is 2, but the video only starts after 1 second, at 2sec, the video position should be 3sec
expect(
getMediaTime({
- fps: 30,
frame: 60,
playbackRate: 2,
- src: 'video.webm',
+ fps: 30,
startFrom: 30,
- mediaType: 'video',
}),
).toBeCloseTo(3, webmPrecision);
});
diff --git a/packages/core/src/use-media-playback.ts b/packages/core/src/use-media-playback.ts
index a74d38a0c3..0e0e71d878 100644
--- a/packages/core/src/use-media-playback.ts
+++ b/packages/core/src/use-media-playback.ts
@@ -92,12 +92,10 @@ export const useMediaPlayback = ({
}
const desiredUnclampedTime = getMediaTime({
- fps,
frame,
- src,
playbackRate: localPlaybackRate,
startFrom: -mediaStartsAt,
- mediaType,
+ fps,
});
const {duration} = mediaRef.current;
const shouldBeTime =
diff --git a/packages/core/src/video/VideoForRendering.tsx b/packages/core/src/video/VideoForRendering.tsx
index cd011c6991..1b547cfce0 100644
--- a/packages/core/src/video/VideoForRendering.tsx
+++ b/packages/core/src/video/VideoForRendering.tsx
@@ -23,9 +23,9 @@ import {useTimelinePosition} from '../timeline-position-state.js';
import {useCurrentFrame} from '../use-current-frame.js';
import {useUnsafeVideoConfig} from '../use-unsafe-video-config.js';
import {evaluateVolume} from '../volume-prop.js';
-import {warnAboutNonSeekableMedia} from '../warn-about-non-seekable-media.js';
import {getMediaTime} from './get-current-time.js';
import type {RemotionVideoProps} from './props.js';
+import {seekToTimeMultipleUntilRight} from './seek-until-right.js';
type VideoForRenderingProps = RemotionVideoProps & {
onDuration: (src: string, durationInSeconds: number) => void;
@@ -149,16 +149,12 @@ const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<
return;
}
- const currentTime = (() => {
- return getMediaTime({
- fps: videoConfig.fps,
- frame,
- src: props.src as string,
- playbackRate: playbackRate || 1,
- startFrom: -mediaStartsAt,
- mediaType: 'video',
- });
- })();
+ const currentTime = getMediaTime({
+ frame,
+ playbackRate: playbackRate || 1,
+ startFrom: -mediaStartsAt,
+ fps: videoConfig.fps,
+ });
const handle = delayRender(`Rendering <Video /> with src="${props.src}"`);
if (process.env.NODE_ENV === 'test') {
continueRender(handle);
@@ -181,30 +177,16 @@ const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<
};
}
- current.currentTime = currentTime;
-
- const seekedHandler = () => {
- warnAboutNonSeekableMedia(current, 'exception');
-
- if (window.navigator.platform.startsWith('Mac')) {
- // Improve me: This is ensures frame perfectness but slows down render.
- // Please see this issue for context: https://github.com/remotion-dev/remotion/issues/200
-
- // Only affects macOS since it uses VideoToolbox decoding.
- setTimeout(() => {
- continueRender(handle);
- }, 100);
- } else {
- continueRender(handle);
- }
- };
-
- current.addEventListener('seeked', seekedHandler, {once: true});
-
const endedHandler = () => {
continueRender(handle);
};
+ seekToTimeMultipleUntilRight(current, currentTime, videoConfig.fps).then(
+ () => {
+ continueRender(handle);
+ },
+ );
+
current.addEventListener('ended', endedHandler, {once: true});
const errorHandler = () => {
@@ -231,7 +213,6 @@ const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<
return () => {
current.removeEventListener('ended', endedHandler);
current.removeEventListener('error', errorHandler);
- current.removeEventListener('seeked', seekedHandler);
continueRender(handle);
};
}, [
diff --git a/packages/core/src/video/get-current-time.ts b/packages/core/src/video/get-current-time.ts
index 1f4761c323..7a304ada7c 100644
--- a/packages/core/src/video/get-current-time.ts
+++ b/packages/core/src/video/get-current-time.ts
@@ -21,17 +21,13 @@ export const getExpectedMediaFrameUncorrected = ({
export const getMediaTime = ({
fps,
frame,
- src,
playbackRate,
startFrom,
- mediaType,
}: {
fps: number;
frame: number;
- src: string;
playbackRate: number;
startFrom: number;
- mediaType: 'video' | 'audio';
}) => {
const expectedFrame = getExpectedMediaFrameUncorrected({
frame,
@@ -39,23 +35,6 @@ export const getMediaTime = ({
startFrom,
});
- const isChrome =
- typeof window !== 'undefined' &&
- window.navigator.userAgent.match(/Chrome\/([0-9]+)/);
- if (
- isChrome &&
- Number(isChrome[1]) < 112 &&
- mediaType === 'video' &&
- src.endsWith('.mp4')
- ) {
- // In Chrome, for MP4s, if 30fps, the first frame is still displayed at 0.033333
- // even though after that it increases by 0.033333333 each.
- // So frame = 0 in Remotion is like frame = 1 for the browser
- return (expectedFrame + 1) / fps;
- }
-
- // For WebM videos, we need to add a little bit of shift to get the right frame.
const msPerFrame = 1000 / fps;
- const msShift = msPerFrame / 2;
- return (expectedFrame * msPerFrame + msShift) / 1000;
+ return (expectedFrame * msPerFrame) / 1000;
};
diff --git a/packages/core/src/video/seek-until-right.ts b/packages/core/src/video/seek-until-right.ts
new file mode 100644
index 0000000000..e681f4ee34
--- /dev/null
+++ b/packages/core/src/video/seek-until-right.ts
@@ -0,0 +1,57 @@
+export const seekToTime = (element: HTMLVideoElement, desiredTime: number) => {
+ element.currentTime = desiredTime;
+
+ let cancel: number;
+ const prom = new Promise<number>((resolve) => {
+ cancel = element.requestVideoFrameCallback((_cb, metadata) => {
+ resolve(metadata.mediaTime);
+ });
+ });
+
+ return {
+ wait: prom,
+ cancel: () => {
+ element.cancelVideoFrameCallback(cancel);
+ },
+ };
+};
+
+export const seekToTimeMultipleUntilRight = async (
+ element: HTMLVideoElement,
+ desiredTime: number,
+ fps: number,
+) => {
+ const seekedTo = await seekToTime(element, desiredTime).wait;
+ const difference = Math.abs(desiredTime - seekedTo);
+ const threshold = 1 / fps;
+ const ident = Math.random();
+
+ if (difference > threshold) {
+ console.log(
+ ident,
+ 'seekedTo',
+ seekedTo,
+ 'desiredTime',
+ desiredTime,
+ 'difference',
+ difference,
+ 'threshold',
+ threshold,
+ );
+ const sign = desiredTime > seekedTo ? 1 : -1;
+
+ const newTime = await seekToTime(
+ element,
+ desiredTime + (threshold / 2) * sign,
+ ).wait;
+ console.log(
+ ident,
+ 'before',
+ seekedTo,
+ 'after',
+ newTime,
+ 'desired',
+ desiredTime,
+ );
+ }
+};