🎥 Make videos programmatically with React
test both webm and mp4 for frame accuracy
Jonny Burgerc14a70f8c580
diff --git a/packages/core/src/video/VideoForDevelopment.tsx b/packages/core/src/video/VideoForDevelopment.tsxindex 56e7735ba7..51459783af 100644--- a/packages/core/src/video/VideoForDevelopment.tsx+++ b/packages/core/src/video/VideoForDevelopment.tsx@@ -5,6 +5,7 @@ import {usePlayingState} from '../timeline-position-state';import {useAbsoluteCurrentFrame, useCurrentFrame} from '../use-frame';import {useUnsafeVideoConfig} from '../use-unsafe-video-config';import {evaluateVolume} from '../volume-prop';+import {getCurrentTime} from './get-current-time';import {RemotionVideoProps} from './props';export const VideoForDevelopment: React.FC<RemotionVideoProps> = (props) => {@@ -67,10 +68,11 @@ export const VideoForDevelopment: React.FC<RemotionVideoProps> = (props) => {}const currentTime = (() => {if (FEATURE_FLAG_V2_BREAKING_CHANGES) {- // In Chrome, 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 (currentFrame + 1) / videoConfig.fps;+ return getCurrentTime({+ fps: videoConfig.fps,+ frame: currentFrame,+ src: props.src as string,+ });}return currentFrame / (1000 / videoConfig.fps);})();@@ -83,7 +85,7 @@ export const VideoForDevelopment: React.FC<RemotionVideoProps> = (props) => {videoRef.current.currentTime = currentTime;videoRef.current.play();}- }, [currentFrame, playing, videoConfig, absoluteFrame]);+ }, [currentFrame, playing, videoConfig, absoluteFrame, props.src]);return <video ref={videoRef} {...nativeProps} />;};diff --git a/packages/core/src/video/VideoForRendering.tsx b/packages/core/src/video/VideoForRendering.tsxindex 87744f9f53..95e4ef3a5e 100644--- a/packages/core/src/video/VideoForRendering.tsx+++ b/packages/core/src/video/VideoForRendering.tsx@@ -9,6 +9,7 @@ import {SequenceContext} from '../sequencing';import {useCurrentFrame} from '../use-frame';import {useUnsafeVideoConfig} from '../use-unsafe-video-config';import {evaluateVolume} from '../volume-prop';+import {getCurrentTime} from './get-current-time';import {RemotionVideoProps} from './props';export const VideoForRendering: React.FC<RemotionVideoProps> = ({@@ -84,10 +85,11 @@ export const VideoForRendering: React.FC<RemotionVideoProps> = ({const currentTime = (() => {if (FEATURE_FLAG_V2_BREAKING_CHANGES) {- // In Chrome, 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 (frame + 1) / videoConfig.fps;+ return getCurrentTime({+ fps: videoConfig.fps,+ frame,+ src: props.src as string,+ });}return frame / (1000 / videoConfig.fps);})();diff --git a/packages/core/src/video/get-current-time.ts b/packages/core/src/video/get-current-time.tsnew file mode 100644index 0000000000..0bff2eb4bb--- /dev/null+++ b/packages/core/src/video/get-current-time.ts@@ -0,0 +1,19 @@+export const getCurrentTime = ({+ fps,+ frame,+ src,+}: {+ fps: number;+ frame: number;+ src: string;+}) => {+ if (src.endsWith('mp4')) {+ // In Chrome, 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 (frame + 1) / fps;+ }+ const msPerFrame = 1000 / fps;+ const msShift = msPerFrame / 2;+ return (frame * msPerFrame + msShift) / 1000;+};diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsxindex 15df190198..0e329fa353 100644--- a/packages/example/src/Video.tsx+++ b/packages/example/src/Video.tsx@@ -179,12 +179,26 @@ export const Index: React.FC = () => {durationInFrames={10}/><Composition- id="video-testing"+ id="video-testing-mp4"component={VideoTesting}width={1080}height={1080}fps={30}durationInFrames={100}+ defaultProps={{+ codec: 'mp4',+ }}+ />+ <Composition+ id="video-testing-webm"+ component={VideoTesting}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={100}+ defaultProps={{+ codec: 'webm',+ }}/><Compositionid="framer"diff --git a/packages/example/src/VideoTesting/framer.mp4 b/packages/example/src/VideoTesting/framer.mp4new file mode 100644index 0000000000..9934affe34Binary files /dev/null and b/packages/example/src/VideoTesting/framer.mp4 differdiff --git a/packages/example/src/VideoTesting/index.tsx b/packages/example/src/VideoTesting/index.tsxindex f8c71087ff..8497c8a904 100644--- a/packages/example/src/VideoTesting/index.tsx+++ b/packages/example/src/VideoTesting/index.tsx@@ -1,12 +1,15 @@import {Sequence, useVideoConfig, Video} from 'remotion';-import video from './framer.webm';+import videoMp4 from './framer.mp4';+import videoWebm from './framer.webm';-export const VideoTesting: React.FC = () => {+export const VideoTesting: React.FC<{+ codec: 'mp4' | 'webm';+}> = ({codec}) => {const {durationInFrames} = useVideoConfig();return (<div><Sequence from={0} durationInFrames={durationInFrames}>- <Video src={video} />+ <Video src={codec === 'mp4' ? videoMp4 : videoWebm} /></Sequence></div>);diff --git a/tests/frame-accuracy.test.ts b/tests/frame-accuracy.test.tsindex c98e5498b4..acc4a552d1 100644--- a/tests/frame-accuracy.test.ts+++ b/tests/frame-accuracy.test.ts@@ -3,70 +3,82 @@ import fs from "fs";import os from "os";import path from "path";import sharp from "sharp";+import { selectColor } from "../packages/example/src/Framer";-import {selectColor} from "../packages/example/src/Framer";+const getMissedFramesforCodec = async (codec: "mp4" | "webm") => {+ const outputPath = await fs.promises.mkdtemp(+ path.join(os.tmpdir(), "remotion-")+ );-test('should render correct frames from embedded videos', async () => {- const outputPath = await fs.promises.mkdtemp(- path.join(os.tmpdir(), 'remotion-')- );-- // render the VideoTesting example (which contains the Framer composition embedded with <Video>) to an image- // sequence which can be checked for accuracy- await execa(- "npx",- [- "remotion",- "render",- "src/index.tsx",- "video-testing",- outputPath,- "--image-format",- "jpeg",- "--quality",- "100",- "--sequence",- ],- {- cwd: "packages/example",- reject: false,- }- );+ // render the VideoTesting example (which contains the Framer composition embedded with <Video>) to an image+ // sequence which can be checked for accuracy+ await execa(+ "npx",+ [+ "remotion",+ "render",+ "src/index.tsx",+ `video-testing-${codec}`,+ outputPath,+ "--image-format",+ "jpeg",+ "--quality",+ "100",+ "--sequence",+ ],+ {+ cwd: "packages/example",+ reject: false,+ }+ );- let missedFrames = 0;+ let missedFrames = 0;- for (let frame = 0; frame < 100; frame++) {- // each frame of the embedded video contains a (deterministically) random color which should appear correctly- // in the rendered output- const expectedColor = {- red: selectColor('red', frame),- green: selectColor('green', frame),- blue: selectColor('blue', frame),- };+ for (let frame = 0; frame < 100; frame++) {+ // each frame of the embedded video contains a (deterministically) random color which should appear correctly+ // in the rendered output+ const expectedColor = {+ red: selectColor("red", frame),+ green: selectColor("green", frame),+ blue: selectColor("blue", frame),+ };- // extract the actual RGB color value of the top left pixel in the frame image that was generated by remotion- const paddedIndex = String(frame).padStart(2, '0');- const filename = path.join(outputPath, `element-${paddedIndex}.jpeg`);- const img = await sharp(filename).raw().toBuffer();+ // extract the actual RGB color value of the top left pixel in the frame image that was generated by remotion+ const paddedIndex = String(frame).padStart(2, "0");+ const filename = path.join(outputPath, `element-${paddedIndex}.jpeg`);+ const img = await sharp(filename).raw().toBuffer();- const actualColor = {- red: img.readUInt8(0),- green: img.readUInt8(1),- blue: img.readUInt8(2),- };+ const actualColor = {+ red: img.readUInt8(0),+ green: img.readUInt8(1),+ blue: img.readUInt8(2),+ };- const colorDistance = {- red: Math.abs(expectedColor.red - actualColor.red),- green: Math.abs(expectedColor.green - actualColor.green),- blue: Math.abs(expectedColor.blue - actualColor.blue),- };+ const colorDistance = {+ red: Math.abs(expectedColor.red - actualColor.red),+ green: Math.abs(expectedColor.green - actualColor.green),+ blue: Math.abs(expectedColor.blue - actualColor.blue),+ };- // encoding sometimes shifts the color slightly - so measure the distance between the expected and actual- // colors and consider any frame not within an acceptable range to be wrong- if (colorDistance.red > 5 || colorDistance.green > 5 || colorDistance.blue > 5) {- missedFrames++;- }+ // encoding sometimes shifts the color slightly - so measure the distance between the expected and actual+ // colors and consider any frame not within an acceptable range to be wrong+ const combinedDistance =+ colorDistance.red + colorDistance.green + colorDistance.blue;+ const threshold = codec === "mp4" ? 49 : 12;+ if (combinedDistance > threshold) {+ console.log(colorDistance);+ missedFrames++;}+ }+ return missedFrames;+};++test("should render correct frames from embedded videos - WebM", async () => {+ const missedFrames = await getMissedFramesforCodec("webm");+ expect(missedFrames).toBe(0);+});- expect(missedFrames).toBe(0);-});\ No newline at end of file+test("should render correct frames from embedded videos - MP4", async () => {+ const missedFrames = await getMissedFramesforCodec("mp4");+ expect(missedFrames).toBe(0);+});