🎥 Make videos programmatically with React
loop based on a state
Jonny Burger17441deeca78
diff --git a/packages/core/src/video/OffthreadVideo.tsx b/packages/core/src/video/OffthreadVideo.tsxindex 8ebff4a978..bc3b9adc0a 100644--- a/packages/core/src/video/OffthreadVideo.tsx+++ b/packages/core/src/video/OffthreadVideo.tsx@@ -1,4 +1,4 @@-import React from 'react';+import React, {useCallback} from 'react';import {getRemotionEnvironment} from '../get-environment';import {Sequence} from '../Sequence';import {validateMediaProps} from '../validate-media-props';@@ -13,6 +13,8 @@ export const OffthreadVideo: React.FC<> = (props) => {const {startFrom, endAt, ...otherProps} = props;+ const onDuration = useCallback(() => undefined, []);+if (typeof startFrom !== 'undefined' || typeof endAt !== 'undefined') {validateStartFromProps(startFrom, endAt);@@ -37,5 +39,11 @@ export const OffthreadVideo: React.FC<return <OffthreadVideoForRendering {...otherProps} />;}- return <VideoForDevelopment onlyWarnForMediaSeekingError {...otherProps} />;+ return (+ <VideoForDevelopment+ onDuration={onDuration}+ onlyWarnForMediaSeekingError+ {...otherProps}+ />+ );};diff --git a/packages/core/src/video/Video.tsx b/packages/core/src/video/Video.tsxindex 9bfa741b1c..8c347ac8f3 100644--- a/packages/core/src/video/Video.tsx+++ b/packages/core/src/video/Video.tsx@@ -1,8 +1,11 @@-import React, {forwardRef} from 'react';+import React, {forwardRef, useCallback, useReducer} from 'react';import {getRemotionEnvironment} from '../get-environment';+import {Loop} from '../loop';import {Sequence} from '../Sequence';+import {useVideoConfig} from '../use-video-config';import {validateMediaProps} from '../validate-media-props';import {validateStartFromProps} from '../validate-start-from-props';+import {durationReducer} from './duration-state';import type {RemotionMainVideoProps, RemotionVideoProps} from './props';import {VideoForDevelopment} from './VideoForDevelopment';import {VideoForRendering} from './VideoForRendering';@@ -12,11 +15,27 @@ const VideoForwardingFunction: React.ForwardRefRenderFunction<RemotionVideoProps & RemotionMainVideoProps> = (props, ref) => {const {startFrom, endAt, ...otherProps} = props;+ const {loop, ...propsOtherThanLoop} = props;+ const {fps} = useVideoConfig();++ const [durations, setDurations] = useReducer(durationReducer, {});if (typeof ref === 'string') {throw new Error('string refs are not supported');}+ const onDuration = useCallback((src: string, durationInSeconds: number) => {+ setDurations({type: 'got-duration', durationInSeconds, src});+ }, []);++ if (loop && props.src && durations[props.src as string] !== undefined) {+ return (+ <Loop durationInFrames={Math.round(durations[props.src as string] * fps)}>+ <Video {...propsOtherThanLoop} ref={ref} />+ </Loop>+ );+ }+if (typeof startFrom !== 'undefined' || typeof endAt !== 'undefined') {validateStartFromProps(startFrom, endAt);@@ -37,7 +56,9 @@ const VideoForwardingFunction: React.ForwardRefRenderFunction<validateMediaProps(props, 'Video');if (getRemotionEnvironment() === 'rendering') {- return <VideoForRendering {...otherProps} ref={ref} />;+ return (+ <VideoForRendering onDuration={onDuration} {...otherProps} ref={ref} />+ );}return (@@ -45,6 +66,7 @@ const VideoForwardingFunction: React.ForwardRefRenderFunction<onlyWarnForMediaSeekingError={false}{...otherProps}ref={ref}+ onDuration={onDuration}/>);};diff --git a/packages/core/src/video/VideoForDevelopment.tsx b/packages/core/src/video/VideoForDevelopment.tsxindex 6270c465ba..2eee8a48a9 100644--- a/packages/core/src/video/VideoForDevelopment.tsx+++ b/packages/core/src/video/VideoForDevelopment.tsx@@ -8,13 +8,11 @@ import React, {} from 'react';import {useFrameForVolumeProp} from '../audio/use-audio-frame';import {continueRender, delayRender} from '../delay-render';-import {Loop} from '../loop';import {usePreload} from '../prefetch';import {useMediaInTimeline} from '../use-media-in-timeline';import {useMediaPlayback} from '../use-media-playback';import {useMediaTagVolume} from '../use-media-tag-volume';import {useSyncVolumeWithMediaTag} from '../use-sync-volume-with-media-tag';-import {useVideoConfig} from '../use-video-config';import {useMediaMutedState,useMediaVolumeState,@@ -23,6 +21,7 @@ import type {RemotionVideoProps} from './props';type VideoForDevelopmentProps = RemotionVideoProps & {onlyWarnForMediaSeekingError: boolean;+ onDuration: (src: string, durationInSeconds: number) => void;};const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<@@ -32,10 +31,8 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<const videoRef = useRef<HTMLVideoElement>(null);const [checkLoop] = useState(() => delayRender());- const videoDuration = useRef<number | null>(null);const volumePropFrame = useFrameForVolumeProp();- const {fps} = useVideoConfig();const {volume,@@ -43,6 +40,7 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<playbackRate,onlyWarnForMediaSeekingError,src,+ onDuration,...nativeProps} = props;@@ -92,7 +90,7 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<}current.onloadedmetadata = () => {- videoDuration.current = current.duration;+ onDuration(src as string, current.duration);continueRender(checkLoop);};@@ -111,20 +109,7 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<return () => {current.removeEventListener('error', errorHandler);};- }, [src, checkLoop]);-- if (props.loop && videoDuration.current) {- return (- <Loop durationInFrames={Math.round(videoDuration.current * fps)}>- <VideoForDevelopment- {...props}- ref={videoRef}- src={actualSrc}- loop={false}- />- </Loop>- );- }+ }, [src, checkLoop, onDuration]);return (<videodiff --git a/packages/core/src/video/VideoForRendering.tsx b/packages/core/src/video/VideoForRendering.tsxindex cc99e26567..0c6f18b926 100644--- a/packages/core/src/video/VideoForRendering.tsx+++ b/packages/core/src/video/VideoForRendering.tsx@@ -4,6 +4,7 @@ import React, {useContext,useEffect,useImperativeHandle,+ useLayoutEffect,useMemo,useRef,} from 'react';@@ -14,6 +15,7 @@ import {} from '../audio/use-audio-frame';import {CompositionManager} from '../CompositionManager';import {continueRender, delayRender} from '../delay-render';+import {getRemotionEnvironment} from '../get-environment';import {isApproximatelyTheSame} from '../is-approximately-the-same';import {random} from '../random';import {SequenceContext} from '../Sequence';@@ -25,9 +27,13 @@ import {warnAboutNonSeekableMedia} from '../warn-about-non-seekable-media';import {getMediaTime} from './get-current-time';import type {RemotionVideoProps} from './props';+type VideoForRenderingProps = RemotionVideoProps & {+ onDuration: (src: string, durationInSeconds: number) => void;+};+const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<HTMLVideoElement,- RemotionVideoProps+ VideoForRenderingProps> = ({onError, volume: volumeProp, playbackRate, ...props}, ref) => {const absoluteFrame = useTimelinePosition();@@ -210,11 +216,47 @@ const VideoForRenderingForwardFunction: React.ForwardRefRenderFunction<mediaStartsAt,]);+ const {src, onDuration} = props;++ // If video source switches, make new handle+ if (getRemotionEnvironment() === 'rendering') {+ // eslint-disable-next-line react-hooks/rules-of-hooks+ useLayoutEffect(() => {+ if (process.env.NODE_ENV === 'test') {+ return;+ }++ const newHandle = delayRender('Loading <Video> duration with src=' + src);+ const {current} = videoRef;++ const didLoad = () => {+ if (current) {+ onDuration(src as string, current.duration);+ }++ continueRender(newHandle);+ };++ if (current?.duration) {+ onDuration(src as string, current.duration);+ continueRender(newHandle);+ } else {+ current?.addEventListener('loadedmetadata', didLoad, {once: true});+ }++ // If tag gets unmounted, clear pending handles because video metadata is not going to load+ return () => {+ current?.removeEventListener('loadedmetadata', didLoad);+ continueRender(newHandle);+ };+ }, [src, onDuration]);+ }+return <video ref={videoRef} {...props} onError={onError} />;};export const VideoForRendering = forwardRef(VideoForRenderingForwardFunction) as ForwardRefExoticComponent<- RemotionVideoProps & RefAttributes<HTMLVideoElement>+ VideoForRenderingProps & RefAttributes<HTMLVideoElement>>;diff --git a/packages/core/src/video/duration-state.ts b/packages/core/src/video/duration-state.tsnew file mode 100644index 0000000000..6b26e5bc43--- /dev/null+++ b/packages/core/src/video/duration-state.ts@@ -0,0 +1,22 @@+type DurationState = Record<string, number>;++type DurationAction = {+ type: 'got-duration';+ src: string;+ durationInSeconds: number;+};++export const durationReducer = (+ state: DurationState,+ action: DurationAction+) => {+ switch (action.type) {+ case 'got-duration':+ return {+ ...state,+ [action.src]: action.durationInSeconds,+ };+ default:+ return state;+ }+};