Skip to content

🎥 Make videos programmatically with React

fall back to offthreadvideo

JonnyBurgera951f33b98d3
diff --git a/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx b/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx
index a7c0e86cf1..a1bff8a4b9 100644
--- a/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx
+++ b/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx
@@ -1,7 +1,7 @@
import {experimental_Video as Video} from '@remotion/media';
import {parseMedia} from '@remotion/media-parser';
import {StudioInternals} from '@remotion/studio';
-import {CalculateMetadataFunction, staticFile} from 'remotion';
+import {CalculateMetadataFunction} from 'remotion';
const fps = 30;
const src = staticFile('bigbuckbunny.mp4') + '#t=lol';
@@ -33,7 +33,7 @@ export const calculateMetadataFn: CalculateMetadataFunction<
const Component = () => {
return (
<>
- <Video src={src} logLevel="verbose" />
+ <Video src={src} />
</>
);
};
diff --git a/packages/media/src/audio-extraction/extract-audio.ts b/packages/media/src/audio-extraction/extract-audio.ts
index c45f013b82..8c8c306cb5 100644
--- a/packages/media/src/audio-extraction/extract-audio.ts
+++ b/packages/media/src/audio-extraction/extract-audio.ts
@@ -23,10 +23,13 @@ export const extractAudio = async ({
logLevel: LogLevel;
loop: boolean;
playbackRate: number;
-}): Promise<{
- data: PcmS16AudioData | null;
- durationInSeconds: number | null;
-}> => {
+}): Promise<
+ | {
+ data: PcmS16AudioData | null;
+ durationInSeconds: number | null;
+ }
+ | 'cannot-decode'
+> => {
const {getAudio, actualMatroskaTimestamps, isMatroska, getDuration} =
await getSinkWeak(src, logLevel);
diff --git a/packages/media/src/audio/audio-for-rendering.tsx b/packages/media/src/audio/audio-for-rendering.tsx
index db18442cc6..3354c91826 100644
--- a/packages/media/src/audio/audio-for-rendering.tsx
+++ b/packages/media/src/audio/audio-for-rendering.tsx
@@ -1,6 +1,7 @@
import type React from 'react';
import {useContext, useLayoutEffect, useState} from 'react';
import {
+ Audio,
cancelRender,
Internals,
useCurrentFrame,
@@ -47,6 +48,8 @@ export const AudioForRendering: React.FC<AudioProps> = ({
const {fps} = videoConfig;
const {delayRender, continueRender} = useDelayRender();
+ const [replaceWithOffthreadVideo, setReplaceWithOffthreadVideo] =
+ useState(false);
useLayoutEffect(() => {
const actualFps = playbackRate ? fps / playbackRate : fps;
@@ -81,7 +84,18 @@ export const AudioForRendering: React.FC<AudioProps> = ({
isClientSideRendering: environment.isClientSideRendering,
loop: loop ?? false,
})
- .then(({audio, durationInSeconds: assetDurationInSeconds}) => {
+ .then((result) => {
+ if (result === 'cannot-decode') {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `Cannot decode ${src}, falling back to OffthreadVideo`,
+ );
+ setReplaceWithOffthreadVideo(true);
+ return;
+ }
+
+ const {audio, durationInSeconds: assetDurationInSeconds} = result;
+
const volumePropsFrame = frameForVolumeProp({
behavior: loopVolumeCurveBehavior ?? 'repeat',
loop: loop ?? false,
@@ -144,5 +158,12 @@ export const AudioForRendering: React.FC<AudioProps> = ({
volumeProp,
]);
+ if (replaceWithOffthreadVideo) {
+ // TODO: Loop and other props
+ return (
+ <Audio src={src} playbackRate={playbackRate} muted={muted} loop={loop} />
+ );
+ }
+
return null;
};
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
index e1daee0fb0..9e3d8a3827 100644
--- a/packages/media/src/extract-frame-and-audio.ts
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -21,11 +21,14 @@ export const extractFrameAndAudio = async ({
includeAudio: boolean;
includeVideo: boolean;
loop: boolean;
-}): Promise<{
- frame: VideoFrame | null;
- audio: PcmS16AudioData | null;
- durationInSeconds: number | null;
-}> => {
+}): Promise<
+ | {
+ frame: VideoFrame | null;
+ audio: PcmS16AudioData | null;
+ durationInSeconds: number | null;
+ }
+ | 'cannot-decode'
+> => {
const [frame, audio] = await Promise.all([
includeVideo
? extractFrame({
@@ -47,6 +50,18 @@ export const extractFrameAndAudio = async ({
: null,
]);
+ if (frame === 'cannot-decode') {
+ return 'cannot-decode';
+ }
+
+ if (audio === 'cannot-decode') {
+ if (frame !== null) {
+ frame?.close();
+ }
+
+ return 'cannot-decode';
+ }
+
return {
frame: frame?.toVideoFrame() ?? null,
audio: audio?.data ?? null,
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index 86c073e65a..9255b9c6c2 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -6,7 +6,7 @@ import {extractFrameAndAudio} from '../extract-frame-and-audio';
test('Should be able to extract a frame', async () => {
await keyframeManager.clearAll();
- const {audio, frame} = await extractFrameAndAudio({
+ const result = await extractFrameAndAudio({
src: '/bigbuckbunny.mp4',
timeInSeconds: 1,
durationInSeconds: 1 / 30,
@@ -17,6 +17,13 @@ test('Should be able to extract a frame', async () => {
loop: false,
});
+ if (result === 'cannot-decode') {
+ throw new Error('Cannot decode');
+ }
+
+ const {audio, frame} = result;
+ assert(audio);
+
assert(frame);
expect(frame.timestamp).toBe(1_000_000);
@@ -37,7 +44,7 @@ test('Should be able to extract a frame', async () => {
test('Should be able to extract the last frame', async () => {
await keyframeManager.clearAll();
- const {audio, frame} = await extractFrameAndAudio({
+ const result = await extractFrameAndAudio({
src: '/bigbuckbunny.mp4',
timeInSeconds: 1_000_000,
durationInSeconds: 1 / 30,
@@ -48,6 +55,12 @@ test('Should be able to extract the last frame', async () => {
loop: false,
});
+ if (result === 'cannot-decode') {
+ throw new Error('Cannot decode');
+ }
+
+ const {audio, frame} = result;
+
assert(frame);
expect(frame.timestamp).toBe(59_958_333);
@@ -80,7 +93,7 @@ test('Should manage the cache', async () => {
test('Should be apply volume correctly', async () => {
await keyframeManager.clearAll();
- const {audio: audioAtFullVolume, frame} = await extractFrameAndAudio({
+ const result = await extractFrameAndAudio({
src: '/bigbuckbunny.mp4',
timeInSeconds: 1,
durationInSeconds: 1 / 30,
@@ -91,6 +104,12 @@ test('Should be apply volume correctly', async () => {
loop: false,
});
+ if (result === 'cannot-decode') {
+ throw new Error('Cannot decode');
+ }
+
+ const {audio: audioAtFullVolume, frame} = result;
+
const totalAudioAtFullVolume = audioAtFullVolume?.data.reduce((acc, curr) => {
const unrounded = curr * 0.5;
const rounded = curr > 0 ? Math.floor(unrounded) : Math.ceil(unrounded);
@@ -110,7 +129,7 @@ test('Should be apply volume correctly', async () => {
test('Should be able to loop', async () => {
await keyframeManager.clearAll();
- const {frame} = await extractFrameAndAudio({
+ const result = await extractFrameAndAudio({
src: `/bigbuckbunny.mp4`,
timeInSeconds: 10000001,
durationInSeconds: 1 / 30,
@@ -121,5 +140,11 @@ test('Should be able to loop', async () => {
loop: true,
});
+ if (result === 'cannot-decode') {
+ throw new Error('Cannot decode');
+ }
+
+ const {frame} = result;
+
expect(frame?.timestamp).toBe(41_000_000);
});
diff --git a/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts b/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts
index fe4b9c7e41..1b6e073cc5 100644
--- a/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts
+++ b/packages/media/src/video-extraction/extract-frame-via-broadcast-channel.ts
@@ -27,6 +27,10 @@ type ExtractFrameResponse =
type: 'response-error';
id: string;
errorStack: string;
+ }
+ | {
+ type: 'response-cannot-decode';
+ id: string;
};
// Doesn't exist in studio
@@ -37,7 +41,7 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
const data = event.data as ExtractFrameRequest;
if (data.type === 'request') {
try {
- const {frame, audio, durationInSeconds} = await extractFrameAndAudio({
+ const result = await extractFrameAndAudio({
src: data.src,
timeInSeconds: data.timeInSeconds,
logLevel: data.logLevel,
@@ -48,6 +52,18 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
loop: data.loop,
});
+ if (result === 'cannot-decode') {
+ const cannotDecodeResponse: ExtractFrameResponse = {
+ type: 'response-cannot-decode',
+ id: data.id,
+ };
+
+ window.remotion_broadcastChannel!.postMessage(cannotDecodeResponse);
+ return;
+ }
+
+ const {frame, audio, durationInSeconds} = result;
+
const videoFrame = frame;
const imageBitmap = videoFrame
? await createImageBitmap(videoFrame)
@@ -102,11 +118,14 @@ export const extractFrameViaBroadcastChannel = ({
includeVideo: boolean;
isClientSideRendering: boolean;
loop: boolean;
-}): Promise<{
- frame: ImageBitmap | VideoFrame | null;
- audio: PcmS16AudioData | null;
- durationInSeconds: number | null;
-}> => {
+}): Promise<
+ | {
+ frame: ImageBitmap | VideoFrame | null;
+ audio: PcmS16AudioData | null;
+ durationInSeconds: number | null;
+ }
+ | 'cannot-decode'
+> => {
if (isClientSideRendering || window.remotion_isMainTab) {
return extractFrameAndAudio({
logLevel,
@@ -122,11 +141,14 @@ export const extractFrameViaBroadcastChannel = ({
const requestId = crypto.randomUUID();
- const resolvePromise = new Promise<{
- frame: ImageBitmap | null;
- audio: PcmS16AudioData | null;
- durationInSeconds: number | null;
- }>((resolve, reject) => {
+ const resolvePromise = new Promise<
+ | {
+ frame: ImageBitmap | null;
+ audio: PcmS16AudioData | null;
+ durationInSeconds: number | null;
+ }
+ | 'cannot-decode'
+ >((resolve, reject) => {
const onMessage = (event: MessageEvent) => {
const data = event.data as ExtractFrameResponse;
@@ -152,6 +174,15 @@ export const extractFrameViaBroadcastChannel = ({
'message',
onMessage,
);
+ } else if (
+ data.type === 'response-cannot-decode' &&
+ data.id === requestId
+ ) {
+ resolve('cannot-decode');
+ window.remotion_broadcastChannel!.removeEventListener(
+ 'message',
+ onMessage,
+ );
}
};
diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.ts
index 76c7e4ac6d..7a02802435 100644
--- a/packages/media/src/video-extraction/extract-frame.ts
+++ b/packages/media/src/video-extraction/extract-frame.ts
@@ -1,3 +1,4 @@
+import type {VideoSample} from 'mediabunny';
import {type LogLevel} from 'remotion';
import {keyframeManager} from '../caches';
import {getSinkWeak} from '../get-sink-weak';
@@ -12,7 +13,7 @@ export const extractFrame = async ({
timeInSeconds: number;
logLevel: LogLevel;
loop: boolean;
-}) => {
+}): Promise<VideoSample | 'cannot-decode' | null> => {
const sink = await getSinkWeak(src, logLevel);
const video = await sink.getVideo();
@@ -22,7 +23,7 @@ export const extractFrame = async ({
}
if (video === 'cannot-decode') {
- throw new Error(`Cannot decode video track for ${src}`);
+ return 'cannot-decode';
}
const timeInSeconds = loop
diff --git a/packages/media/src/video/video-for-rendering.tsx b/packages/media/src/video/video-for-rendering.tsx
index 078757b194..efb19ef3df 100644
--- a/packages/media/src/video/video-for-rendering.tsx
+++ b/packages/media/src/video/video-for-rendering.tsx
@@ -8,6 +8,7 @@ import React, {
import {
cancelRender,
Internals,
+ OffthreadVideo,
useCurrentFrame,
useDelayRender,
useRemotionEnvironment,
@@ -52,12 +53,18 @@ export const VideoForRendering: React.FC<VideoProps> = ({
const {delayRender, continueRender} = useDelayRender();
const canvasRef = useRef<HTMLCanvasElement>(null);
+ const [replaceWithOffthreadVideo, setReplaceWithOffthreadVideo] =
+ useState(false);
useLayoutEffect(() => {
if (!canvasRef.current) {
return;
}
+ if (replaceWithOffthreadVideo) {
+ return;
+ }
+
const actualFps = playbackRate ? fps / playbackRate : fps;
const timestamp = frame / actualFps;
const durationInSeconds = 1 / actualFps;
@@ -90,69 +97,77 @@ export const VideoForRendering: React.FC<VideoProps> = ({
isClientSideRendering: environment.isClientSideRendering,
loop: loop ?? false,
})
- .then(
- ({
+ .then((result) => {
+ if (result === 'cannot-decode') {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `Cannot decode ${src}, falling back to OffthreadVideo`,
+ );
+ setReplaceWithOffthreadVideo(true);
+ return;
+ }
+
+ const {
frame: imageBitmap,
audio,
durationInSeconds: assetDurationInSeconds,
- }) => {
- if (imageBitmap) {
- onVideoFrame?.(imageBitmap);
- const context = canvasRef.current?.getContext('2d');
- if (!context) {
- return;
- }
-
- context.canvas.width =
- imageBitmap instanceof ImageBitmap
- ? imageBitmap.width
- : imageBitmap.displayWidth;
- context.canvas.height =
- imageBitmap instanceof ImageBitmap
- ? imageBitmap.height
- : imageBitmap.displayHeight;
- context.canvas.style.aspectRatio = `${context.canvas.width} / ${context.canvas.height}`;
- context.drawImage(imageBitmap, 0, 0);
-
- imageBitmap.close();
- } else if (window.remotion_videoEnabled) {
- cancelRender(new Error('No video frame found'));
+ } = result;
+ if (imageBitmap) {
+ onVideoFrame?.(imageBitmap);
+ const context = canvasRef.current?.getContext('2d');
+ if (!context) {
+ return;
}
- const volumePropsFrame = frameForVolumeProp({
- behavior: loopVolumeCurveBehavior ?? 'repeat',
- loop: loop ?? false,
- assetDurationInSeconds: assetDurationInSeconds ?? 0,
- fps,
- frame,
- startsAt,
- });
-
- const volume = Internals.evaluateVolume({
- volume: volumeProp,
- frame: volumePropsFrame,
- mediaVolume: 1,
+ context.canvas.width =
+ imageBitmap instanceof ImageBitmap
+ ? imageBitmap.width
+ : imageBitmap.displayWidth;
+ context.canvas.height =
+ imageBitmap instanceof ImageBitmap
+ ? imageBitmap.height
+ : imageBitmap.displayHeight;
+ context.canvas.style.aspectRatio = `${context.canvas.width} / ${context.canvas.height}`;
+ context.drawImage(imageBitmap, 0, 0);
+
+ imageBitmap.close();
+ } else if (window.remotion_videoEnabled) {
+ cancelRender(new Error('No video frame found'));
+ }
+
+ const volumePropsFrame = frameForVolumeProp({
+ behavior: loopVolumeCurveBehavior ?? 'repeat',
+ loop: loop ?? false,
+ assetDurationInSeconds: assetDurationInSeconds ?? 0,
+ fps,
+ frame,
+ startsAt,
+ });
+
+ 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: Array.from(audio.data),
+ sampleRate: audio.sampleRate,
+ numberOfChannels: audio.numberOfChannels,
+ frame: absoluteFrame,
+ timestamp: audio.timestamp,
+ duration: (audio.numberOfFrames / audio.sampleRate) * 1_000_000,
});
+ }
- Internals.warnAboutTooHighVolume(volume);
-
- if (audio && volume > 0) {
- applyVolume(audio.data, volume);
- registerRenderAsset({
- type: 'inline-audio',
- id,
- audio: Array.from(audio.data),
- sampleRate: audio.sampleRate,
- numberOfChannels: audio.numberOfChannels,
- frame: absoluteFrame,
- timestamp: audio.timestamp,
- duration: (audio.numberOfFrames / audio.sampleRate) * 1_000_000,
- });
- }
-
- continueRender(newHandle);
- },
- )
+ continueRender(newHandle);
+ })
.catch((error) => {
cancelRender(error);
});
@@ -182,6 +197,7 @@ export const VideoForRendering: React.FC<VideoProps> = ({
startsAt,
unregisterRenderAsset,
volumeProp,
+ replaceWithOffthreadVideo,
]);
const classNameValue = useMemo(() => {
@@ -190,5 +206,12 @@ export const VideoForRendering: React.FC<VideoProps> = ({
.join(' ');
}, [className]);
+ if (replaceWithOffthreadVideo) {
+ // TODO: Loop and other props
+ return (
+ <OffthreadVideo src={src} playbackRate={playbackRate} muted={muted} />
+ );
+ }
+
return <canvas ref={canvasRef} style={style} className={classNameValue} />;
};