Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Support looping OffthreadVideo fallback

JonnyBurgerb4a706f4c89e
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 6a6f836b14..2b97a4493d 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -10,6 +10,7 @@ import {
useMediaStartsAt,
} from './audio/use-audio-frame.js';
import {BufferingContextReact, BufferingProvider} from './buffering.js';
+import {calculateLoopDuration} from './calculate-loop.js';
import {
CanUseRemotionHooks,
CanUseRemotionHooksProvider,
@@ -215,6 +216,7 @@ export const Internals = {
AudioForPreview,
OBJECTFIT_CONTAIN_CLASS_NAME,
InnerOffthreadVideo,
+ calculateLoopDuration,
} as const;
export type {
diff --git a/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx b/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx
index 154e0119da..753716e449 100644
--- a/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx
+++ b/packages/example/src/OffthreadRemoteVideo/NewRemoteVideo.tsx
@@ -1,34 +1,35 @@
-import {Audio} from '@remotion/media';
+import {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('audio-48000hz.wav') + '#t=lol';
+const src = 'https://remotion.media/video.mp4' + '#t=lol';
export const calculateMetadataFn: CalculateMetadataFunction<
Record<string, unknown>
> = async () => {
- const {slowDurationInSeconds} = await parseMedia({
+ const {slowDurationInSeconds, dimensions} = await parseMedia({
src,
acknowledgeRemotionLicense: true,
fields: {
slowDurationInSeconds: true,
+ dimensions: true,
},
});
return {
durationInFrames: Math.round(slowDurationInSeconds * fps),
fps,
- width: 100,
- height: 100,
+ width: dimensions?.width ?? 100,
+ height: dimensions?.height ?? 100,
};
};
const Component = () => {
return (
<>
- <Audio src={src} toneFrequency={0.9} />
+ <Video src={src} />
</>
);
};
diff --git a/packages/media/src/audio/audio-for-rendering.tsx b/packages/media/src/audio/audio-for-rendering.tsx
index 7522d19cce..2ae6f645e5 100644
--- a/packages/media/src/audio/audio-for-rendering.tsx
+++ b/packages/media/src/audio/audio-for-rendering.tsx
@@ -108,7 +108,7 @@ export const AudioForRendering: React.FC<AudioProps> = ({
audioStreamIndex: audioStreamIndex ?? 0,
})
.then((result) => {
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
if (disallowFallbackToHtml5Audio) {
cancelRender(
new Error(
@@ -125,7 +125,7 @@ export const AudioForRendering: React.FC<AudioProps> = ({
return;
}
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
if (disallowFallbackToHtml5Audio) {
cancelRender(
new Error(
@@ -142,7 +142,7 @@ export const AudioForRendering: React.FC<AudioProps> = ({
return;
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
if (disallowFallbackToHtml5Audio) {
cancelRender(
new Error(
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
index c2726e6dd8..aa23828624 100644
--- a/packages/media/src/extract-frame-and-audio.ts
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -1,7 +1,7 @@
import type {LogLevel} from 'remotion';
import {extractAudio} from './audio-extraction/extract-audio';
-import type {PcmS16AudioData} from './convert-audiodata/convert-audiodata';
import {extractFrame} from './video-extraction/extract-frame';
+import type {ExtractFrameViaBroadcastChannelResult} from './video-extraction/extract-frame-via-broadcast-channel';
export const extractFrameAndAudio = async ({
src,
@@ -23,16 +23,7 @@ export const extractFrameAndAudio = async ({
includeVideo: boolean;
loop: boolean;
audioStreamIndex: number;
-}): Promise<
- | {
- frame: VideoFrame | null;
- audio: PcmS16AudioData | null;
- durationInSeconds: number | null;
- }
- | 'cannot-decode'
- | 'unknown-container-format'
- | 'network-error'
-> => {
+}): Promise<ExtractFrameViaBroadcastChannelResult> => {
try {
const [frame, audio] = await Promise.all([
includeVideo
@@ -57,11 +48,11 @@ export const extractFrameAndAudio = async ({
]);
if (frame === 'cannot-decode') {
- return 'cannot-decode';
+ return {type: 'cannot-decode', durationInSeconds};
}
if (frame === 'unknown-container-format') {
- return 'unknown-container-format';
+ return {type: 'unknown-container-format'};
}
if (audio === 'unknown-container-format') {
@@ -69,7 +60,7 @@ export const extractFrameAndAudio = async ({
frame?.close();
}
- return 'unknown-container-format';
+ return {type: 'unknown-container-format'};
}
if (audio === 'cannot-decode') {
@@ -77,10 +68,11 @@ export const extractFrameAndAudio = async ({
frame?.close();
}
- return 'cannot-decode';
+ return {type: 'cannot-decode', durationInSeconds};
}
return {
+ type: 'success',
frame: frame?.toVideoFrame() ?? null,
audio: audio?.data ?? null,
durationInSeconds: audio?.durationInSeconds ?? null,
@@ -95,7 +87,7 @@ export const extractFrameAndAudio = async ({
// Firefox
error.message.includes('NetworkError when attempting to fetch resource')
) {
- return 'network-error';
+ return {type: 'network-error'};
}
throw err;
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index 8d7b412f2a..1d0e1c7f7a 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -18,15 +18,15 @@ test('Should be able to extract a frame', async () => {
audioStreamIndex: 0,
});
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
throw new Error('Cannot decode');
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
throw new Error('Network error');
}
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
throw new Error('Unknown container format');
}
@@ -34,7 +34,7 @@ test('Should be able to extract a frame', async () => {
assert(audio);
assert(frame);
- expect(frame.timestamp).toBe(1_000_000);
+ expect((frame as VideoFrame).timestamp).toBe(1_000_000);
assert(audio);
expect(audio.sampleRate).toBe(48000);
@@ -65,22 +65,22 @@ test('Should be able to extract the last frame', async () => {
audioStreamIndex: 0,
});
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
throw new Error('Cannot decode');
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
throw new Error('Network error');
}
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
throw new Error('Unknown container format');
}
const {audio, frame} = result;
assert(frame);
- expect(frame.timestamp).toBe(59_958_333);
+ expect((frame as VideoFrame).timestamp).toBe(59_958_333);
assert(!audio);
@@ -124,15 +124,15 @@ test('Should be apply volume correctly', async () => {
audioStreamIndex: 0,
});
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
throw new Error('Cannot decode');
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
throw new Error('Network error');
}
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
throw new Error('Unknown container format');
}
@@ -169,19 +169,19 @@ test('Should be able to loop', async () => {
audioStreamIndex: 0,
});
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
throw new Error('Cannot decode');
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
throw new Error('Network error');
}
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
throw new Error('Unknown container format');
}
const {frame} = result;
- expect(frame?.timestamp).toBe(41_000_000);
+ expect((frame as VideoFrame)?.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 4045e2e876..56d00a2519 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
@@ -32,6 +32,7 @@ type ExtractFrameResponse =
| {
type: 'response-cannot-decode';
id: string;
+ durationInSeconds: number | null;
}
| {
type: 'response-network-error';
@@ -62,17 +63,18 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
audioStreamIndex: data.audioStreamIndex,
});
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
const cannotDecodeResponse: ExtractFrameResponse = {
type: 'response-cannot-decode',
id: data.id,
+ durationInSeconds: result.durationInSeconds,
};
window.remotion_broadcastChannel!.postMessage(cannotDecodeResponse);
return;
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
const networkErrorResponse: ExtractFrameResponse = {
type: 'response-network-error',
id: data.id,
@@ -82,7 +84,7 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
return;
}
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
const unknownContainerFormatResponse: ExtractFrameResponse = {
type: 'response-unknown-container-format',
id: data.id,
@@ -130,6 +132,17 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
);
}
+export type ExtractFrameViaBroadcastChannelResult =
+ | {
+ type: 'success';
+ frame: ImageBitmap | VideoFrame | null;
+ audio: PcmS16AudioData | null;
+ durationInSeconds: number | null;
+ }
+ | {type: 'cannot-decode'; durationInSeconds: number | null}
+ | {type: 'network-error'}
+ | {type: 'unknown-container-format'};
+
export const extractFrameViaBroadcastChannel = ({
src,
timeInSeconds,
@@ -152,16 +165,7 @@ export const extractFrameViaBroadcastChannel = ({
isClientSideRendering: boolean;
loop: boolean;
audioStreamIndex: number;
-}): Promise<
- | {
- frame: ImageBitmap | VideoFrame | null;
- audio: PcmS16AudioData | null;
- durationInSeconds: number | null;
- }
- | 'cannot-decode'
- | 'network-error'
- | 'unknown-container-format'
-> => {
+}): Promise<ExtractFrameViaBroadcastChannelResult> => {
if (isClientSideRendering || window.remotion_isMainTab) {
return extractFrameAndAudio({
logLevel,
@@ -180,13 +184,14 @@ export const extractFrameViaBroadcastChannel = ({
const resolvePromise = new Promise<
| {
+ type: 'success';
frame: ImageBitmap | null;
audio: PcmS16AudioData | null;
durationInSeconds: number | null;
}
- | 'cannot-decode'
- | 'network-error'
- | 'unknown-container-format'
+ | {type: 'cannot-decode'; durationInSeconds: number | null}
+ | {type: 'network-error'}
+ | {type: 'unknown-container-format'}
>((resolve, reject) => {
const onMessage = (event: MessageEvent) => {
const data = event.data as ExtractFrameResponse;
@@ -201,6 +206,7 @@ export const extractFrameViaBroadcastChannel = ({
if (data.type === 'response-success') {
resolve({
+ type: 'success',
frame: data.frame ? data.frame : null,
audio: data.audio ? data.audio : null,
durationInSeconds: data.durationInSeconds
@@ -224,7 +230,10 @@ export const extractFrameViaBroadcastChannel = ({
}
if (data.type === 'response-cannot-decode') {
- resolve('cannot-decode');
+ resolve({
+ type: 'cannot-decode',
+ durationInSeconds: data.durationInSeconds,
+ });
window.remotion_broadcastChannel!.removeEventListener(
'message',
onMessage,
@@ -233,7 +242,7 @@ export const extractFrameViaBroadcastChannel = ({
}
if (data.type === 'response-network-error') {
- resolve('network-error');
+ resolve({type: 'network-error'});
window.remotion_broadcastChannel!.removeEventListener(
'message',
onMessage,
@@ -242,7 +251,7 @@ export const extractFrameViaBroadcastChannel = ({
}
if (data.type === 'response-unknown-container-format') {
- resolve('unknown-container-format');
+ resolve({type: 'unknown-container-format'});
window.remotion_broadcastChannel!.removeEventListener(
'message',
onMessage,
diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsx
index e8b88b8306..262b05c326 100644
--- a/packages/media/src/video/video-for-preview.tsx
+++ b/packages/media/src/video/video-for-preview.tsx
@@ -29,32 +29,6 @@ const {
SequenceContext,
} = Internals;
-const calculateLoopDuration = ({
- endAt,
- mediaDuration,
- playbackRate,
- startFrom,
-}: {
- mediaDuration: number;
- playbackRate: number;
- startFrom: number | undefined;
- endAt: number | undefined;
-}) => {
- let duration = mediaDuration;
-
- if (typeof endAt !== 'undefined') {
- duration = endAt;
- }
-
- if (typeof startFrom !== 'undefined') {
- duration -= startFrom;
- }
-
- const actualDuration = duration / playbackRate;
-
- return Math.floor(actualDuration);
-};
-
type NewVideoForPreviewProps = {
readonly src: string;
readonly style: React.CSSProperties | undefined;
@@ -381,7 +355,7 @@ const VideoForPreviewWithDuration: React.FC<
return (
<Loop
- durationInFrames={calculateLoopDuration({
+ durationInFrames={Internals.calculateLoopDuration({
endAt: trimAfter,
mediaDuration,
playbackRate: playbackRate ?? 1,
diff --git a/packages/media/src/video/video-for-rendering.tsx b/packages/media/src/video/video-for-rendering.tsx
index edb543ff33..7507af5cc7 100644
--- a/packages/media/src/video/video-for-rendering.tsx
+++ b/packages/media/src/video/video-for-rendering.tsx
@@ -14,12 +14,14 @@ import type {
import {
cancelRender,
Internals,
+ Loop,
random,
useCurrentFrame,
useDelayRender,
useRemotionEnvironment,
useVideoConfig,
} from 'remotion';
+import {calculateLoopDuration} from '../../../core/src/calculate-loop';
import {applyVolume} from '../convert-audiodata/apply-volume';
import {frameForVolumeProp} from '../looped-frame';
import {extractFrameViaBroadcastChannel} from '../video-extraction/extract-frame-via-broadcast-channel';
@@ -46,6 +48,12 @@ type InnerVideoProps = {
readonly disallowFallbackToOffthreadVideo: boolean;
readonly stack: string | undefined;
readonly toneFrequency: number;
+ readonly trimBeforeValue: number | undefined;
+ readonly trimAfterValue: number | undefined;
+};
+
+type FallbackToOffthreadVideo = {
+ durationInSeconds: number | null;
};
export const VideoForRendering: React.FC<InnerVideoProps> = ({
@@ -67,6 +75,8 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
disallowFallbackToOffthreadVideo,
stack,
toneFrequency,
+ trimAfterValue,
+ trimBeforeValue,
}) => {
if (!src) {
throw new TypeError('No `src` was passed to <Video>.');
@@ -101,8 +111,9 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
const {delayRender, continueRender} = useDelayRender();
const canvasRef = useRef<HTMLCanvasElement>(null);
- const [replaceWithOffthreadVideo, setReplaceWithOffthreadVideo] =
- useState(false);
+ const [replaceWithOffthreadVideo, setReplaceWithOffthreadVideo] = useState<
+ FallbackToOffthreadVideo | false
+ >(false);
useLayoutEffect(() => {
if (!canvasRef.current) {
@@ -147,7 +158,7 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
audioStreamIndex,
})
.then((result) => {
- if (result === 'unknown-container-format') {
+ if (result.type === 'unknown-container-format') {
if (disallowFallbackToOffthreadVideo) {
cancelRender(
new Error(
@@ -163,11 +174,11 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
);
}
- setReplaceWithOffthreadVideo(true);
+ setReplaceWithOffthreadVideo({durationInSeconds: null});
return;
}
- if (result === 'cannot-decode') {
+ if (result.type === 'cannot-decode') {
if (disallowFallbackToOffthreadVideo) {
cancelRender(
new Error(
@@ -183,11 +194,13 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
);
}
- setReplaceWithOffthreadVideo(true);
+ setReplaceWithOffthreadVideo({
+ durationInSeconds: result.durationInSeconds,
+ });
return;
}
- if (result === 'network-error') {
+ if (result.type === 'network-error') {
if (disallowFallbackToOffthreadVideo) {
cancelRender(
new Error(
@@ -203,7 +216,7 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
);
}
- setReplaceWithOffthreadVideo(true);
+ setReplaceWithOffthreadVideo({durationInSeconds: null});
return;
}
@@ -323,7 +336,7 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
if (replaceWithOffthreadVideo) {
// TODO: Loop and other props
- return (
+ const fallback = (
<Internals.InnerOffthreadVideo
src={src}
playbackRate={playbackRate ?? 1}
@@ -362,6 +375,32 @@ export const VideoForRendering: React.FC<InnerVideoProps> = ({
_remotionInternalNativeLoopPassed={false}
/>
);
+
+ if (loop) {
+ if (!replaceWithOffthreadVideo.durationInSeconds) {
+ cancelRender(
+ 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.`,
+ ),
+ );
+ }
+
+ return (
+ <Loop
+ layout="none"
+ durationInFrames={calculateLoopDuration({
+ endAt: trimAfterValue,
+ mediaDuration: replaceWithOffthreadVideo.durationInSeconds,
+ playbackRate,
+ startFrom: trimBeforeValue,
+ })}
+ >
+ {fallback}
+ </Loop>
+ );
+ }
+
+ return fallback;
}
return <canvas ref={canvasRef} style={style} className={classNameValue} />;
diff --git a/packages/media/src/video/video.tsx b/packages/media/src/video/video.tsx
index 2f003d2cb8..d45c8624f8 100644
--- a/packages/media/src/video/video.tsx
+++ b/packages/media/src/video/video.tsx
@@ -120,6 +120,8 @@ const InnerVideo: React.FC<InnerVideoProps> = ({
style={style}
volume={volume}
toneFrequency={toneFrequency}
+ trimAfterValue={trimAfterValue}
+ trimBeforeValue={trimBeforeValue}
/>
);
}