🎥 Make videos programmatically with React
add phone scene to testbed
Jonny Burger8d8d9fb76fdd
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.tsindex 282c6b0b34..356bfaf6b2 100644--- a/packages/core/src/internals.ts+++ b/packages/core/src/internals.ts@@ -2,6 +2,7 @@ import {SharedAudioContext,SharedAudioContextProvider,} from './audio/shared-audio-tags.js';+import {useMediaStartsAt} from './audio/use-audio-frame.js';import {CanUseRemotionHooks,CanUseRemotionHooksProvider,@@ -140,6 +141,7 @@ export const Internals = {isIosSafari,WATCH_REMOTION_STATIC_FILES,addSequenceStackTraces,+ useMediaStartsAt,} as const;export type {diff --git a/packages/example/public/phone.mp4 b/packages/example/public/phone.mp4new file mode 100644index 0000000000..d805b460ddBinary files /dev/null and b/packages/example/public/phone.mp4 differdiff --git a/packages/example/public/tablet.mp4 b/packages/example/public/tablet.mp4new file mode 100644index 0000000000..a05d60b916Binary files /dev/null and b/packages/example/public/tablet.mp4 differdiff --git a/packages/example/src/ThreeScene/Phone.tsx b/packages/example/src/ThreeScene/Phone.tsxnew file mode 100644index 0000000000..4c5bd597c4--- /dev/null+++ b/packages/example/src/ThreeScene/Phone.tsx@@ -0,0 +1,117 @@+import {useThree} from '@react-three/fiber';+import React, {useEffect, useMemo} from 'react';+import {interpolate, spring, useCurrentFrame, useVideoConfig} from 'remotion';+import {Texture} from 'three';+import {+ CAMERA_DISTANCE,+ getPhoneLayout,+ PHONE_CURVE_SEGMENTS,+ PHONE_SHININESS,+} from './helpers/layout';+import {roundedRect} from './helpers/rounded-rectangle';+import {RoundedBox} from './RoundedBox';++export const Phone: React.FC<{+ videoTexture: Texture | null;+ aspectRatio: number;+ baseScale: number;+ phoneColor: string;+}> = ({aspectRatio, videoTexture, baseScale, phoneColor}) => {+ const frame = useCurrentFrame();+ const {fps, durationInFrames} = useVideoConfig();++ const layout = useMemo(+ () => getPhoneLayout(aspectRatio, baseScale),+ [aspectRatio, baseScale],+ );++ // Place a camera and set the distance to the object.+ // Then make it look at the object.+ const camera = useThree((state) => state.camera);+ useEffect(() => {+ camera.position.set(0, 0, CAMERA_DISTANCE);+ camera.near = 0.2;+ camera.far = Math.max(5000, CAMERA_DISTANCE * 2);+ camera.lookAt(0, 0, 0);+ }, [camera]);++ // Make the video fill the phone texture+ useEffect(() => {+ if (videoTexture) {+ videoTexture.repeat.y = 1 / layout.screen.height;+ videoTexture.repeat.x = 1 / layout.screen.width;+ }+ }, [aspectRatio, layout.screen.height, layout.screen.width, videoTexture]);++ // During the whole scene, the phone is rotating.+ // 2 * Math.PI is a full rotation.+ const constantRotation = interpolate(+ frame,+ [0, durationInFrames],+ [0, Math.PI * 6],+ );++ // When the composition starts, there is some extra+ // rotation and translation.+ const entranceAnimation = spring({+ frame,+ fps,+ config: {+ damping: 200,+ mass: 3,+ },+ });++ // Calculate the entrance rotation,+ // doing one full spin+ const entranceRotation = interpolate(+ entranceAnimation,+ [0, 1],+ [-Math.PI, Math.PI],+ );++ // Calculating the total rotation of the phone+ const rotateY = entranceRotation + constantRotation;++ // Calculating the translation of the phone at the beginning.+ // The start position of the phone is set to 4 "units"+ const translateY = interpolate(entranceAnimation, [0, 1], [-4, 0]);++ // Calculate a rounded rectangle for the phone screen+ const screenGeometry = useMemo(() => {+ return roundedRect({+ width: layout.screen.width,+ height: layout.screen.height,+ radius: layout.screen.radius,+ });+ }, [layout.screen.height, layout.screen.radius, layout.screen.width]);++ return (+ <group+ scale={entranceAnimation}+ rotation={[0, rotateY, 0]}+ position={[0, translateY, 0]}+ >+ <RoundedBox+ radius={layout.phone.radius}+ depth={layout.phone.thickness}+ curveSegments={PHONE_CURVE_SEGMENTS}+ position={layout.phone.position}+ width={layout.phone.width}+ height={layout.phone.height}+ >+ <meshPhongMaterial color={phoneColor} shininess={PHONE_SHININESS} />+ </RoundedBox>+ <mesh position={layout.screen.position}>+ <shapeGeometry args={[screenGeometry]} />+ {videoTexture ? (+ <meshBasicMaterial+ color={0xffffff}+ toneMapped={false}+ map={videoTexture}+ />+ ) : null}+ </mesh>+ </group>+ );+};diff --git a/packages/example/src/ThreeScene/RoundedBox.tsx b/packages/example/src/ThreeScene/RoundedBox.tsxnew file mode 100644index 0000000000..4f1b5de312--- /dev/null+++ b/packages/example/src/ThreeScene/RoundedBox.tsx@@ -0,0 +1,43 @@+import React, {useMemo} from 'react';+import {roundedRect} from './helpers/rounded-rectangle';++type Props = {+ width: number;+ height: number;+ radius: number;+ curveSegments: number;+ depth: number;+} & Omit<JSX.IntrinsicElements['mesh'], 'args'>;++export const RoundedBox: React.FC<Props> = ({+ width,+ height,+ radius,+ curveSegments,+ children,+ depth,+ ...otherProps+}) => {+ const shape = useMemo(+ () => roundedRect({width, height, radius}),+ [height, radius, width],+ );++ const params = useMemo(+ () => ({+ depth,+ bevelEnabled: true,+ bevelSize: 0,+ bevelThickness: 0,+ curveSegments,+ }),+ [curveSegments, depth],+ );++ return (+ <mesh {...otherProps}>+ <extrudeGeometry attach="geometry" args={[shape, params]} />+ {children}+ </mesh>+ );+};diff --git a/packages/example/src/ThreeScene/Scene.tsx b/packages/example/src/ThreeScene/Scene.tsxnew file mode 100644index 0000000000..442220820c--- /dev/null+++ b/packages/example/src/ThreeScene/Scene.tsx@@ -0,0 +1,72 @@+import {getVideoMetadata, VideoMetadata} from '@remotion/media-utils';+import {+ ThreeCanvas,+ useOffthreadVideoTexture,+ useVideoTexture,+} from '@remotion/three';+import {zColor} from '@remotion/zod-types';+import React, {useEffect, useRef, useState} from 'react';+import {AbsoluteFill, staticFile, useVideoConfig, Video} from 'remotion';+import {z} from 'zod';+import {Phone} from './Phone';++const container: React.CSSProperties = {+ backgroundColor: 'white',+};++const videoStyle: React.CSSProperties = {+ position: 'absolute',+ opacity: 0,+};++export const myCompSchema = z.object({+ phoneColor: zColor(),+ deviceType: z.enum(['phone', 'tablet']),+ textureType: z.enum(['video', 'offthreadvideo']),+});++type MyCompSchemaType = z.infer<typeof myCompSchema>;++export const VideoTextureDemo: React.FC<+ {+ baseScale: number;+ } & MyCompSchemaType+> = ({baseScale, phoneColor, deviceType, textureType}) => {+ const videoRef = useRef<HTMLVideoElement>(null);+ const {width, height} = useVideoConfig();+ const [videoData, setVideoData] = useState<VideoMetadata | null>(null);++ const videoSrc =+ deviceType === 'phone' ? staticFile('phone.mp4') : staticFile('tablet.mp4');++ useEffect(() => {+ getVideoMetadata(videoSrc)+ .then((data) => setVideoData(data))+ .catch((err) => console.log(err));+ }, [videoSrc]);++ const texture =+ textureType === 'offthreadvideo'+ ? // eslint-disable-next-line react-hooks/rules-of-hooks+ useOffthreadVideoTexture({src: videoSrc, videoRef})+ : // eslint-disable-next-line react-hooks/rules-of-hooks+ useVideoTexture(videoRef);++ return (+ <AbsoluteFill style={container}>+ <Video ref={videoRef} src={videoSrc} style={videoStyle} />+ {videoData ? (+ <ThreeCanvas linear width={width} height={height}>+ <ambientLight intensity={1.5} color={0xffffff} />+ <pointLight position={[10, 10, 0]} />+ <Phone+ phoneColor={phoneColor}+ baseScale={baseScale}+ videoTexture={texture}+ aspectRatio={videoData.aspectRatio}+ />+ </ThreeCanvas>+ ) : null}+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/ThreeScene/helpers/layout.ts b/packages/example/src/ThreeScene/helpers/layout.tsnew file mode 100644index 0000000000..5e89cc7416--- /dev/null+++ b/packages/example/src/ThreeScene/helpers/layout.ts@@ -0,0 +1,97 @@+import {Vector3} from '@react-three/fiber';++// The distance from which the camera is pointing to the phone.+export const CAMERA_DISTANCE = 2.5;++// A small number to avoid z-index flickering+export const Z_FLICKER_PREVENTION = 0.001;++// Shininess of the phone+export const PHONE_SHININESS = 30;++// In how many segments the phone rounded corners+// are divided. Increase number for smoother phone+export const PHONE_CURVE_SEGMENTS = 8;++// Calculate phone size. Whichever side is smaller gets+// normalized to the base scale.+const getPhoneHeight = (aspectRatio: number, baseScale: number): number => {+ if (aspectRatio > 1) {+ return baseScale;+ }+ return baseScale / aspectRatio;+};++const getPhoneWidth = (aspectRatio: number, baseScale: number): number => {+ if (aspectRatio < 1) {+ return baseScale;+ }+ return baseScale * aspectRatio;+};++type Layout = {+ position: Vector3;+ height: number;+ width: number;+ radius: number;+};++type PhoneLayout = {+ phone: Layout & {+ thickness: number;+ bevel: number;+ };+ screen: Layout;+};++export const getPhoneLayout = (+ // I recommend building the phone layout based+ // on the aspect ratio of the phone+ aspectRatio: number,+ // This value can be increased or decreased to tweak the+ // base value of the phone.+ baseScale: number,+): PhoneLayout => {+ // The depth of the phone body+ const phoneThickness = baseScale * 0.15;++ // How big the border of the phone is.+ const phoneBevel = baseScale * 0.04;++ // The inner radius of the phone, aka the screen radius+ const screenRadius = baseScale * 0.07;++ const phoneHeight = getPhoneHeight(aspectRatio, baseScale);+ const phoneWidth = getPhoneWidth(aspectRatio, baseScale);+ const phonePosition: Vector3 = [-phoneWidth / 2, -phoneHeight / 2, 0];+ const screenWidth = phoneWidth - phoneBevel * 2;+ const screenHeight = phoneHeight - phoneBevel * 2;+ const screenPosition: Vector3 = [+ -screenWidth / 2,+ -screenHeight / 2,+ phoneThickness + Z_FLICKER_PREVENTION,+ ];++ // Define the outer radius of the phone.+ // It looks better if the outer radius is a bit bigger than the screen radios,+ // formula taken from https://twitter.com/joshwcomeau/status/134978208002102886+ const phoneRadius =+ screenRadius + (getPhoneWidth(aspectRatio, baseScale) - screenWidth) / 2;++ return {+ phone: {+ position: phonePosition,+ height: phoneHeight,+ width: phoneWidth,+ radius: phoneRadius,+ thickness: phoneThickness,+ bevel: phoneBevel,+ },+ screen: {+ position: screenPosition,+ height: screenHeight,+ width: screenWidth,+ radius: screenRadius,+ },+ };+};diff --git a/packages/example/src/ThreeScene/helpers/rounded-rectangle.ts b/packages/example/src/ThreeScene/helpers/rounded-rectangle.tsnew file mode 100644index 0000000000..52e24dc6c3--- /dev/null+++ b/packages/example/src/ThreeScene/helpers/rounded-rectangle.ts@@ -0,0 +1,23 @@+import {Shape} from 'three';++export function roundedRect({+ width,+ height,+ radius,+}: {+ width: number;+ height: number;+ radius: number;+}): Shape {+ const roundedRectShape = new Shape();+ roundedRectShape.moveTo(0, radius);+ roundedRectShape.lineTo(0, height - radius);+ roundedRectShape.quadraticCurveTo(0, height, radius, height);+ roundedRectShape.lineTo(width - radius, height);+ roundedRectShape.quadraticCurveTo(width, height, width, height - radius);+ roundedRectShape.lineTo(width, radius);+ roundedRectShape.quadraticCurveTo(width, 0, width - radius, 0);+ roundedRectShape.lineTo(radius, 0);+ roundedRectShape.quadraticCurveTo(0, 0, 0, radius);+ return roundedRectShape;+}diff --git a/packages/three/src/use-offthread-video-texture.ts b/packages/three/src/use-offthread-video-texture.tsindex bb8c455880..7167fa1462 100644--- a/packages/three/src/use-offthread-video-texture.ts+++ b/packages/three/src/use-offthread-video-texture.ts@@ -1,10 +1,11 @@import {getVideoMetadata} from '@remotion/media-utils';-import {useCallback, useEffect, useMemo, useRef, useState} from 'react';+import {useCallback, useEffect, useMemo, useState} from 'react';import {cancelRender,continueRender,delayRender,getRemotionEnvironment,+ Internals,useCurrentFrame,useVideoConfig,} from 'remotion';@@ -33,60 +34,21 @@ export function useVideoDuration({src}: {src: string}) {return videoDuration;}-const useVideoRef = ({- src,- currentTime,-}: {- src: string;- currentTime: number;-}) => {- const videoRef = useRef<HTMLVideoElement | null>(null);-- const videoElement = useMemo(() => {- const video = document.createElement('video');- video.muted = true;- video.src = src;- video.style.display = 'none';-- // crossOrigin="anonymous" is important to allow CORS-enabled servers- // to be read from a canvas- video.crossOrigin = 'anonymous';-- return video;- }, [src]);-- useEffect(() => {- document.body.appendChild(videoElement);-- videoRef.current = videoElement;-- return () => {- document.body.removeChild(videoElement);- };- }, [videoElement]);-- useEffect(() => {- if (videoRef.current) {- videoRef.current.currentTime = currentTime;- }- }, [currentTime]);-- return {videoRef};-};--interface UseOffthreadVideoTextureProps {+export type UseOffthreadVideoTextureOptions = {src: string;+ videoRef: React.MutableRefObject<HTMLVideoElement | null>;loop?: boolean;playbackRate?: number;transparent?: boolean;-}+};export function useOffthreadVideoTexture({src,+ videoRef,loop = false,playbackRate = 1,transparent = false,-}: UseOffthreadVideoTextureProps) {+}: UseOffthreadVideoTextureOptions) {const frame = useCurrentFrame();const {fps} = useVideoConfig();@@ -95,15 +57,24 @@ export function useOffthreadVideoTexture({}const {isRendering} = getRemotionEnvironment();+ if (!isRendering) {+ // eslint-disable-next-line react-hooks/rules-of-hooks+ return useVideoTexture(videoRef);+ }++ // eslint-disable-next-line react-hooks/rules-of-hooks+ const mediaStartsAt = Internals.useMediaStartsAt();+ // eslint-disable-next-line react-hooks/rules-of-hooksconst videoDuration = useVideoDuration({src});+ // eslint-disable-next-line react-hooks/rules-of-hooksconst currentTime = useMemo(() => {let time =NoReactInternals.getExpectedMediaFrameUncorrected({frame,playbackRate,- startFrom: 0,+ startFrom: -mediaStartsAt,}) / fps;if (loop && videoDuration !== null) {@@ -111,8 +82,9 @@ export function useOffthreadVideoTexture({}return time;- }, [frame, fps, loop, videoDuration, playbackRate]);+ }, [frame, playbackRate, mediaStartsAt, fps, loop, videoDuration]);+ // eslint-disable-next-line react-hooks/rules-of-hooksconst offthreadVideoFrameSrc = useMemo(() => {return NoReactInternals.getOffthreadVideoSource({currentTime,@@ -121,8 +93,10 @@ export function useOffthreadVideoTexture({});}, [currentTime, src, transparent]);+ // eslint-disable-next-line react-hooks/rules-of-hooksconst [imageTexture, setImageTexture] = useState<THREE.Texture | null>(null);+ // eslint-disable-next-line react-hooks/rules-of-hooksconst fetchTexture = useCallback(() => {const imageTextureHandle = delayRender('fetch offthread video frame');@@ -140,8 +114,12 @@ export function useOffthreadVideoTexture({.catch((err) => {cancelRender(err);});+ return () => {+ continueRender(imageTextureHandle);+ };}, [offthreadVideoFrameSrc, isRendering]);+ // eslint-disable-next-line react-hooks/rules-of-hooksuseEffect(() => {fetchTexture();}, [offthreadVideoFrameSrc, fetchTexture]);@@ -150,9 +128,6 @@ export function useOffthreadVideoTexture({return imageTexture;}- // eslint-disable-next-line react-hooks/rules-of-hooks- const {videoRef} = useVideoRef({src, currentTime});-// eslint-disable-next-line react-hooks/rules-of-hooksconst videoTexture = useVideoTexture(videoRef);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 027e8ea212..9226454ea9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -850,6 +850,9 @@ importers:'@types/styled-components':specifier: ^5.1.26version: 5.1.26+ '@types/three':+ specifier: 0.157.2+ version: 0.157.2'@types/web':specifier: 0.0.78version: 0.0.78@@ -889,6 +892,9 @@ importers:styled-components:specifier: ^5.3.6+ three:+ specifier: 0.158.0+ version: 0.158.0ts-unused-exports:specifier: ^7.0.1version: 7.0.3([email protected])