🎥 Make videos programmatically with React
import React, {
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import type {EffectsOutputSize} from 'remotion';
import type {
EffectDefinitionAndStack,
LogLevel,
LoopVolumeCurveBehavior,
SequenceControls,
VolumeProp,
} from 'remotion';
import {
Html5Video,
Internals,
useBufferState,
useCurrentFrame,
useVideoConfig,
} from 'remotion';
import {getTimeInSeconds} from '../get-time-in-seconds';
import {frameForVolumeProp} from '../looped-frame';
import {MediaPlayer} from '../media-player';
import {type MediaOnError, callOnErrorAndResolve} from '../on-error';
import {ProResDecoderNotEnabledError} from '../prores-error';
import type {MediaRequestInit} from '../request-init';
import {useCommonEffects} from '../use-common-effects';
import {useMediaPlayerMuted} from '../use-media-player-muted';
import type {
FallbackOffthreadVideoProps,
MaxCanvasSinkFrameSize,
NativeVideoProps,
VideoObjectFit,
} from './props';
import {cacheVideoFrame, getCachedVideoFrame} from './video-frame-cache';
import {warnAboutObjectFitInStyleOrClassName} from './warn-object-fit-css';
const {
useUnsafeVideoConfig,
SharedAudioContext,
useMediaVolumeState,
useFrameForVolumeProp,
evaluateVolume,
warnAboutTooHighVolume,
usePreload,
SequenceContext,
useEffectChainState,
usePlaying,
useBuffering,
useMediaAudioState,
} = Internals;
type VideoForPreviewProps = NativeVideoProps & {
readonly src: string;
readonly style: React.CSSProperties | undefined;
readonly playbackRate: number;
readonly preservePitch: boolean | null;
readonly toneFrequency: number;
readonly logLevel: LogLevel;
readonly className: string | undefined;
readonly muted: boolean;
readonly volume: VolumeProp;
readonly loopVolumeCurveBehavior: LoopVolumeCurveBehavior;
readonly onVideoFrame: undefined | ((frame: CanvasImageSource) => void);
readonly showInTimeline: boolean;
readonly loop: boolean;
readonly trimAfter: number | undefined;
readonly trimBefore: number | undefined;
readonly _remotionInternalStack: string | null;
readonly disallowFallbackToOffthreadVideo: boolean;
readonly fallbackOffthreadVideoProps: FallbackOffthreadVideoProps;
readonly audioStreamIndex: number | null;
readonly debugOverlay: boolean;
readonly headless: boolean;
readonly onError: MediaOnError | undefined;
readonly credentials: RequestCredentials | undefined;
readonly requestInit: MediaRequestInit | undefined;
readonly objectFit: VideoObjectFit;
readonly maxCanvasSinkFrameSize: MaxCanvasSinkFrameSize | null;
readonly setMediaDurationInSeconds: (durationInSeconds: number) => void;
readonly _experimentalInitiallyDrawCachedFrame: boolean;
readonly effects: EffectDefinitionAndStack<unknown>[];
readonly effectsOutputSize: EffectsOutputSize | null;
};
type VideoForPreviewAssertedShowingProps = VideoForPreviewProps;
const VideoForPreviewAssertedShowing: React.FC<
VideoForPreviewAssertedShowingProps
> = ({
src: unpreloadedSrc,
style,
playbackRate,
toneFrequency,
preservePitch,
logLevel,
className,
muted,
volume,
loopVolumeCurveBehavior,
onVideoFrame,
showInTimeline,
loop,
trimAfter,
trimBefore,
_remotionInternalStack,
disallowFallbackToOffthreadVideo,
fallbackOffthreadVideoProps,
audioStreamIndex,
debugOverlay,
headless,
onError,
credentials,
requestInit,
objectFit: objectFitProp,
maxCanvasSinkFrameSize,
_experimentalInitiallyDrawCachedFrame,
effects,
effectsOutputSize,
setMediaDurationInSeconds,
...props
}) => {
const src = usePreload(unpreloadedSrc);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const videoConfig = useUnsafeVideoConfig();
const frame = useCurrentFrame();
const mediaPlayerRef = useRef<MediaPlayer | null>(null);
const initialTrimBeforeRef = useRef(trimBefore);
const initialTrimAfterRef = useRef(trimAfter);
const initialOnVideoFrameRef = useRef(onVideoFrame);
const [initialRequestInit] = useState(requestInit);
const [mediaPlayerReady, setMediaPlayerReady] = useState(false);
const [knownDuration, setKnownDuration] = useState<number | null>(null);
const [terminalError, setTerminalError] = useState<Error | null>(null);
const [shouldFallbackToNativeVideo, setShouldFallbackToNativeVideo] =
useState(false);
const playing = usePlaying();
const {playbackRate: globalPlaybackRate} = Internals.usePlaybackRate();
const preservePitchOnPlayback = useContext(Internals.PlaybackPitchContext);
const sharedAudioContext = useContext(SharedAudioContext);
const buffer = useBufferState();
const [mediaVolume] = useMediaVolumeState();
const unloopedVolumePropFrame = useFrameForVolumeProp(
loopVolumeCurveBehavior,
);
const volumePropFrame =
loop && videoConfig
? frameForVolumeProp({
behavior: loopVolumeCurveBehavior,
loop,
assetDurationInSeconds: knownDuration,
fps: videoConfig.fps,
frame,
startsAt: unloopedVolumePropFrame - frame,
playbackRate,
trimBefore,
trimAfter,
})
: unloopedVolumePropFrame;
const userPreferredVolume = evaluateVolume({
frame: volumePropFrame,
volume,
mediaVolume,
});
if (!videoConfig) {
throw new Error('No video config found');
}
warnAboutTooHighVolume(userPreferredVolume);
const effectChainState = useEffectChainState(effectsOutputSize);
const effectsRef = useRef(effects);
effectsRef.current = effects;
const onErrorRef = useRef(onError);
onErrorRef.current = onError;
const disallowFallbackRef = useRef(disallowFallbackToOffthreadVideo);
disallowFallbackRef.current = disallowFallbackToOffthreadVideo;
const effectChainStateRef = useRef(effectChainState);
effectChainStateRef.current = effectChainState;
const maxCanvasSinkFrameSizeRef = useRef(maxCanvasSinkFrameSize);
maxCanvasSinkFrameSizeRef.current = maxCanvasSinkFrameSize;
const parentSequence = useContext(SequenceContext);
const isPremounting = Boolean(parentSequence?.premounting);
const isPostmounting = Boolean(parentSequence?.postmounting);
const sequenceOffset = (parentSequence?.absoluteFrom ?? 0) / videoConfig.fps;
const sequencePlaybackRate = parentSequence?.playbackRate ?? 1;
const effectivePlaybackRate = playbackRate * sequencePlaybackRate;
const effectiveToneFrequency =
(toneFrequency ?? 1) /
(preservePitch ? effectivePlaybackRate : 1) /
(preservePitchOnPlayback && globalPlaybackRate > 0
? globalPlaybackRate
: 1);
const sequenceDurationInFrames =
videoConfig.durationInFrames / sequencePlaybackRate;
const currentTime = frame / sequencePlaybackRate / videoConfig.fps;
const currentTimeRef = useRef(currentTime);
currentTimeRef.current = currentTime;
const preloadedSrc = usePreload(src);
// TODO: Consider Sequence hidden
const {isMutedForPlayback: effectiveMuted} = useMediaAudioState({
muted,
volume: userPreferredVolume,
audioEnabled: true,
});
const mediaPlayerMuted = useMediaPlayerMuted({
muted,
volume: userPreferredVolume,
});
const isPlayerBuffering = useBuffering();
const initialPlaying = useRef(playing && !isPlayerBuffering);
const initialIsPremounting = useRef(isPremounting);
const initialIsPostmounting = useRef(isPostmounting);
const initialGlobalPlaybackRate = useRef(globalPlaybackRate);
const initialPlaybackRate = useRef(effectivePlaybackRate);
const initialToneFrequency = useRef(effectiveToneFrequency);
const initialMuted = useRef(mediaPlayerMuted);
const initialVolume = useRef(userPreferredVolume);
const initialSequenceDuration = useRef(sequenceDurationInFrames);
const initialSequenceOffset = useRef(sequenceOffset);
const hasDrawnRealFrameRef = useRef(false);
const isPremountingRef = useRef(isPremounting);
isPremountingRef.current = isPremounting;
useLayoutEffect(() => {
if (!_experimentalInitiallyDrawCachedFrame) {
return;
}
const canvas = canvasRef.current;
if (!canvas) {
return;
}
const cached = getCachedVideoFrame(src);
if (!cached) {
return;
}
canvas.width = cached.width;
canvas.height = cached.height;
const ctx = canvas.getContext('2d', {
alpha: true,
});
if (!ctx) {
return;
}
ctx.drawImage(cached, 0, 0);
}, [_experimentalInitiallyDrawCachedFrame, src]);
useLayoutEffect(() => {
if (!_experimentalInitiallyDrawCachedFrame) {
return;
}
const currentCanvasRef = canvasRef;
return () => {
const canvas = currentCanvasRef.current;
if (
!canvas ||
!hasDrawnRealFrameRef.current ||
isPremountingRef.current
) {
return;
}
cacheVideoFrame(src, canvas);
};
}, [_experimentalInitiallyDrawCachedFrame, src]);
useEffect(() => {
const sharedAudioContextForMediaPlayer =
sharedAudioContext?.audioContext && sharedAudioContext.gainNode
? {
audioContext: sharedAudioContext.audioContext,
gainNode: sharedAudioContext.gainNode,
audioSyncAnchor: sharedAudioContext.audioSyncAnchor,
scheduleAudioNode: sharedAudioContext.scheduleAudioNode,
unscheduleAudioNode: sharedAudioContext.unscheduleAudioNode,
}
: null;
try {
const player = new MediaPlayer({
canvas: canvasRef.current,
src: preloadedSrc,
logLevel,
sharedAudioContext: sharedAudioContextForMediaPlayer,
loop,
trimAfter: initialTrimAfterRef.current,
trimBefore: initialTrimBeforeRef.current,
fps: videoConfig.fps,
playbackRate: initialPlaybackRate.current,
toneFrequency: initialToneFrequency.current,
audioStreamIndex,
debugOverlay,
bufferState: buffer,
isPremounting: initialIsPremounting.current,
isPostmounting: initialIsPostmounting.current,
globalPlaybackRate: initialGlobalPlaybackRate.current,
durationInFrames: initialSequenceDuration.current,
onVideoFrameCallback: initialOnVideoFrameRef.current ?? null,
playing: initialPlaying.current,
sequenceOffset: initialSequenceOffset.current,
credentials,
requestInit: initialRequestInit,
tagType: 'video',
getEffects: () => effectsRef.current,
getEffectChainState: (width, height) =>
effectChainStateRef.current?.get(width, height)!,
maxCanvasSinkFrameSize: maxCanvasSinkFrameSizeRef.current,
onError: (error) => {
const [action, errorToUse] = callOnErrorAndResolve({
onError: onErrorRef.current,
error,
disallowFallback: disallowFallbackRef.current,
isClientSideRendering: false,
clientSideError: error,
});
if (action === 'fallback') {
setShouldFallbackToNativeVideo(true);
} else {
setTerminalError(errorToUse);
}
},
});
mediaPlayerRef.current = player;
player
.initialize(
currentTimeRef.current,
initialMuted.current,
initialVolume.current,
)
.then((result) => {
if (result.type === 'disposed') {
return;
}
const handleError = (error: Error, fallbackMessage: string) => {
const [action, errorToUse] = callOnErrorAndResolve({
onError: onErrorRef.current,
error,
disallowFallback: disallowFallbackToOffthreadVideo,
isClientSideRendering: false,
clientSideError: error,
});
if (action === 'fail') {
throw errorToUse;
}
// action === 'fallback'
Internals.Log.warn(
{logLevel, tag: '@remotion/media'},
fallbackMessage,
);
setShouldFallbackToNativeVideo(true);
};
if (
result.type === 'unknown-container-format' ||
result.type === 'network-error'
) {
// The catch below applies onError and the existing fallback policy.
throw result.error;
}
if (result.type === 'cannot-decode') {
handleError(
result.error,
`Cannot decode ${preloadedSrc}, falling back to <OffthreadVideo>`,
);
return;
}
if (result.type === 'cannot-decode-prores') {
// Unrecoverable: a native <video> can't decode ProRes either, so
// we must not fall back. The .catch below notifies onError and
// rethrows without falling back.
throw new ProResDecoderNotEnabledError(preloadedSrc);
}
if (result.type === 'no-tracks') {
handleError(
new Error(`No video or audio tracks found for ${preloadedSrc}.`),
`No video or audio tracks found for ${preloadedSrc}, falling back to <OffthreadVideo>`,
);
return;
}
if (result.type === 'success') {
setMediaPlayerReady(true);
setMediaDurationInSeconds(result.durationInSeconds);
setKnownDuration(result.durationInSeconds);
hasDrawnRealFrameRef.current = true;
}
})
.catch((error) => {
// ProRes without a registered decoder is unrecoverable and must not
// fall back to a native <video> (which cannot decode it either).
// Notify onError once for observability, then rethrow.
if (error instanceof ProResDecoderNotEnabledError) {
onErrorRef.current?.(error);
throw error;
}
const [action, errorToUse] = callOnErrorAndResolve({
onError: onErrorRef.current,
error,
disallowFallback: disallowFallbackToOffthreadVideo,
isClientSideRendering: false,
clientSideError: error,
});
if (action === 'fail') {
throw errorToUse;
}
Internals.Log.error(
{logLevel, tag: '@remotion/media'},
'[VideoForPreview] Failed to initialize MediaPlayer',
errorToUse,
);
setShouldFallbackToNativeVideo(true);
});
} catch (error) {
const [action, errorToUse] = callOnErrorAndResolve({
error: error as Error,
onError: onErrorRef.current,
disallowFallback: disallowFallbackToOffthreadVideo,
isClientSideRendering: false,
clientSideError: error as Error,
});
if (action === 'fail') {
throw errorToUse;
}
Internals.Log.error(
{logLevel, tag: '@remotion/media'},
'[VideoForPreview] MediaPlayer initialization failed',
errorToUse,
);
setShouldFallbackToNativeVideo(true);
}
return () => {
if (mediaPlayerRef.current) {
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
`[VideoForPreview] Disposing MediaPlayer`,
);
mediaPlayerRef.current.dispose();
mediaPlayerRef.current = null;
}
setMediaPlayerReady(false);
setShouldFallbackToNativeVideo(false);
hasDrawnRealFrameRef.current = false;
};
}, [
audioStreamIndex,
buffer,
debugOverlay,
disallowFallbackToOffthreadVideo,
logLevel,
loop,
preloadedSrc,
sharedAudioContext,
videoConfig.fps,
credentials,
initialRequestInit,
setMediaDurationInSeconds,
// Compare the numbers, so that a new object with the same size does not
// recreate the player.
maxCanvasSinkFrameSize?.width,
maxCanvasSinkFrameSize?.height,
]);
warnAboutObjectFitInStyleOrClassName({style, className, logLevel});
const classNameValue = useMemo(() => {
return [Internals.OBJECTFIT_CONTAIN_CLASS_NAME, className]
.filter(Internals.truthy)
.join(' ');
}, [className]);
useCommonEffects({
mediaPlayerRef,
mediaPlayerReady,
currentTimeRef,
playing,
isPlayerBuffering,
frame,
trimBefore,
trimAfter,
effectiveMuted: mediaPlayerMuted,
userPreferredVolume,
playbackRate: effectivePlaybackRate,
toneFrequency: effectiveToneFrequency,
globalPlaybackRate,
fps: videoConfig.fps,
sequenceOffset,
loop,
durationInFrames: sequenceDurationInFrames,
isPremounting,
isPostmounting,
currentTime,
logLevel,
label: 'VideoForPreview',
});
useLayoutEffect(() => {
const mediaPlayer = mediaPlayerRef.current;
if (!mediaPlayer || !mediaPlayerReady) {
return;
}
mediaPlayer.setDebugOverlay(debugOverlay);
}, [debugOverlay, mediaPlayerReady]);
useLayoutEffect(() => {
const mediaPlayer = mediaPlayerRef.current;
if (!mediaPlayer || !mediaPlayerReady) {
return;
}
mediaPlayer.setVideoFrameCallback(onVideoFrame ?? null);
}, [onVideoFrame, mediaPlayerReady]);
useLayoutEffect(() => {
const mediaPlayer = mediaPlayerRef.current;
if (!mediaPlayer || !mediaPlayerReady) {
return;
}
mediaPlayer.redrawVideoEffects().catch(() => {
// Player may have been disposed between layout and the async redraw.
});
}, [
effects,
effectsOutputSize?.width,
effectsOutputSize?.height,
mediaPlayerReady,
mediaPlayerRef,
]);
const actualStyle: React.CSSProperties = useMemo(() => {
return {
...style,
// TODO: Previousy we did hide on isSequenceHidden
objectFit: objectFitProp,
};
}, [objectFitProp, style]);
if (terminalError) {
throw terminalError;
}
if (shouldFallbackToNativeVideo && !disallowFallbackToOffthreadVideo) {
// <Video> will fallback to <VideoForPreview> anyway
// not using <OffthreadVideo> because it does not support looping
return (
<Html5Video
{...props}
src={src}
style={actualStyle}
className={className}
muted={effectiveMuted}
volume={volume}
trimAfter={trimAfter}
trimBefore={trimBefore}
playbackRate={playbackRate}
toneFrequency={toneFrequency}
loopVolumeCurveBehavior={loopVolumeCurveBehavior}
name={'<Html5Video> (fallback)'}
loop={loop}
showInTimeline={showInTimeline}
_remotionInternalStack={_remotionInternalStack ?? undefined}
{...fallbackOffthreadVideoProps}
preservePitch={
fallbackOffthreadVideoProps?.preservePitch ?? preservePitch ?? true
}
/>
);
}
if (headless) {
return null;
}
return (
<canvas
{...props}
ref={canvasRef}
// Don't set width and height here.
// Width is set in the video iterator manager, if props are being updated, they are being applied again by React.
// This will lead to inefficient resizes.
style={actualStyle}
className={classNameValue}
/>
);
};
export const VideoForPreview: React.FC<
VideoForPreviewProps & {
readonly controls: SequenceControls | undefined;
}
> = (props) => {
const frame = useCurrentFrame();
const videoConfig = useVideoConfig();
const currentTime = frame / videoConfig.fps;
const showShow = useMemo(() => {
return (
getTimeInSeconds({
unloopedTimeInSeconds: currentTime,
playbackRate: props.playbackRate,
loop: props.loop,
trimBefore: props.trimBefore,
trimAfter: props.trimAfter,
mediaDurationInSeconds: Infinity,
fps: videoConfig.fps,
ifNoMediaDuration: 'infinity',
src: props.src,
}) !== null
);
}, [
currentTime,
props.loop,
props.playbackRate,
props.src,
videoConfig.fps,
props.trimBefore,
props.trimAfter,
]);
if (!showShow) {
return null;
}
return <VideoForPreviewAssertedShowing {...props} />;
};