🎥 Make videos programmatically with React
import React, {
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import type {EffectsOutputSize} from 'remotion';
import type {
EffectDefinitionAndStack,
LogLevel,
LoopVolumeCurveBehavior,
OnVideoFrame,
VolumeProp,
} from 'remotion';
import {
Internals,
Loop,
random,
useCurrentFrame,
useDelayRender,
useRemotionEnvironment,
useVideoConfig,
} from 'remotion';
import {useMaxMediaCacheSize, useRenderMediaCache} from '../caches';
import {applyVolume} from '../convert-audiodata/apply-volume';
import {frameForVolumeProp} from '../looped-frame';
import {type MediaOnError, callOnErrorAndResolve} from '../on-error';
import {ProResDecoderNotEnabledError} from '../prores-error';
import type {MediaRequestInit} from '../request-init';
import {extractFrameViaBroadcastChannel} from '../video-extraction/extract-frame-via-broadcast-channel';
import type {
FallbackOffthreadVideoProps,
NativeVideoProps,
VideoObjectFit,
} from './props';
import {warnAboutObjectFitInStyleOrClassName} from './warn-object-fit-css';
type InnerVideoProps = NativeVideoProps & {
readonly className: string | undefined;
readonly loop: boolean;
readonly src: string;
readonly logLevel: LogLevel;
readonly muted: boolean;
readonly volume: VolumeProp;
readonly loopVolumeCurveBehavior: LoopVolumeCurveBehavior;
readonly onVideoFrame: OnVideoFrame | undefined;
readonly playbackRate: number;
readonly style: React.CSSProperties;
readonly delayRenderRetries: number | null;
readonly delayRenderTimeoutInMilliseconds: number | null;
readonly fallbackOffthreadVideoProps: FallbackOffthreadVideoProps;
readonly audioStreamIndex: number | null;
readonly disallowFallbackToOffthreadVideo: boolean;
readonly _remotionInternalStack: string | undefined;
readonly toneFrequency: number;
readonly preservePitch: boolean | null;
readonly trimBeforeValue: number | undefined;
readonly trimAfterValue: number | undefined;
readonly headless: boolean;
readonly onError: MediaOnError | undefined;
readonly credentials: RequestCredentials | undefined;
readonly requestInit: MediaRequestInit | undefined;
readonly objectFit: VideoObjectFit;
readonly effects: EffectDefinitionAndStack<unknown>[];
readonly effectsOutputSize: EffectsOutputSize | null;
};
type FallbackToOffthreadVideo = {
durationInSeconds: number | null;
};
export const VideoForRendering: React.FC<InnerVideoProps> = ({
volume: volumeProp,
playbackRate,
src,
muted,
loopVolumeCurveBehavior,
delayRenderRetries,
delayRenderTimeoutInMilliseconds,
onVideoFrame,
logLevel,
loop,
style,
className,
fallbackOffthreadVideoProps,
audioStreamIndex,
disallowFallbackToOffthreadVideo,
_remotionInternalStack,
toneFrequency,
preservePitch,
trimAfterValue,
trimBeforeValue,
headless,
onError,
credentials,
requestInit,
objectFit: objectFitProp,
effects,
effectsOutputSize,
...props
}) => {
if (!src) {
throw new TypeError('No `src` was passed to <Video>.');
}
const audioContext = useContext(Internals.SharedAudioContext);
const sampleRate = audioContext?.sampleRate ?? 48000;
const frame = useCurrentFrame();
const absoluteFrame = Internals.useTimelinePosition();
const {fps} = useVideoConfig();
const {registerRenderAsset, unregisterRenderAsset} = useContext(
Internals.RenderAssetManager,
);
const startsAt = Internals.useMediaStartsAt();
const sequenceContext = useContext(Internals.SequenceContext);
const sequencePlaybackRate = sequenceContext?.playbackRate ?? 1;
const startInVideo = sequenceContext
? sequenceContext.cumulatedFrom + sequenceContext.relativeFrom
: 0;
// Generate a string that's as unique as possible for this asset
// but at the same time the same on all threads
const id = useMemo(
() =>
`media-video-${random(
src,
)}-${sequenceContext?.cumulatedFrom}-${sequenceContext?.relativeFrom}-${sequenceContext?.durationInFrames}`,
[
src,
sequenceContext?.cumulatedFrom,
sequenceContext?.relativeFrom,
sequenceContext?.durationInFrames,
],
);
const environment = useRemotionEnvironment();
const {delayRender, continueRender, cancelRender} = useDelayRender();
const canvasRef = useRef<HTMLCanvasElement>(null);
const [replaceWithOffthreadVideo, setReplaceWithOffthreadVideo] = useState<
FallbackToOffthreadVideo | false
>(false);
const [initialRequestInit] = useState(requestInit);
const audioEnabled = Internals.useAudioEnabled();
const videoEnabled = Internals.useVideoEnabled();
const {isMutedForPlayback, shouldUseAudio} = Internals.useMediaAudioState({
muted,
volume: null,
audioEnabled,
});
const maxCacheSize = useMaxMediaCacheSize(logLevel);
const mediaCache = useRenderMediaCache(logLevel);
const effectChainState = Internals.useEffectChainState(effectsOutputSize);
const [error, setError] = useState<Error | null>(null);
if (error) {
throw error;
}
useLayoutEffect(() => {
if (!canvasRef.current && !headless) {
return;
}
if (replaceWithOffthreadVideo) {
return;
}
if (!canvasRef.current?.getContext && !headless) {
return setError(
new Error(
'Canvas does not have .getContext() method available. This could be because <Video> was mounted inside an <svg> tag.',
),
);
}
const timestamp = frame / sequencePlaybackRate / fps;
const durationInSeconds = 1 / fps;
let cancelled = false;
const newHandle = delayRender(
`Extracting frame at time ${timestamp} from ${src}`,
{
retries: delayRenderRetries ?? undefined,
timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
},
);
extractFrameViaBroadcastChannel({
sampleRate,
src,
timeInSeconds: timestamp,
durationInSeconds,
playbackRate: playbackRate * sequencePlaybackRate,
logLevel,
includeAudio: shouldUseAudio,
includeVideo: videoEnabled,
isClientSideRendering: environment.isClientSideRendering,
loop,
audioStreamIndex,
trimAfter: trimAfterValue,
trimBefore: trimBeforeValue,
fps,
maxCacheSize,
credentials,
requestInit: initialRequestInit,
mediaCache,
})
.then(async (result) => {
if (cancelled || mediaCache.isDisposed()) {
if (result.type === 'success') {
result.frame?.close();
}
return;
}
const handleError = (
err: Error,
clientSideError: Error,
fallbackMessage: string,
mediaDurationInSeconds: number | null,
) => {
if (environment.isClientSideRendering) {
cancelRender(clientSideError);
return;
}
const [action, errorToUse] = callOnErrorAndResolve({
onError,
error: err,
disallowFallback: disallowFallbackToOffthreadVideo,
isClientSideRendering: environment.isClientSideRendering,
clientSideError: err,
});
if (action === 'fail') {
cancelRender(errorToUse);
return;
}
// action === 'fallback'
if (window.remotion_isMainTab) {
Internals.Log.warn(
{logLevel, tag: '@remotion/media'},
fallbackMessage,
);
}
setReplaceWithOffthreadVideo({
durationInSeconds: mediaDurationInSeconds,
});
};
if (
(result.type === 'unknown-container-format' ||
result.type === 'network-error') &&
result.error
) {
handleError(
result.error,
result.error,
`Failed to read ${src}: ${result.error.message}, falling back to <OffthreadVideo>`,
null,
);
return;
}
if (result.type === 'unknown-container-format') {
handleError(
new Error(`Unknown container format ${src}.`),
new Error(
`Cannot render video "${src}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`,
),
`Unknown container format for ${src} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`,
null,
);
return;
}
if (result.type === 'cannot-decode') {
handleError(
result.error,
new Error(`Cannot render video "${src}": ${result.error.message}`, {
cause: result.error,
}),
`Cannot decode ${src}, falling back to <OffthreadVideo>`,
result.durationInSeconds,
);
return;
}
if (result.type === 'cannot-decode-prores') {
// Unrecoverable: ProRes must not silently fall back to
// <OffthreadVideo>. Registering the decoder is the only fix.
// Notify onError once for observability, then hard-fail.
const proresError = new ProResDecoderNotEnabledError(src);
onError?.(proresError);
cancelRender(proresError);
return;
}
if (result.type === 'cannot-decode-alpha') {
handleError(
new Error(`Cannot decode alpha component for ${src}.`),
new Error(
`Cannot render video "${src}": The alpha channel could not be decoded by the browser.`,
),
`Cannot decode alpha component for ${src}, falling back to <OffthreadVideo>`,
result.durationInSeconds,
);
return;
}
if (result.type === 'network-error') {
handleError(
new Error(`Network error fetching ${src}.`),
new Error(
`Cannot render video "${src}": Network error while fetching the video (possibly CORS).`,
),
`Network error fetching ${src} (no CORS?), falling back to <OffthreadVideo>`,
null,
);
return;
}
const {
frame: imageBitmap,
audio,
durationInSeconds: assetDurationInSeconds,
} = result;
if (imageBitmap) {
onVideoFrame?.(imageBitmap);
const context = canvasRef.current?.getContext('2d', {
alpha: true,
});
// Could be in headless mode
if (context) {
context.canvas.width = imageBitmap.width;
context.canvas.height = imageBitmap.height;
context.canvas.style.aspectRatio = `${context.canvas.width} / ${context.canvas.height}`;
context.drawImage(imageBitmap, 0, 0);
if (effects.length > 0) {
const completed = await Internals.runEffectChain({
state: effectChainState.get(
imageBitmap.width,
imageBitmap.height,
)!,
source: context.canvas,
effects,
output: context.canvas,
width: imageBitmap.width,
height: imageBitmap.height,
});
if (!completed || cancelled || mediaCache.isDisposed()) {
imageBitmap.close();
return;
}
}
}
imageBitmap.close();
} else if (videoEnabled) {
// A video that only starts at time 0.033sec
// we shall not crash here but clear the canvas
const context = canvasRef.current?.getContext('2d', {
alpha: true,
});
if (context) {
context.clearRect(
0,
0,
context.canvas.width,
context.canvas.height,
);
}
}
const volumePropsFrame = frameForVolumeProp({
behavior: loopVolumeCurveBehavior,
loop,
assetDurationInSeconds: assetDurationInSeconds ?? 0,
fps,
frame,
startsAt,
playbackRate,
trimBefore: trimBeforeValue,
trimAfter: trimAfterValue,
});
const volume = Internals.evaluateVolume({
volume: volumeProp,
frame: volumePropsFrame,
mediaVolume: 1,
});
Internals.warnAboutTooHighVolume(volume);
if (audio && volume > 0) {
applyVolume(audio.data, volume);
registerRenderAsset({
type: 'inline-audio',
id,
audio: environment.isClientSideRendering
? audio.data
: Array.from(audio.data),
frame: absoluteFrame,
startInVideo,
timestamp: audio.timestamp,
duration: audio.durationInMicroSeconds,
toneFrequency:
toneFrequency /
(preservePitch ? playbackRate * sequencePlaybackRate : 1),
});
}
continueRender(newHandle);
})
.catch((err) => {
if (cancelled || mediaCache.isDisposed()) {
return;
}
cancelRender(err);
});
return () => {
cancelled = true;
continueRender(newHandle);
unregisterRenderAsset(id);
};
}, [
sampleRate,
absoluteFrame,
continueRender,
delayRender,
delayRenderRetries,
delayRenderTimeoutInMilliseconds,
environment.isClientSideRendering,
fps,
frame,
id,
logLevel,
loop,
loopVolumeCurveBehavior,
shouldUseAudio,
onVideoFrame,
playbackRate,
sequencePlaybackRate,
registerRenderAsset,
src,
startInVideo,
startsAt,
unregisterRenderAsset,
volumeProp,
replaceWithOffthreadVideo,
audioStreamIndex,
disallowFallbackToOffthreadVideo,
toneFrequency,
preservePitch,
trimAfterValue,
trimBeforeValue,
videoEnabled,
maxCacheSize,
cancelRender,
headless,
onError,
credentials,
effectChainState,
effects,
initialRequestInit,
mediaCache,
]);
warnAboutObjectFitInStyleOrClassName({style, className, logLevel});
const classNameValue = useMemo(() => {
return [Internals.OBJECTFIT_CONTAIN_CLASS_NAME, className]
.filter(Internals.truthy)
.join(' ');
}, [className]);
const styleWithObjectFit: React.CSSProperties = useMemo(() => {
return {
...style,
objectFit: objectFitProp,
};
}, [objectFitProp, style]);
if (replaceWithOffthreadVideo) {
const fallback = (
<Internals.InnerOffthreadVideo
{...props}
src={src}
playbackRate={playbackRate ?? 1}
muted={isMutedForPlayback}
acceptableTimeShiftInSeconds={
fallbackOffthreadVideoProps?.acceptableTimeShiftInSeconds
}
loopVolumeCurveBehavior={loopVolumeCurveBehavior ?? 'repeat'}
delayRenderRetries={delayRenderRetries ?? undefined}
delayRenderTimeoutInMilliseconds={
delayRenderTimeoutInMilliseconds ?? undefined
}
name={'Fallback to <OffthreadVideo>'}
style={styleWithObjectFit}
allowAmplificationDuringRender
transparent={fallbackOffthreadVideoProps?.transparent ?? true}
toneMapped={fallbackOffthreadVideoProps?.toneMapped ?? true}
audioStreamIndex={audioStreamIndex ?? 0}
className={className}
onVideoFrame={onVideoFrame}
volume={volumeProp}
id={id}
onError={fallbackOffthreadVideoProps?.onError}
toneFrequency={toneFrequency}
// these shouldn't matter during rendering / should not appear at all
showInTimeline={false}
crossOrigin={fallbackOffthreadVideoProps?.crossOrigin}
onAutoPlayError={fallbackOffthreadVideoProps?.onAutoPlayError ?? null}
pauseWhenBuffering={
fallbackOffthreadVideoProps?.pauseWhenBuffering ?? false
}
trimAfter={trimAfterValue}
durationInFrames={undefined}
trimBefore={trimBeforeValue}
useWebAudioApi={fallbackOffthreadVideoProps?.useWebAudioApi ?? false}
preservePitch={
fallbackOffthreadVideoProps?.preservePitch ?? preservePitch ?? true
}
startFrom={undefined}
endAt={undefined}
_remotionInternalStack={_remotionInternalStack}
_remotionInternalNativeLoopPassed={false}
/>
);
if (loop) {
if (!replaceWithOffthreadVideo.durationInSeconds) {
const err = new Error(
`Cannot render video ${src}: @remotion/media was unable to render, and fell back to <OffthreadVideo>. Also, "loop" was set, but <OffthreadVideo> does not support looping and @remotion/media could also not determine the duration of the video.`,
);
cancelRender(err);
throw err;
}
return (
<Loop
layout="none"
durationInFrames={Internals.calculateMediaDuration({
trimAfter: trimAfterValue,
mediaDurationInFrames:
replaceWithOffthreadVideo.durationInSeconds * fps,
playbackRate,
trimBefore: trimBeforeValue,
})}
>
{fallback}
</Loop>
);
}
return fallback;
}
if (headless) {
return null;
}
return (
<canvas
{...props}
ref={canvasRef}
style={styleWithObjectFit}
className={classNameValue}
/>
);
};