🎥 Make videos programmatically with React
`@remotion/media`: Wait for BroadcastChannel to be ready
JonnyBurger197415ce39df
diff --git a/packages/media/src/video-extraction/add-broadcast-channel-listener.ts b/packages/media/src/video-extraction/add-broadcast-channel-listener.tsindex 1daac4ec3a..5e8e0b3f2e 100644--- a/packages/media/src/video-extraction/add-broadcast-channel-listener.ts+++ b/packages/media/src/video-extraction/add-broadcast-channel-listener.ts@@ -2,7 +2,7 @@ import type {LogLevel} from 'remotion';import type {PcmS16AudioData} from '../convert-audiodata/convert-audiodata';import {extractFrameAndAudio} from '../extract-frame-and-audio';-export type ExtractFrameResponse =+export type MessageFromMainTab =| {type: 'response-success';id: string;@@ -32,6 +32,9 @@ export type ExtractFrameResponse =| {type: 'response-unknown-container-format';id: string;+ }+ | {+ type: 'main-tab-ready';};export type ExtractFrameRequest = {@@ -52,114 +55,159 @@ export type ExtractFrameRequest = {maxCacheSize: number;};+// Send to other channels a message to let them know that the+// tab was loaded and is ready to receive requests.+// Emit "readiness" messages for approximately 10 seconds.+const emitReadiness = (channel: BroadcastChannel) => {+ channel.postMessage({+ type: 'main-tab-ready',+ } as MessageFromMainTab);++ let times = 0;++ const interval = setInterval(() => {+ channel.postMessage({+ type: 'main-tab-ready',+ } as MessageFromMainTab);+ times++;+ if (times > 30) {+ clearInterval(interval);+ }+ }, 300);+};+export const addBroadcastChannelListener = () => {// Doesn't exist in studioif (- typeof window !== 'undefined' &&- window.remotion_broadcastChannel &&- window.remotion_isMainTab+ !(+ typeof window !== 'undefined' &&+ window.remotion_broadcastChannel &&+ window.remotion_isMainTab+ )) {- window.remotion_broadcastChannel.addEventListener(- 'message',- async (event) => {- const data = event.data as ExtractFrameRequest;- if (data.type === 'request') {- try {- const result = await extractFrameAndAudio({- src: data.src,- timeInSeconds: data.timeInSeconds,- logLevel: data.logLevel,- durationInSeconds: data.durationInSeconds,- playbackRate: data.playbackRate,- includeAudio: data.includeAudio,- includeVideo: data.includeVideo,- loop: data.loop,- audioStreamIndex: data.audioStreamIndex,- trimAfter: data.trimAfter,- trimBefore: data.trimBefore,- fps: data.fps,- maxCacheSize: data.maxCacheSize,- });-- 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.type === 'cannot-decode-alpha') {- const cannotDecodeAlphaResponse: ExtractFrameResponse = {- type: 'response-cannot-decode-alpha',- id: data.id,- durationInSeconds: result.durationInSeconds,- };-- window.remotion_broadcastChannel!.postMessage(- cannotDecodeAlphaResponse,- );- return;- }-- if (result.type === 'network-error') {- const networkErrorResponse: ExtractFrameResponse = {- type: 'response-network-error',- id: data.id,- };-- window.remotion_broadcastChannel!.postMessage(- networkErrorResponse,- );- return;- }-- if (result.type === 'unknown-container-format') {- const unknownContainerFormatResponse: ExtractFrameResponse = {- type: 'response-unknown-container-format',- id: data.id,- };-- window.remotion_broadcastChannel!.postMessage(- unknownContainerFormatResponse,- );- return;- }-- const {frame, audio, durationInSeconds} = result;-- const imageBitmap = frame ? await createImageBitmap(frame) : null;- if (frame) {- frame.close();- }-- const response: ExtractFrameResponse = {- type: 'response-success',+ return;+ }++ window.remotion_broadcastChannel.addEventListener(+ 'message',+ async (event) => {+ const data = event.data as ExtractFrameRequest;+ if (data.type === 'request') {+ try {+ const result = await extractFrameAndAudio({+ src: data.src,+ timeInSeconds: data.timeInSeconds,+ logLevel: data.logLevel,+ durationInSeconds: data.durationInSeconds,+ playbackRate: data.playbackRate,+ includeAudio: data.includeAudio,+ includeVideo: data.includeVideo,+ loop: data.loop,+ audioStreamIndex: data.audioStreamIndex,+ trimAfter: data.trimAfter,+ trimBefore: data.trimBefore,+ fps: data.fps,+ maxCacheSize: data.maxCacheSize,+ });++ if (result.type === 'cannot-decode') {+ const cannotDecodeResponse: MessageFromMainTab = {+ type: 'response-cannot-decode',id: data.id,- frame: imageBitmap,- audio,- durationInSeconds: durationInSeconds ?? null,+ durationInSeconds: result.durationInSeconds,};- window.remotion_broadcastChannel!.postMessage(response);- } catch (error) {- const response: ExtractFrameResponse = {- type: 'response-error',+ window.remotion_broadcastChannel!.postMessage(cannotDecodeResponse);+ return;+ }++ if (result.type === 'cannot-decode-alpha') {+ const cannotDecodeAlphaResponse: MessageFromMainTab = {+ type: 'response-cannot-decode-alpha',id: data.id,- errorStack: (error as Error).stack ?? 'No stack trace',+ durationInSeconds: result.durationInSeconds,};- window.remotion_broadcastChannel!.postMessage(response);+ window.remotion_broadcastChannel!.postMessage(+ cannotDecodeAlphaResponse,+ );+ return;}- } else {- throw new Error('Invalid message: ' + JSON.stringify(data));++ if (result.type === 'network-error') {+ const networkErrorResponse: MessageFromMainTab = {+ type: 'response-network-error',+ id: data.id,+ };++ window.remotion_broadcastChannel!.postMessage(networkErrorResponse);+ return;+ }++ if (result.type === 'unknown-container-format') {+ const unknownContainerFormatResponse: MessageFromMainTab = {+ type: 'response-unknown-container-format',+ id: data.id,+ };++ window.remotion_broadcastChannel!.postMessage(+ unknownContainerFormatResponse,+ );+ return;+ }++ const {frame, audio, durationInSeconds} = result;++ const imageBitmap = frame ? await createImageBitmap(frame) : null;+ if (frame) {+ frame.close();+ }++ const response: MessageFromMainTab = {+ type: 'response-success',+ id: data.id,+ frame: imageBitmap,+ audio,+ durationInSeconds: durationInSeconds ?? null,+ };++ window.remotion_broadcastChannel!.postMessage(response);+ } catch (error) {+ const response: MessageFromMainTab = {+ type: 'response-error',+ id: data.id,+ errorStack: (error as Error).stack ?? 'No stack trace',+ };++ window.remotion_broadcastChannel!.postMessage(response);}- },- );+ } else {+ throw new Error('Invalid message: ' + JSON.stringify(data));+ }+ },+ );++ emitReadiness(window.remotion_broadcastChannel!);+};++let mainTabIsReadyProm = null as Promise<void> | null;++export const waitForMainTabToBeReady = (channel: BroadcastChannel) => {+ if (mainTabIsReadyProm) {+ return mainTabIsReadyProm;}++ mainTabIsReadyProm = new Promise<void>((resolve) => {+ const onMessage = (event: MessageEvent) => {+ const data = event.data as MessageFromMainTab;+ if (data.type === 'main-tab-ready') {+ resolve();+ channel.removeEventListener('message', onMessage);+ }+ };++ channel.addEventListener('message', onMessage);+ });++ return mainTabIsReadyProm;};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.tsindex fdab64ab9e..f936d6d858 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@@ -3,9 +3,12 @@ import type {PcmS16AudioData} from '../convert-audiodata/convert-audiodata';import {extractFrameAndAudio} from '../extract-frame-and-audio';import type {ExtractFrameRequest,- ExtractFrameResponse,+ MessageFromMainTab,+} from './add-broadcast-channel-listener';+import {+ addBroadcastChannelListener,+ waitForMainTabToBeReady,} from './add-broadcast-channel-listener';-import {addBroadcastChannelListener} from './add-broadcast-channel-listener';export type ExtractFrameViaBroadcastChannelResult =| {@@ -21,7 +24,7 @@ export type ExtractFrameViaBroadcastChannelResult =addBroadcastChannelListener();-export const extractFrameViaBroadcastChannel = ({+export const extractFrameViaBroadcastChannel = async ({src,timeInSeconds,logLevel,@@ -70,6 +73,8 @@ export const extractFrameViaBroadcastChannel = ({});}+ await waitForMainTabToBeReady(window.remotion_broadcastChannel!);+const requestId = crypto.randomUUID();const resolvePromise = new Promise<@@ -85,12 +90,16 @@ export const extractFrameViaBroadcastChannel = ({| {type: 'unknown-container-format'}>((resolve, reject) => {const onMessage = (event: MessageEvent) => {- const data = event.data as ExtractFrameResponse;+ const data = event.data as MessageFromMainTab;if (!data) {return;}+ if (data.type === 'main-tab-ready') {+ return;+ }+if (data.id !== requestId) {return;}