🎥 Make videos programmatically with React
alright
JonnyBurger06f197f9294f
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 7a0fcd6c41..89fed17b61 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -23,7 +23,6 @@ import {type VideoIterator,} from './video/video-preview-iterator';-export const SEEK_THRESHOLD = 0.05;const AUDIO_BUFFER_TOLERANCE_THRESHOLD = 0.1;export type MediaPlayerInitResult =@@ -34,11 +33,6 @@ export type MediaPlayerInitResult =| {type: 'no-tracks'}| {type: 'disposed'};-type DrawnFrame = {- timestamp: number;- endTimestamp: number;-};-export class MediaPlayer {private canvas: HTMLCanvasElement | null;private context: CanvasRenderingContext2D | null;@@ -87,8 +81,6 @@ export class MediaPlayer {private initializationPromise: Promise<MediaPlayerInitResult> | null = null;- private drawnFrame: DrawnFrame | null = null;-constructor({canvas,src,@@ -347,22 +339,21 @@ export class MediaPlayer {return;}- const isSignificantSeek =- currentPlaybackTime === null ||- Math.abs(newTime - currentPlaybackTime) > SEEK_THRESHOLD;+ const satisfyResult =+ await this.videoFrameIterator?.tryToSatisfySeekOrDestroy(newTime);- this.audioSyncAnchor = this.sharedAudioContext.currentTime - newTime;+ if (satisfyResult?.type === 'satisfied') {+ this.drawFrame(satisfyResult.frame);+ return;+ }- if (isSignificantSeek) {- this.mediaEnded = false;+ this.mediaEnded = false;+ this.audioSyncAnchor = this.sharedAudioContext.currentTime - newTime;- await Promise.all([- this.startAudioIterator(newTime),- this.startVideoIterator(newTime),- ]);- } else if (!this.playing) {- this.render();- }+ await Promise.all([+ this.startAudioIterator(newTime),+ this.startVideoIterator(newTime),+ ]);}public async play(): Promise<void> {@@ -526,6 +517,24 @@ export class MediaPlayer {this.renderPromiseChain = null;};+ private drawFrame = (frame: WrappedCanvas): void => {+ if (!this.context) {+ throw new Error('Context not initialized');+ }++ this.context.clearRect(0, 0, this.canvas!.width, this.canvas!.height);+ this.context.drawImage(frame.canvas, 0, 0);+ this.drawDebugOverlay();+ if (this.onVideoFrameCallback && this.canvas) {+ this.onVideoFrameCallback(this.canvas);+ }++ Internals.Log.trace(+ {logLevel: this.logLevel, tag: '@remotion/media'},+ `[MediaPlayer] Drew frame ${frame.timestamp.toFixed(3)}s`,+ );+ };+private renderDoNotCallDirectly = async (nonce: number): Promise<void> => {if (nonce !== this.currentRenderNonce) {return;@@ -560,22 +569,8 @@ export class MediaPlayer {}}- if (this.context && frame) {- this.context.clearRect(0, 0, this.canvas!.width, this.canvas!.height);- this.context.drawImage(frame.canvas, 0, 0);- this.drawDebugOverlay();- if (this.onVideoFrameCallback && this.canvas) {- this.onVideoFrameCallback(this.canvas);- }-- this.drawnFrame = {- timestamp: frame.timestamp,- endTimestamp: frame.timestamp + frame.duration,- };- Internals.Log.trace(- {logLevel: this.logLevel, tag: '@remotion/media'},- `[MediaPlayer] Drew frame ${frame.timestamp.toFixed(3)}s`,- );+ if (frame) {+ this.drawFrame(frame);}}@@ -596,13 +591,19 @@ export class MediaPlayer {return false;}- if (this.drawnFrame === null) {+ if (this.videoFrameIterator === null) {+ return true;+ }++ const lastReturnedFrame = this.videoFrameIterator.getLastReturnedFrame();+ if (lastReturnedFrame === null) {return true;}return (- roundTo4Digits(this.drawnFrame.endTimestamp) <=- roundTo4Digits(playbackTime)+ roundTo4Digits(+ lastReturnedFrame.timestamp + lastReturnedFrame.duration,+ ) <= roundTo4Digits(playbackTime));}diff --git a/packages/media/src/video/video-preview-iterator.ts b/packages/media/src/video/video-preview-iterator.tsindex 49e2515f4d..b284a56cac 100644--- a/packages/media/src/video/video-preview-iterator.ts+++ b/packages/media/src/video/video-preview-iterator.ts@@ -1,4 +1,5 @@-import type {CanvasSink} from 'mediabunny';+import type {CanvasSink, WrappedCanvas} from 'mediabunny';+import {roundTo4Digits} from '../helpers/round-to-4-digits';export const createVideoIterator = (timeToSeek: number,@@ -6,6 +7,8 @@ export const createVideoIterator = () => {let destroyed = false;const iterator = videoSink.canvases(timeToSeek);+ let lastReturnedFrame: WrappedCanvas | null = null;+ let iteratorEnded = false;const getNextOrNullIfNotAvailable = async () => {const next = iterator.next();@@ -15,34 +18,124 @@ export const createVideoIterator = (Promise.resolve().then(() => resolve());}),]);+if (!result) {return {type: 'need-to-wait-for-it' as const,waitPromise: async () => {const res = await next;+ if (res.value) {+ lastReturnedFrame = res.value;+ } else {+ iteratorEnded = true;+ }+return res.value;},};}+ if (result.value) {+ lastReturnedFrame = result.value;+ } else {+ iteratorEnded = true;+ }+return {type: 'got-frame-or-end' as const,- frame: result.value,+ frame: result.value ?? null,};};+ const destroy = () => {+ destroyed = true;+ lastReturnedFrame = null;+ iterator.return().catch(() => undefined);+ };++ const tryToSatisfySeekOrDestroy = async (+ time: number,+ ): Promise<+ | {+ type: 'not-satisfied';+ }+ | {+ type: 'satisfied';+ frame: WrappedCanvas;+ }+ > => {+ if (lastReturnedFrame && time < lastReturnedFrame.timestamp) {+ return {+ type: 'not-satisfied' as const,+ };+ }++ if (iteratorEnded) {+ if (lastReturnedFrame) {+ return {+ type: 'satisfied' as const,+ frame: lastReturnedFrame,+ };+ }++ return {+ type: 'not-satisfied' as const,+ };+ }++ while (true) {+ const frame = await getNextOrNullIfNotAvailable();+ if (frame.type === 'need-to-wait-for-it') {+ return {+ type: 'not-satisfied' as const,+ };+ }++ if (frame.type === 'got-frame-or-end') {+ if (frame.frame === null) {+ iteratorEnded = true;+ if (lastReturnedFrame) {+ return {+ type: 'satisfied' as const,+ frame: lastReturnedFrame,+ };+ }++ return {+ type: 'not-satisfied' as const,+ };+ }++ const frameTimestamp = roundTo4Digits(frame.frame.timestamp);+ const frameEndTimestamp = roundTo4Digits(+ frame.frame.timestamp + frame.frame.duration,+ );+ const timestamp = roundTo4Digits(time);+ if (frameTimestamp <= timestamp && frameEndTimestamp > timestamp) {+ return {+ type: 'satisfied' as const,+ frame: frame.frame,+ };+ }++ continue;+ }++ throw new Error('Unreachable');+ }+ };+return {getNextOrNullIfNotAvailable,- destroy: () => {- destroyed = true;- iterator.return().catch(() => undefined);- },+ destroy,getNext: () => {return iterator.next();},isDestroyed: () => {return destroyed;},+ tryToSatisfySeekOrDestroy,+ getLastReturnedFrame: () => lastReturnedFrame,};};