Skip to content

🎥 Make videos programmatically with React

fallback logic v1

Igor Samokhovetsf49a2aed997e
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
index e3fc9cd520..bcafbdce13 100644
--- a/packages/media/src/extract-frame-and-audio.ts
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -1,5 +1,6 @@
import type {LogLevel} from 'remotion';
import {extractAudio} from './audio-extraction/extract-audio';
+import {isNetworkError} from './is-network-error';
import {extractFrame} from './video-extraction/extract-frame';
import type {ExtractFrameViaBroadcastChannelResult} from './video-extraction/extract-frame-via-broadcast-channel';
@@ -96,14 +97,7 @@ export const extractFrameAndAudio = async ({
};
} catch (err) {
const error = err as Error;
- if (
- // Chrome
- error.message.includes('Failed to fetch') ||
- // Safari
- error.message.includes('Load failed') ||
- // Firefox
- error.message.includes('NetworkError when attempting to fetch resource')
- ) {
+ if (isNetworkError(error)) {
return {type: 'network-error'};
}
diff --git a/packages/media/src/is-network-error.ts b/packages/media/src/is-network-error.ts
new file mode 100644
index 0000000000..ef093cfcc6
--- /dev/null
+++ b/packages/media/src/is-network-error.ts
@@ -0,0 +1,19 @@
+/**
+ * Utility to check if error is network error
+ * @param error
+ * @returns
+ */
+export function isNetworkError(error: Error) {
+ if (
+ // Chrome
+ error.message.includes('Failed to fetch') ||
+ // Safari
+ error.message.includes('Load failed') ||
+ // Firefox
+ error.message.includes('NetworkError when attempting to fetch resource')
+ ) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/packages/media/src/video/media-player.ts b/packages/media/src/video/media-player.ts
index eb6e57df74..23417b32b3 100644
--- a/packages/media/src/video/media-player.ts
+++ b/packages/media/src/video/media-player.ts
@@ -8,12 +8,20 @@ import {
} from 'mediabunny';
import type {LogLevel} from 'remotion';
import {Internals} from 'remotion';
+import {isNetworkError} from '../is-network-error';
import {resolvePlaybackTime} from './resolve-playback-time';
import {sleep, withTimeout} from './timeout-utils';
export const SEEK_THRESHOLD = 0.05;
const AUDIO_BUFFER_TOLERANCE_THRESHOLD = 0.1;
+export type MediaPlayerInitResult =
+ | {type: 'success'}
+ | {type: 'unknown-container-format'}
+ | {type: 'cannot-decode'}
+ | {type: 'network-error'}
+ | {type: 'no-tracks'};
+
export class MediaPlayer {
private canvas: HTMLCanvasElement | null;
private context: CanvasRenderingContext2D | null;
@@ -129,7 +137,9 @@ export class MediaPlayer {
return this.isBuffering && Boolean(this.bufferingStartedAtMs);
}
- public async initialize(startTimeUnresolved: number): Promise<void> {
+ public async initialize(
+ startTimeUnresolved: number,
+ ): Promise<MediaPlayerInitResult> {
try {
const urlSource = new UrlSource(this.src);
@@ -140,6 +150,24 @@ export class MediaPlayer {
this.input = input;
+ try {
+ await this.input.getFormat();
+ } catch (error) {
+ const err = error as Error;
+
+ if (isNetworkError(err)) {
+ throw error;
+ }
+
+ Internals.Log.error(
+ {logLevel: this.logLevel, tag: '@remotion/media'},
+ `[MediaPlayer] Failed to recognize format for ${this.src}`,
+ error,
+ );
+
+ return {type: 'unknown-container-format'};
+ }
+
const [duration, videoTrack, audioTrack] = await Promise.all([
input.computeDuration(),
input.getPrimaryVideoTrack(),
@@ -148,10 +176,16 @@ export class MediaPlayer {
this.totalDuration = duration;
if (!videoTrack && !audioTrack) {
- throw new Error(`No video or audio track found for ${this.src}`);
+ return {type: 'no-tracks'};
}
if (videoTrack && this.canvas && this.context) {
+ const canDecode = await videoTrack.canDecode();
+
+ if (!canDecode) {
+ return {type: 'cannot-decode'};
+ }
+
this.canvasSink = new CanvasSink(videoTrack, {
poolSize: 2,
fit: 'contain',
@@ -188,7 +222,20 @@ export class MediaPlayer {
]);
this.startRenderLoop();
+
+ return {type: 'success'};
} catch (error) {
+ const err = error as Error;
+
+ if (isNetworkError(err)) {
+ Internals.Log.error(
+ {logLevel: this.logLevel, tag: '@remotion/media'},
+ `[MediaPlayer] Network/CORS error for ${this.src}`,
+ err,
+ );
+ return {type: 'network-error'};
+ }
+
Internals.Log.error(
{logLevel: this.logLevel, tag: '@remotion/media'},
'[MediaPlayer] Failed to initialize',
diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsx
index 47c64df91c..b2f774d7ba 100644
--- a/packages/media/src/video/video-for-preview.tsx
+++ b/packages/media/src/video/video-for-preview.tsx
@@ -5,7 +5,12 @@ import type {
OnVideoFrame,
VolumeProp,
} from 'remotion';
-import {Internals, useBufferState, useCurrentFrame} from 'remotion';
+import {
+ Internals,
+ Video as RemotionVideo,
+ useBufferState,
+ useCurrentFrame,
+} from 'remotion';
import {MediaPlayer} from './media-player';
const {
@@ -63,6 +68,8 @@ const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
const mediaPlayerRef = useRef<MediaPlayer | null>(null);
const [mediaPlayerReady, setMediaPlayerReady] = useState(false);
+ const [shouldFallbackToNativeVideo, setShouldFallbackToNativeVideo] =
+ useState(false);
const [playing] = Timeline.usePlayingState();
const timelineContext = useContext(Timeline.TimelineContext);
@@ -139,8 +146,46 @@ const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
player
.initialize(currentTimeRef.current)
- .then(() => {
- setMediaPlayerReady(true);
+ .then((result) => {
+ if (result.type === 'unknown-container-format') {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `Unknown container format for ${preloadedSrc}, falling back to native <Video>`,
+ );
+ setShouldFallbackToNativeVideo(true);
+ return;
+ }
+
+ if (result.type === 'network-error') {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `Network/CORS error for ${preloadedSrc}, falling back to native <Video>`,
+ );
+ setShouldFallbackToNativeVideo(true);
+ return;
+ }
+
+ if (result.type === 'cannot-decode') {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `Cannot decode video for ${preloadedSrc}, falling back to native <Video>`,
+ );
+ setShouldFallbackToNativeVideo(true);
+ return;
+ }
+
+ if (result.type === 'no-tracks') {
+ Internals.Log.info(
+ {logLevel, tag: '@remotion/media'},
+ `No video or audio tracks found for ${preloadedSrc}, falling back to native <Video>`,
+ );
+ setShouldFallbackToNativeVideo(true);
+ return;
+ }
+
+ if (result.type === 'success') {
+ setMediaPlayerReady(true);
+ }
})
.catch((error) => {
Internals.Log.error(
@@ -148,6 +193,7 @@ const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
'[NewVideoForPreview] Failed to initialize MediaPlayer',
error,
);
+ setShouldFallbackToNativeVideo(true);
});
} catch (error) {
Internals.Log.error(
@@ -155,6 +201,7 @@ const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
'[NewVideoForPreview] MediaPlayer initialization failed',
error,
);
+ setShouldFallbackToNativeVideo(true);
}
return () => {
@@ -168,6 +215,7 @@ const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
}
setMediaPlayerReady(false);
+ setShouldFallbackToNativeVideo(false);
};
}, [
preloadedSrc,
@@ -302,6 +350,26 @@ const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
};
}, [onVideoFrame, mediaPlayerReady]);
+ if (shouldFallbackToNativeVideo) {
+ return (
+ <RemotionVideo
+ src={src}
+ style={style}
+ className={className}
+ muted={muted}
+ volume={volume}
+ playbackRate={playbackRate}
+ loop={loop}
+ loopVolumeCurveBehavior={loopVolumeCurveBehavior}
+ name={name}
+ showInTimeline={showInTimeline}
+ stack={stack ?? undefined}
+ trimBefore={trimBefore}
+ trimAfter={trimAfter}
+ />
+ );
+ }
+
return (
<canvas
ref={canvasRef}