Skip to content

🎥 Make videos programmatically with React

awesome

JonnyBurgere4d96a0dd293
diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsx
index 16c1359b9a..7238457a6c 100644
--- a/packages/media/src/audio/audio-for-preview.tsx
+++ b/packages/media/src/audio/audio-for-preview.tsx
@@ -5,7 +5,9 @@ import {
Audio as RemotionAudio,
useBufferState,
useCurrentFrame,
+ useVideoConfig,
} from 'remotion';
+import {getTimeInSeconds} from '../get-time-in-seconds';
import {MediaPlayer} from '../media-player';
import {useLoopDisplay} from '../show-in-timeline';
import {useMediaInTimeline} from '../use-media-in-timeline';
@@ -43,7 +45,7 @@ type NewAudioForPreviewProps = {
readonly fallbackHtml5AudioProps: FallbackHtml5AudioProps | undefined;
};
-const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
+const AudioForPreviewAssertedShowing: React.FC<NewAudioForPreviewProps> = ({
src,
playbackRate,
logLevel,
@@ -231,14 +233,14 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
setMediaPlayerReady(true);
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- `[NewAudioForPreview] MediaPlayer initialized successfully`,
+ `[AudioForPreview] MediaPlayer initialized successfully`,
);
}
})
.catch((error) => {
Internals.Log.error(
{logLevel, tag: '@remotion/media'},
- '[NewAudioForPreview] Failed to initialize MediaPlayer',
+ '[AudioForPreview] Failed to initialize MediaPlayer',
error,
);
setShouldFallbackToNativeAudio(true);
@@ -246,7 +248,7 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
} catch (error) {
Internals.Log.error(
{logLevel, tag: '@remotion/media'},
- '[NewAudioForPreview] MediaPlayer initialization failed',
+ '[AudioForPreview] MediaPlayer initialization failed',
error,
);
setShouldFallbackToNativeAudio(true);
@@ -261,7 +263,7 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
if (mediaPlayerRef.current) {
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- `[NewAudioForPreview] Disposing MediaPlayer`,
+ `[AudioForPreview] Disposing MediaPlayer`,
);
mediaPlayerRef.current.dispose();
mediaPlayerRef.current = null;
@@ -303,7 +305,7 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
audioPlayer.seekTo(currentTime);
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- `[NewAudioForPreview] Updating target time to ${currentTime.toFixed(3)}s`,
+ `[AudioForPreview] Updating target time to ${currentTime.toFixed(3)}s`,
);
}, [currentTime, logLevel, mediaPlayerReady]);
@@ -420,8 +422,40 @@ export const AudioForPreview: React.FC<InnerAudioProps> = ({
}) => {
const preloadedSrc = usePreload(src);
+ const frame = useCurrentFrame();
+ const videoConfig = useVideoConfig();
+ const currentTime = frame / videoConfig.fps;
+
+ const showShow = useMemo(() => {
+ return (
+ getTimeInSeconds({
+ unloopedTimeInSeconds: currentTime,
+ playbackRate: playbackRate ?? 1,
+ loop: loop ?? false,
+ trimBefore,
+ trimAfter,
+ mediaDurationInSeconds: Infinity,
+ fps: videoConfig.fps,
+ ifNoMediaDuration: 'infinity',
+ src,
+ }) !== null
+ );
+ }, [
+ currentTime,
+ loop,
+ playbackRate,
+ src,
+ trimAfter,
+ trimBefore,
+ videoConfig.fps,
+ ]);
+
+ if (!showShow) {
+ return null;
+ }
+
return (
- <NewAudioForPreview
+ <AudioForPreviewAssertedShowing
audioStreamIndex={audioStreamIndex ?? 0}
src={preloadedSrc}
playbackRate={playbackRate ?? 1}
diff --git a/packages/media/src/get-time-in-seconds.ts b/packages/media/src/get-time-in-seconds.ts
index f9b797f5f3..c6d723b28e 100644
--- a/packages/media/src/get-time-in-seconds.ts
+++ b/packages/media/src/get-time-in-seconds.ts
@@ -31,7 +31,7 @@ export const getTimeInSeconds = ({
? Internals.calculateMediaDuration({
trimAfter,
mediaDurationInFrames: mediaDurationInSeconds
- ? mediaDurationInSeconds! * fps
+ ? mediaDurationInSeconds * fps
: Infinity,
// Playback rate was already specified before
playbackRate: 1,
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index cd86751123..c7494e3758 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -105,6 +105,11 @@ export class MediaPlayer {
this.bufferState = bufferState;
this.nonceManager = makeNonceManager();
+ this.input = new Input({
+ source: new UrlSource(this.src),
+ formats: ALL_FORMATS,
+ });
+
if (canvas) {
const context = canvas.getContext('2d', {
alpha: true,
@@ -121,10 +126,10 @@ export class MediaPlayer {
}
}
- private input: Input<UrlSource> | null = null;
+ private input: Input<UrlSource>;
private isDisposalError(): boolean {
- return this.input?.disposed === true;
+ return this.input.disposed === true;
}
public initialize(
@@ -139,21 +144,12 @@ export class MediaPlayer {
startTimeUnresolved: number,
): Promise<MediaPlayerInitResult> {
try {
- const urlSource = new UrlSource(this.src);
-
- const input = new Input({
- source: urlSource,
- formats: ALL_FORMATS,
- });
-
- this.input = input;
-
- if (input.disposed) {
+ if (this.input.disposed) {
return {type: 'disposed'};
}
try {
- await input.getFormat();
+ await this.input.getFormat();
} catch (error) {
if (this.isDisposalError()) {
return {type: 'disposed'};
@@ -175,10 +171,14 @@ export class MediaPlayer {
}
const [durationInSeconds, videoTrack, audioTracks] = await Promise.all([
- input.computeDuration(),
- input.getPrimaryVideoTrack(),
- input.getAudioTracks(),
+ this.input.computeDuration(),
+ this.input.getPrimaryVideoTrack(),
+ this.input.getAudioTracks(),
]);
+ if (this.input.disposed) {
+ return {type: 'disposed'};
+ }
+
this.totalDuration = durationInSeconds;
const audioTrack = audioTracks[this.audioStreamIndex] ?? null;
@@ -194,6 +194,10 @@ export class MediaPlayer {
return {type: 'cannot-decode'};
}
+ if (this.input.disposed) {
+ return {type: 'disposed'};
+ }
+
this.videoIteratorManager = videoIteratorManager({
videoTrack,
bufferState: this.bufferState,
@@ -218,7 +222,7 @@ export class MediaPlayer {
});
if (startTime === null) {
- return {type: 'success', durationInSeconds: this.totalDuration};
+ throw new Error(`should have asserted that the time is not null`);
}
this.setPlaybackTime(startTime);
@@ -281,21 +285,6 @@ export class MediaPlayer {
}
public async seekTo(time: number): Promise<void> {
- const nonce = this.nonceManager.createAsyncOperation();
- await this.seekPromiseChain;
-
- this.seekPromiseChain = this.seekToDoNotCallDirectly(time, nonce);
- await this.seekPromiseChain;
- }
-
- public async seekToDoNotCallDirectly(
- time: number,
- nonce: Nonce,
- ): Promise<void> {
- if (nonce.isStale()) {
- return;
- }
-
const newTime = getTimeInSeconds({
unloopedTimeInSeconds: time,
playbackRate: this.playbackRate,
@@ -309,9 +298,21 @@ export class MediaPlayer {
});
if (newTime === null) {
- // invalidate in-flight video operations
- this.videoIteratorManager?.destroy();
- this.audioIteratorManager?.destroy();
+ throw new Error(`should have asserted that the time is not null`);
+ }
+
+ const nonce = this.nonceManager.createAsyncOperation();
+ await this.seekPromiseChain;
+
+ this.seekPromiseChain = this.seekToDoNotCallDirectly(time, nonce);
+ await this.seekPromiseChain;
+ }
+
+ public async seekToDoNotCallDirectly(
+ newTime: number,
+ nonce: Nonce,
+ ): Promise<void> {
+ if (nonce.isStale()) {
return;
}
@@ -406,9 +407,11 @@ export class MediaPlayer {
}
}
- this.input?.dispose();
+ // Mark all async operations as stale
+ this.nonceManager.createAsyncOperation();
this.videoIteratorManager?.destroy();
this.audioIteratorManager?.destroy();
+ this.input.dispose();
}
private scheduleAudioNode = (
diff --git a/packages/media/src/video-iterator-manager.ts b/packages/media/src/video-iterator-manager.ts
index 6410191740..cd7043ca4c 100644
--- a/packages/media/src/video-iterator-manager.ts
+++ b/packages/media/src/video-iterator-manager.ts
@@ -110,7 +110,9 @@ export const videoIteratorManager = ({
}
// Intentionally not awaited, letting audio start as well
- startVideoIterator(newTime, nonce);
+ startVideoIterator(newTime, nonce).catch(() => {
+ // Ignore errors, might be stale or disposed
+ });
};
return {
diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsx
index 81ade2c68b..af4ddb083f 100644
--- a/packages/media/src/video/video-for-preview.tsx
+++ b/packages/media/src/video/video-for-preview.tsx
@@ -7,7 +7,14 @@ import React, {
useState,
} from 'react';
import type {LogLevel, LoopVolumeCurveBehavior, VolumeProp} from 'remotion';
-import {Html5Video, Internals, useBufferState, useCurrentFrame} from 'remotion';
+import {
+ Html5Video,
+ Internals,
+ useBufferState,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+import {getTimeInSeconds} from '../get-time-in-seconds';
import {MediaPlayer} from '../media-player';
import {useLoopDisplay} from '../show-in-timeline';
import {useMediaInTimeline} from '../use-media-in-timeline';
@@ -49,7 +56,7 @@ type VideoForPreviewProps = {
readonly debugOverlay: boolean;
};
-export const VideoForPreview: React.FC<VideoForPreviewProps> = ({
+const VideoForPreviewAssertedShowing: React.FC<VideoForPreviewProps> = ({
src: unpreloadedSrc,
style,
playbackRate,
@@ -429,3 +436,39 @@ export const VideoForPreview: React.FC<VideoForPreviewProps> = ({
/>
);
};
+
+export const VideoForPreview: React.FC<VideoForPreviewProps> = (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,
+ props.trimAfter,
+ props.trimBefore,
+ videoConfig.fps,
+ ]);
+
+ if (!showShow) {
+ return null;
+ }
+
+ return <VideoForPreviewAssertedShowing {...props} />;
+};