🎥 Make videos programmatically with React
Update Three.js VideoTexture
Jonny Burger41af97832917
diff --git a/bun.lock b/bun.lockindex dadfad9091..20b359eedc 100644--- a/bun.lock+++ b/bun.lock@@ -1885,6 +1885,7 @@"dependencies": {"@react-three/fiber": "9.2.0","@remotion/cli": "workspace:*",+ "@remotion/media": "workspace:*","@remotion/three": "workspace:*","@remotion/zod-types": "workspace:*","mediabunny": "1.25.8",diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsxindex c77ceb07c5..941665c9bf 100644--- a/packages/media/src/audio/audio-for-preview.tsx+++ b/packages/media/src/audio/audio-for-preview.tsx@@ -178,6 +178,7 @@ const AudioForPreviewAssertedShowing: React.FC<NewAudioForPreviewProps> = ({isPostmounting,isPremounting,globalPlaybackRate,+ onVideoFrameCallback: null,});mediaPlayerRef.current = player;diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 0036f0272b..0a7b3b3955 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -84,6 +84,7 @@ export class MediaPlayer {bufferState,isPremounting,isPostmounting,+ onVideoFrameCallback,}: {canvas: HTMLCanvasElement | OffscreenCanvas | null;src: string;@@ -100,6 +101,7 @@ export class MediaPlayer {bufferState: ReturnType<typeof useBufferState>;isPremounting: boolean;isPostmounting: boolean;+ onVideoFrameCallback: null | ((frame: CanvasImageSource) => void);}) {this.canvas = canvas ?? null;this.src = src;@@ -117,6 +119,7 @@ export class MediaPlayer {this.isPremounting = isPremounting;this.isPostmounting = isPostmounting;this.nonceManager = makeNonceManager();+ this.onVideoFrameCallback = onVideoFrameCallback;this.input = new Input({source: new UrlSource(this.src),diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsxindex c90052f589..622ab17596 100644--- a/packages/media/src/video/video-for-preview.tsx+++ b/packages/media/src/video/video-for-preview.tsx@@ -85,6 +85,7 @@ const VideoForPreviewAssertedShowing: React.FC<VideoForPreviewProps> = ({const mediaPlayerRef = useRef<MediaPlayer | null>(null);const initialTrimBeforeRef = useRef(trimBefore);const initialTrimAfterRef = useRef(trimAfter);+ const initialOnVideoFrameRef = useRef(onVideoFrame);const [mediaPlayerReady, setMediaPlayerReady] = useState(false);const [shouldFallbackToNativeVideo, setShouldFallbackToNativeVideo] =@@ -186,6 +187,7 @@ const VideoForPreviewAssertedShowing: React.FC<VideoForPreviewProps> = ({isPremounting,isPostmounting,globalPlaybackRate,+ onVideoFrameCallback: initialOnVideoFrameRef.current ?? null,});mediaPlayerRef.current = player;diff --git a/packages/template-three/package.json b/packages/template-three/package.jsonindex b41d563ce1..2803c0e31b 100644--- a/packages/template-three/package.json+++ b/packages/template-three/package.json@@ -13,6 +13,7 @@"dependencies": {"@react-three/fiber": "9.2.0","@remotion/cli": "workspace:*",+ "@remotion/media": "workspace:*","@remotion/three": "workspace:*","@remotion/zod-types": "workspace:*","react": "19.2.3",diff --git a/packages/template-three/src/Phone.tsx b/packages/template-three/src/Phone.tsxindex 57c29fbd11..17f3c34a65 100644--- a/packages/template-three/src/Phone.tsx+++ b/packages/template-three/src/Phone.tsx@@ -4,27 +4,21 @@ import { interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";import { Texture } from "three";import {CAMERA_DISTANCE,- getPhoneLayout,PHONE_CURVE_SEGMENTS,PHONE_SHININESS,+ PhoneLayout,} from "./helpers/layout";import { roundedRect } from "./helpers/rounded-rectangle";import { RoundedBox } from "./RoundedBox";export const Phone: React.FC<{- readonly videoTexture: Texture | null;- readonly aspectRatio: number;- readonly baseScale: number;+ readonly videoTexture: Texture;readonly phoneColor: string;-}> = ({ aspectRatio, videoTexture, baseScale, phoneColor }) => {+ phoneLayout: PhoneLayout;+}> = ({ videoTexture, phoneColor, phoneLayout }) => {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);@@ -35,14 +29,6 @@ export const Phone: React.FC<{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(@@ -80,11 +66,15 @@ export const Phone: React.FC<{// Calculate a rounded rectangle for the phone screenconst screenGeometry = useMemo(() => {return roundedRect({- width: layout.screen.width,- height: layout.screen.height,- radius: layout.screen.radius,+ width: phoneLayout.screen.width,+ height: phoneLayout.screen.height,+ radius: phoneLayout.screen.radius,});- }, [layout.screen.height, layout.screen.radius, layout.screen.width]);+ }, [+ phoneLayout.screen.height,+ phoneLayout.screen.radius,+ phoneLayout.screen.width,+ ]);return (<group@@ -93,24 +83,22 @@ export const Phone: React.FC<{position={[0, translateY, 0]}><RoundedBox- radius={layout.phone.radius}- depth={layout.phone.thickness}+ radius={phoneLayout.phone.radius}+ depth={phoneLayout.phone.thickness}curveSegments={PHONE_CURVE_SEGMENTS}- position={layout.phone.position}- width={layout.phone.width}- height={layout.phone.height}+ position={phoneLayout.phone.position}+ width={phoneLayout.phone.width}+ height={phoneLayout.phone.height}><meshPhongMaterial color={phoneColor} shininess={PHONE_SHININESS} /></RoundedBox>- <mesh position={layout.screen.position}>+ <mesh position={phoneLayout.screen.position}><shapeGeometry args={[screenGeometry]} />- {videoTexture ? (- <meshBasicMaterial- color={0xffffff}- toneMapped={false}- map={videoTexture}- />- ) : null}+ <meshBasicMaterial+ color={0xffffff}+ toneMapped={false}+ map={videoTexture}+ /></mesh></group>);diff --git a/packages/template-three/src/Root.tsx b/packages/template-three/src/Root.tsxindex 2e0f5d4b77..3b2e8917d8 100644--- a/packages/template-three/src/Root.tsx+++ b/packages/template-three/src/Root.tsx@@ -1,5 +1,6 @@-import { Composition } from "remotion";+import { Composition, staticFile } from "remotion";import { Scene, myCompSchema } from "./Scene";+import { getMediaMetadata } from "./helpers/get-media-metadata";// Welcome to the Remotion Three Starter Kit!// Two compositions have been created, showing how to use@@ -22,8 +23,8 @@ export const RemotionRoot: React.FC = () => {<Compositionid="Scene"component={Scene}- durationInFrames={300}fps={30}+ durationInFrames={300}width={1280}height={720}schema={myCompSchema}@@ -31,6 +32,24 @@ export const RemotionRoot: React.FC = () => {deviceType: "phone",phoneColor: "rgba(110, 152, 191, 0.00)" as const,baseScale: 1,+ mediaMetadata: null,+ videoSrc: null,+ }}+ calculateMetadata={async ({ props }) => {+ const videoSrc =+ props.deviceType === "phone"+ ? staticFile("phone.mp4")+ : staticFile("tablet.mp4");++ const mediaMetadata = await getMediaMetadata(videoSrc);++ return {+ props: {+ ...props,+ mediaMetadata,+ videoSrc,+ },+ };}}/></>diff --git a/packages/template-three/src/Scene.tsx b/packages/template-three/src/Scene.tsxindex 945daf1d87..700c97552e 100644--- a/packages/template-three/src/Scene.tsx+++ b/packages/template-three/src/Scene.tsx@@ -1,12 +1,13 @@-import { Html5Video, staticFile } from "remotion";-import { ThreeCanvas } from "@remotion/three";-import React, { useEffect, useRef, useState } from "react";+import { ThreeCanvas, ThreeCanvasRef } from "@remotion/three";+import React, { useCallback, useMemo, useRef, useState } from "react";import { AbsoluteFill, useVideoConfig } from "remotion";import { Phone } from "./Phone";import { z } from "zod";import { zColor } from "@remotion/zod-types";-import { useTexture } from "./use-texture";-import { getMediaMetadata } from "./helpers/get-media-metadata";+import { MediabunnyMetadata } from "./helpers/get-media-metadata";+import { Video } from "@remotion/media";+import { CanvasTexture, Texture } from "three";+import { getPhoneLayout } from "./helpers/layout";const container: React.CSSProperties = {backgroundColor: "white",@@ -27,46 +28,74 @@ type MyCompSchemaType = z.infer<typeof myCompSchema>;export const Scene: React.FC<{readonly baseScale: number;+ mediaMetadata: MediabunnyMetadata | null;+ videoSrc: string | null;} & MyCompSchemaType-> = ({ baseScale, phoneColor, deviceType }) => {- const videoRef = useRef<HTMLVideoElement>(null);+> = ({ baseScale, phoneColor, mediaMetadata, videoSrc }) => {const { width, height } = useVideoConfig();- const [videoData, setVideoData] = useState<{- width: number;- height: number;- } | null>(null);- const videoSrc =- deviceType === "phone" ? staticFile("phone.mp4") : staticFile("tablet.mp4");+ if (!mediaMetadata) {+ throw new Error("Media metadata is not supported yet");+ }+ if (!videoSrc) {+ throw new Error("Video source is not supported yet");+ }- useEffect(() => {- getMediaMetadata(videoSrc)- .then((data) => setVideoData(data.dimensions))- .catch((err) => console.log(err));- }, [videoSrc]);+ const [canvasTexture] = useState(() => {+ return new OffscreenCanvas(+ mediaMetadata.dimensions.width,+ mediaMetadata.dimensions.height,+ );+ });- const texture = useTexture(videoSrc, videoRef);+ const [context] = useState(() => {+ const context = canvasTexture.getContext("2d");+ if (!context) {+ throw new Error("Failed to get context");+ }+ return context;+ });++ const threeCanvasRef = useRef<ThreeCanvasRef>(null);++ const aspectRatio = useMemo(+ () => mediaMetadata.dimensions.width / mediaMetadata.dimensions.height,+ [mediaMetadata.dimensions.width, mediaMetadata.dimensions.height],+ );++ const layout = useMemo(+ () => getPhoneLayout(aspectRatio, baseScale),+ [aspectRatio, baseScale],+ );++ const [texture] = useState<Texture>(() => {+ const tex = new CanvasTexture(canvasTexture);+ tex.repeat.y = 1 / layout.screen.height;+ tex.repeat.x = 1 / layout.screen.width;+ return tex;+ });++ const onVideoFrame = useCallback(+ (frame: CanvasImageSource) => {+ context.drawImage(frame, 0, 0);+ texture.needsUpdate = true;+ threeCanvasRef.current?.invalidate();+ },+ [context, texture],+ );return (<AbsoluteFill style={container}>- <Html5Video- ref={videoRef}- src={videoSrc}- style={videoStyle}- pauseWhenBuffering- />- {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.width / videoData.height}- />- </ThreeCanvas>- ) : null}+ <Video src={videoSrc} style={videoStyle} onVideoFrame={onVideoFrame} />+ <ThreeCanvas ref={threeCanvasRef} linear width={width} height={height}>+ <ambientLight intensity={1.5} color={0xffffff} />+ <pointLight position={[10, 10, 0]} />+ <Phone+ phoneColor={phoneColor}+ phoneLayout={layout}+ videoTexture={texture}+ />+ </ThreeCanvas></AbsoluteFill>);};diff --git a/packages/template-three/src/helpers/get-media-metadata.ts b/packages/template-three/src/helpers/get-media-metadata.tsindex 6743c135d5..e439716931 100644--- a/packages/template-three/src/helpers/get-media-metadata.ts+++ b/packages/template-three/src/helpers/get-media-metadata.ts@@ -10,12 +10,13 @@ export const getMediaMetadata = async (src: string) => {const durationInSeconds = await input.computeDuration();const videoTrack = await input.getPrimaryVideoTrack();- const dimensions = videoTrack- ? {- width: videoTrack.displayWidth,- height: videoTrack.displayHeight,- }- : null;+ if (!videoTrack) {+ throw new Error("Video track not found");+ }+ const dimensions = {+ width: videoTrack.displayWidth,+ height: videoTrack.displayHeight,+ };const packetStats = await videoTrack?.computePacketStats(50);const fps = packetStats?.averagePacketRate ?? null;@@ -25,3 +26,5 @@ export const getMediaMetadata = async (src: string) => {fps,};};++export type MediabunnyMetadata = Awaited<ReturnType<typeof getMediaMetadata>>;diff --git a/packages/template-three/src/helpers/layout.ts b/packages/template-three/src/helpers/layout.tsindex 1e5f416174..c303a4f5a2 100644--- a/packages/template-three/src/helpers/layout.ts+++ b/packages/template-three/src/helpers/layout.ts@@ -36,7 +36,7 @@ type Layout = {radius: number;};-type PhoneLayout = {+export type PhoneLayout = {phone: Layout & {thickness: number;bevel: number;diff --git a/packages/three/src/ThreeCanvas.tsx b/packages/three/src/ThreeCanvas.tsxindex 01e91592c3..e81601d281 100644--- a/packages/three/src/ThreeCanvas.tsx+++ b/packages/three/src/ThreeCanvas.tsx@@ -1,6 +1,13 @@import type {RootState} from '@react-three/fiber';import {Canvas, useThree} from '@react-three/fiber';-import React, {useCallback, useEffect, useLayoutEffect, useState} from 'react';+import React, {+ useCallback,+ useEffect,+ useImperativeHandle,+ useLayoutEffect,+ useRef,+ useState,+} from 'react';import {Internals,useCurrentFrame,@@ -45,53 +52,90 @@ const FiberFrameInvalidator = () => {return null;};+type InvalidatorRef = {+ readonly invalidate: () => void;+};++const Invalidator = React.forwardRef<InvalidatorRef, {}>((_, ref) => {+ const {invalidate} = useThree();++ useImperativeHandle(ref, () => {+ return {+ invalidate,+ };+ }, [invalidate]);++ return null;+});++export type ThreeCanvasRef = {+ invalidate: () => void;+};+/** @description A wrapper for React Three Fiber's <Canvas /> which synchronizes with Remotion's useCurrentFrame().* @see [Documentation](https://www.remotion.dev/docs/three-canvas)*/-export const ThreeCanvas = (props: ThreeCanvasProps) => {- const {isRendering} = useRemotionEnvironment();-- // https://r3f.docs.pmnd.rs/advanced/scaling-performance#on-demand-rendering- const shouldUseFrameloopDemand = isRendering;-- const {children, width, height, style, onCreated, ...rest} = props;- const {delayRender, continueRender} = useDelayRender();- const [waitForCreated] = useState(() =>- delayRender('Waiting for <ThreeCanvas/> to be created'),- );-- validateDimension(width, 'width', 'of the <ThreeCanvas /> component');- validateDimension(height, 'height', 'of the <ThreeCanvas /> component');- const contexts = Internals.useRemotionContexts();- const actualStyle = {- width: props.width,- height: props.height,- ...(style ?? {}),- };-- const remotion_onCreated: typeof onCreated = useCallback(- (state: RootState) => {- continueRender(waitForCreated);- onCreated?.(state);- },- [onCreated, waitForCreated, continueRender],- );-- return (- <SuspenseLoader>- <Canvas- style={actualStyle}- {...rest}- frameloop={shouldUseFrameloopDemand ? 'demand' : 'always'}- onCreated={remotion_onCreated}- >- <Scale width={width} height={height} />- <Internals.RemotionContextProvider contexts={contexts}>- {shouldUseFrameloopDemand && <FiberFrameInvalidator />}- {children}- </Internals.RemotionContextProvider>- </Canvas>- </SuspenseLoader>- );-};+export const ThreeCanvas = React.forwardRef<ThreeCanvasRef, ThreeCanvasProps>(+ (props, ref) => {+ const {isRendering} = useRemotionEnvironment();++ // https://r3f.docs.pmnd.rs/advanced/scaling-performance#on-demand-rendering+ const shouldUseFrameloopDemand = isRendering;++ const {children, width, height, style, onCreated, ...rest} = props;+ const {delayRender, continueRender} = useDelayRender();+ const [waitForCreated] = useState(() =>+ delayRender('Waiting for <ThreeCanvas/> to be created'),+ );++ validateDimension(width, 'width', 'of the <ThreeCanvas /> component');+ validateDimension(height, 'height', 'of the <ThreeCanvas /> component');+ const contexts = Internals.useRemotionContexts();+ const actualStyle = {+ width: props.width,+ height: props.height,+ ...(style ?? {}),+ };++ const remotion_onCreated: typeof onCreated = useCallback(+ (state: RootState) => {+ continueRender(waitForCreated);+ onCreated?.(state);+ },+ [onCreated, waitForCreated, continueRender],+ );++ const invalidatorRef = useRef<InvalidatorRef>(null);++ React.useImperativeHandle(+ ref,+ () => ({+ invalidate: () => {+ invalidatorRef.current?.invalidate();+ },+ }),+ [],+ );++ return (+ <SuspenseLoader>+ <Canvas+ style={actualStyle}+ {...rest}+ frameloop={shouldUseFrameloopDemand ? 'demand' : 'always'}+ onCreated={remotion_onCreated}+ >+ <Scale width={width} height={height} />+ <Internals.RemotionContextProvider contexts={contexts}>+ {shouldUseFrameloopDemand && <FiberFrameInvalidator />}+ <Invalidator ref={invalidatorRef} />+ {children}+ </Internals.RemotionContextProvider>+ </Canvas>+ </SuspenseLoader>+ );+ },+);++ThreeCanvas.displayName = 'ThreeCanvas';diff --git a/packages/three/src/index.ts b/packages/three/src/index.tsindex 08d8f05cc1..e5f639d0f2 100644--- a/packages/three/src/index.ts+++ b/packages/three/src/index.ts@@ -1,4 +1,4 @@-export {ThreeCanvas, ThreeCanvasProps} from './ThreeCanvas';+export {ThreeCanvas, ThreeCanvasProps, ThreeCanvasRef} from './ThreeCanvas';export {UseOffthreadVideoTextureOptions,useOffthreadVideoTexture,diff --git a/packages/three/src/use-offthread-video-texture.ts b/packages/three/src/use-offthread-video-texture.tsindex c7264c1bec..18f5132c74 100644--- a/packages/three/src/use-offthread-video-texture.ts+++ b/packages/three/src/use-offthread-video-texture.ts@@ -133,7 +133,14 @@ export function useOffthreadVideoTexture({const env = useRemotionEnvironment();- const {isRendering} = env;+ const {isRendering, isClientSideRendering} = env;++ if (isClientSideRendering) {+ throw new Error(+ 'useOffthreadVideoTexture() cannot be used in client side rendering.',+ );+ }+if (!isRendering) {throw new Error('useOffthreadVideoTexture() can only be used during rendering. Use useRemotionEnvironment().isRendering to render it conditionally.',