Skip to content

🎥 Make videos programmatically with React

create mediaplayer class and control it as we control normal <video>

Igor Samokhovets5bf753199927
diff --git a/packages/video/src/media-player.ts b/packages/video/src/media-player.ts
new file mode 100644
index 0000000000..c547eca60c
--- /dev/null
+++ b/packages/video/src/media-player.ts
@@ -0,0 +1,314 @@
+import type {WrappedCanvas} from 'mediabunny';
+import {ALL_FORMATS, CanvasSink, Input, UrlSource} from 'mediabunny';
+import {Log, type LogLevel} from './log';
+
+export interface MediaPlayerOptions {
+ readonly logLevel?: LogLevel;
+}
+
+const SEEK_THRESHOLD = 0.05;
+
+export class MediaPlayer {
+ private canvas: HTMLCanvasElement;
+ private context: CanvasRenderingContext2D;
+ private src: string;
+ private logLevel: LogLevel;
+
+ private canvasSink: CanvasSink | null = null;
+ private videoFrameIterator: AsyncGenerator<
+ WrappedCanvas,
+ void,
+ unknown
+ > | null = null;
+
+ private nextFrame: WrappedCanvas | null = null;
+
+ private targetTime = 0; // set by React component via seekTo()
+
+ private playing = false;
+ private animationFrameId: number | null = null;
+
+ private asyncId = 0;
+
+ private initialized = false;
+ private totalDuration = 0;
+
+ constructor({
+ canvas,
+ src,
+ logLevel,
+ }: {
+ canvas: HTMLCanvasElement;
+ src: string;
+ logLevel: LogLevel;
+ }) {
+ this.canvas = canvas;
+ this.src = src;
+ this.logLevel = logLevel ?? 'info';
+
+ const context = canvas.getContext('2d', {
+ alpha: false,
+ desynchronized: true,
+ });
+ if (!context) {
+ throw new Error('Could not get 2D context from canvas');
+ }
+
+ this.context = context;
+
+ Log.trace(this.logLevel, `[MediaPlayer] Created for src: ${src}`);
+ }
+
+ public async initialize(): Promise<void> {
+ if (this.initialized) {
+ Log.trace(this.logLevel, `[MediaPlayer] Already initialized, skipping`);
+ return;
+ }
+
+ try {
+ Log.trace(this.logLevel, `[MediaPlayer] Initializing...`);
+
+ const input = new Input({
+ source: new UrlSource(this.src),
+ formats: ALL_FORMATS,
+ });
+
+ this.totalDuration = await input.computeDuration();
+ const videoTrack = await input.getPrimaryVideoTrack();
+
+ if (!videoTrack) {
+ throw new Error(`No video track found for ${this.src}`);
+ }
+
+ this.canvasSink = new CanvasSink(videoTrack, {
+ poolSize: 2,
+ fit: 'contain',
+ });
+
+ this.canvas.width = videoTrack.displayWidth;
+ this.canvas.height = videoTrack.displayHeight;
+
+ this.initialized = true;
+
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Initialized successfully, duration: ${this.totalDuration}s`,
+ );
+ } catch (error) {
+ Log.error('[MediaPlayer] Failed to initialize', error);
+ throw error;
+ }
+ }
+
+ public seekTo(time: number): void {
+ if (!this.initialized) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Not initialized, ignoring seekTo(${time})`,
+ );
+ return;
+ }
+
+ const newTargetTime = Math.max(0, Math.min(time, this.totalDuration));
+
+ const isSignificantSeek =
+ Math.abs(newTargetTime - this.targetTime) > SEEK_THRESHOLD;
+
+ this.targetTime = newTargetTime;
+
+ if (isSignificantSeek) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Significant seek to ${this.targetTime.toFixed(3)}s - creating new iterator`,
+ );
+ this.startVideoIterator(this.targetTime);
+ } else {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Minor time update to ${this.targetTime.toFixed(3)}s - using existing iterator`,
+ );
+
+ // if paused, trigger a single frame update to show current position
+ if (!this.playing) {
+ this.renderSingleFrame();
+ }
+ }
+ }
+
+ public play(): void {
+ if (!this.playing) {
+ this.playing = true;
+ Log.trace(this.logLevel, `[MediaPlayer] Play - starting render loop`);
+ this.startRenderLoop();
+ }
+ }
+
+ public pause(): void {
+ if (this.playing) {
+ this.playing = false;
+ Log.trace(this.logLevel, `[MediaPlayer] Pause - stopping render loop`);
+ this.stopRenderLoop();
+ }
+ }
+
+ public dispose(): void {
+ Log.trace(this.logLevel, `[MediaPlayer] Disposing...`);
+
+ this.stopRenderLoop();
+ this.videoFrameIterator?.return();
+ this.videoFrameIterator = null;
+ this.nextFrame = null;
+ this.canvasSink = null;
+ this.initialized = false;
+ this.asyncId++;
+ }
+
+ public get currentTime(): number {
+ return this.targetTime;
+ }
+
+ public get duration(): number {
+ return this.totalDuration;
+ }
+
+ public get isPlaying(): boolean {
+ return this.playing;
+ }
+
+ private renderSingleFrame(): void {
+ if (this.nextFrame && this.nextFrame.timestamp <= this.targetTime) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Single frame update at ${this.nextFrame.timestamp.toFixed(3)}s`,
+ );
+ this.context.drawImage(this.nextFrame.canvas, 0, 0);
+ this.nextFrame = null;
+ this.updateNextFrame();
+ }
+ }
+
+ private startRenderLoop(): void {
+ if (this.animationFrameId !== null) {
+ return;
+ }
+
+ Log.trace(this.logLevel, `[MediaPlayer] Starting render loop`);
+ this.render();
+ }
+
+ private stopRenderLoop(): void {
+ if (this.animationFrameId !== null) {
+ cancelAnimationFrame(this.animationFrameId);
+ this.animationFrameId = null;
+ Log.trace(this.logLevel, `[MediaPlayer] Stopped render loop`);
+ }
+ }
+
+ private render = (): void => {
+ if (this.nextFrame && this.nextFrame.timestamp <= this.targetTime) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Drawing frame at ${this.nextFrame.timestamp.toFixed(3)}s (target: ${this.targetTime.toFixed(3)}s)`,
+ );
+ this.context.drawImage(this.nextFrame.canvas, 0, 0);
+ this.nextFrame = null;
+
+ this.updateNextFrame();
+ }
+
+ // continue render loop only if playing
+ if (this.playing) {
+ this.animationFrameId = requestAnimationFrame(this.render);
+ } else {
+ this.animationFrameId = null;
+ }
+ };
+
+ private startVideoIterator = async (timeToSeek: number): Promise<void> => {
+ if (!this.canvasSink) {
+ return;
+ }
+
+ this.asyncId++;
+ const currentAsyncId = this.asyncId;
+
+ await this.videoFrameIterator?.return();
+
+ this.videoFrameIterator = this.canvasSink.canvases(timeToSeek);
+
+ try {
+ const firstFrame = (await this.videoFrameIterator.next()).value ?? null;
+ const secondFrame = (await this.videoFrameIterator.next()).value ?? null;
+
+ if (currentAsyncId !== this.asyncId) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Race condition detected, aborting startVideoIterator for ${timeToSeek.toFixed(3)}s`,
+ );
+ return;
+ }
+
+ if (firstFrame) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Drew initial frame ${firstFrame.timestamp.toFixed(3)}s`,
+ );
+ this.context.drawImage(firstFrame.canvas, 0, 0);
+ }
+
+ this.nextFrame = secondFrame;
+
+ if (secondFrame) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Buffered next frame ${secondFrame.timestamp.toFixed(3)}s`,
+ );
+ }
+ } catch (error) {
+ Log.error('[MediaPlayer] Failed to start video iterator', error);
+ }
+ };
+
+ private updateNextFrame = async (): Promise<void> => {
+ if (!this.videoFrameIterator) {
+ return;
+ }
+
+ const currentAsyncId = this.asyncId;
+
+ try {
+ while (true) {
+ const newNextFrame =
+ (await this.videoFrameIterator.next()).value ?? null;
+ if (!newNextFrame) {
+ break;
+ }
+
+ if (currentAsyncId !== this.asyncId) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Race condition detected in updateNextFrame`,
+ );
+ break;
+ }
+
+ if (newNextFrame.timestamp <= this.targetTime) {
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Drawing immediate frame ${newNextFrame.timestamp.toFixed(3)}s`,
+ );
+ this.context.drawImage(newNextFrame.canvas, 0, 0);
+ } else {
+ this.nextFrame = newNextFrame;
+ Log.trace(
+ this.logLevel,
+ `[MediaPlayer] Buffered next frame ${newNextFrame.timestamp.toFixed(3)}s`,
+ );
+ break;
+ }
+ }
+ } catch (error) {
+ Log.error('[MediaPlayer] Failed to update next frame', error);
+ }
+ };
+}
diff --git a/packages/video/src/new-video-for-preview.tsx b/packages/video/src/new-video-for-preview.tsx
index 4f8594587e..55f6ff357a 100644
--- a/packages/video/src/new-video-for-preview.tsx
+++ b/packages/video/src/new-video-for-preview.tsx
@@ -1,10 +1,9 @@
-import type {WrappedCanvas} from 'mediabunny';
-import {ALL_FORMATS, CanvasSink, Input, UrlSource} from 'mediabunny';
-import React, {useCallback, useEffect, useRef, useState} from 'react';
+import React, {useEffect, useRef, useState} from 'react';
import {Internals, useCurrentFrame} from 'remotion';
import {Log, type LogLevel} from './log';
+import {MediaPlayer} from './media-player';
-const {useUnsafeVideoConfig} = Internals;
+const {useUnsafeVideoConfig, Timeline} = Internals;
type NewVideoForPreviewProps = {
readonly src: string;
@@ -13,8 +12,6 @@ type NewVideoForPreviewProps = {
readonly logLevel?: LogLevel;
};
-const SEEK_THRESHOLD = 0.05;
-
export const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
src,
style,
@@ -24,16 +21,12 @@ export const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
const canvasRef = useRef<HTMLCanvasElement>(null);
const videoConfig = useUnsafeVideoConfig();
const frame = useCurrentFrame();
-
- const [canvasSink, setCanvasSink] = useState<CanvasSink | null>(null);
- const videoFrameIteratorRef = useRef<AsyncGenerator<
- WrappedCanvas,
- void,
- unknown
- > | null>(null);
- const nextFrameRef = useRef<WrappedCanvas | null>(null);
- const asyncIdRef = useRef<number>(0);
const lastCurrentTimeRef = useRef<number>(-1);
+ const mediaPlayerRef = useRef<MediaPlayer | null>(null);
+
+ const [mediaPlayerReady, setMediaPlayerReady] = useState(false);
+
+ const [playing] = Timeline.usePlayingState();
if (!videoConfig) {
throw new Error('No video config found');
@@ -46,190 +39,92 @@ export const NewVideoForPreview: React.FC<NewVideoForPreviewProps> = ({
const actualFps = videoConfig.fps / playbackRate;
const currentTime = frame / actualFps;
- // set up the canvas sink here
useEffect(() => {
- const currentAsyncId = asyncIdRef.current;
- const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource(src),
- });
-
- input
- .getPrimaryVideoTrack()
- .then((track) => {
- if (!track) {
- throw new Error(`No video track found for ${src}`);
- }
-
- const newCanvasSink = new CanvasSink(track, {
- poolSize: 2,
- });
-
- Log.trace(logLevel, `[NewVideoForPreview] Created canvas sink`);
- setCanvasSink(newCanvasSink);
- })
- .catch((err) => {
- Log.error('[NewVideoForPreview] Failed to set up sink', err);
- });
- return () => {
- asyncIdRef.current = currentAsyncId + 1; // cancel any pending operations
- videoFrameIteratorRef.current?.return();
- videoFrameIteratorRef.current = null;
- nextFrameRef.current = null;
- };
- }, [src, logLevel]);
-
- const drawFrame = useCallback((canvasImageSource: CanvasImageSource) => {
- const canvas = canvasRef.current;
- if (!canvas) {
- return;
- }
-
- const ctx = canvas.getContext('2d');
- if (!ctx) {
- return;
- }
-
- ctx.drawImage(canvasImageSource, 0, 0);
- }, []);
+ if (!canvasRef.current) return;
- const isSignificantSeek = useCallback((newTime: number): boolean => {
- if (lastCurrentTimeRef.current === -1) return true;
+ let mounted = true;
- const timeDiff = Math.abs(newTime - lastCurrentTimeRef.current);
- return timeDiff > SEEK_THRESHOLD;
- }, []);
-
- // uses existing iterator
- const updateNextFrame = useCallback(async () => {
- if (!videoFrameIteratorRef.current) return;
-
- const currentAsyncId = asyncIdRef.current;
-
- try {
- const result = await videoFrameIteratorRef.current.next();
-
- if (currentAsyncId !== asyncIdRef.current) {
+ const initializePlayer = async () => {
+ try {
Log.trace(
logLevel,
- `[NewVideoForPreview] Race condition detected, aborting fetch`,
+ `[NewVideoForPreview] Creating MediaPlayer for src: ${src}`,
);
- // race condition detected, just return
- return;
- }
-
- if (result.value) {
- Log.trace(
+ const player = new MediaPlayer({
+ canvas: canvasRef.current!,
+ src,
logLevel,
- `[NewVideoForPreview] Buffered next frame ${result.value.timestamp.toFixed(3)}s`,
- );
- nextFrameRef.current = result.value;
- }
- } catch (err) {
- Log.error('[NewVideoForPreview] Failed to update next frame', err);
- }
- }, [logLevel]);
-
- // frame consumption using existing iterator (like mediabunny render loop)
- const checkAndConsumeFrame = useCallback(() => {
- const nextFrame = nextFrameRef.current;
-
- if (nextFrame && nextFrame.timestamp <= currentTime) {
- Log.trace(
- logLevel,
- `[NewVideoForPreview] Using cached frame ${nextFrame.timestamp.toFixed(3)}s`,
- );
- drawFrame(nextFrame.canvas);
- nextFrameRef.current = null;
-
- // Continue using SAME iterator for next frame
- updateNextFrame();
- return true;
- }
-
- return false;
- }, [currentTime, drawFrame, logLevel, updateNextFrame]);
-
- // resets the current iterator, starts a new one
- const startVideoIterator = useCallback(
- async (timeToSeek: number) => {
- if (!canvasSink) return;
-
- asyncIdRef.current++;
- const currentAsyncId = asyncIdRef.current;
-
- // clean up previous iterator
- await videoFrameIteratorRef.current?.return();
+ });
- videoFrameIteratorRef.current = canvasSink.canvases(timeToSeek);
+ mediaPlayerRef.current = player;
+ await player.initialize();
- try {
- const firstFrame =
- (await videoFrameIteratorRef.current.next()).value ?? null;
- const secondFrame =
- (await videoFrameIteratorRef.current.next()).value ?? null;
-
- if (currentAsyncId !== asyncIdRef.current) {
- Log.trace(
- logLevel,
- `[NewVideoForPreview] Race condition detected, aborting fetch for ${timeToSeek.toFixed(3)}s`,
- );
+ if (!mounted) {
+ player.dispose();
return;
}
- if (firstFrame) {
- Log.trace(
- logLevel,
- `[NewVideoForPreview] Drew initial frame ${firstFrame.timestamp.toFixed(3)}s`,
+ Log.trace(
+ logLevel,
+ `[NewVideoForPreview] MediaPlayer initialized successfully`,
+ );
+
+ setMediaPlayerReady(true);
+ } catch (error) {
+ if (mounted) {
+ Log.error(
+ '[NewVideoForPreview] MediaPlayer initialization failed',
+ error,
);
- drawFrame(firstFrame.canvas);
}
+ }
+ };
- nextFrameRef.current = secondFrame;
+ initializePlayer();
- if (secondFrame) {
- updateNextFrame();
- }
- } catch (err) {
- Log.error('[NewVideoForPreview] Failed to start video iterator', err);
+ return () => {
+ mounted = false;
+ if (mediaPlayerRef.current) {
+ Log.trace(logLevel, `[NewVideoForPreview] Disposing MediaPlayer`);
+ mediaPlayerRef.current.dispose();
+ mediaPlayerRef.current = null;
}
- },
- [canvasSink, drawFrame, logLevel, updateNextFrame],
- );
+ };
+ }, [src, logLevel]);
- // main sync effect - mediabunny player example insipired
+ // sync play/pause state with Remotion timeline (like old VideoForPreview video does)
useEffect(() => {
- if (!canvasSink) return;
+ const mediaPlayer = mediaPlayerRef.current;
+ if (!mediaPlayer) return;
- const isSeek = isSignificantSeek(currentTime);
-
- if (isSeek) {
+ if (playing) {
Log.trace(
logLevel,
- `[NewVideoForPreview] Seek detected to ${currentTime.toFixed(3)}s, creating new iterator`,
+ `[NewVideoForPreview] Remotion playing - calling MediaPlayer.play()`,
);
- startVideoIterator(currentTime);
+ mediaPlayer.play();
} else {
- const frameConsumed = checkAndConsumeFrame();
-
- if (!frameConsumed && !nextFrameRef.current) {
- Log.trace(
- logLevel,
- `[NewVideoForPreview] No cached frame, fetching for ${currentTime.toFixed(3)}s`,
- );
- startVideoIterator(currentTime);
- }
+ Log.trace(
+ logLevel,
+ `[NewVideoForPreview] Remotion paused - calling MediaPlayer.pause()`,
+ );
+ mediaPlayer.pause();
}
+ }, [playing, logLevel]);
+
+ // sync target time with MediaPlayer
+ useEffect(() => {
+ const mediaPlayer = mediaPlayerRef.current;
+ if (!mediaPlayer || !mediaPlayerReady) return;
+
+ mediaPlayer.seekTo(currentTime);
+ Log.trace(
+ logLevel,
+ `[NewVideoForPreview] Updating target time to ${currentTime.toFixed(3)}s`,
+ );
lastCurrentTimeRef.current = currentTime;
- }, [
- canvasSink,
- currentTime,
- isSignificantSeek,
- checkAndConsumeFrame,
- startVideoIterator,
- logLevel,
- ]);
+ }, [currentTime, logLevel, mediaPlayerReady]);
return (
<canvas