🎥 Make videos programmatically with React
`@remotion/renderer`: Fix media rendering failures after `delayRender()` retries
Jonny Burgereb3cbdee246b
diff --git a/packages/media/src/video-extraction/add-broadcast-channel-listener.ts b/packages/media/src/video-extraction/add-broadcast-channel-listener.tsindex 7426a6df09..23518f2054 100644--- a/packages/media/src/video-extraction/add-broadcast-channel-listener.ts+++ b/packages/media/src/video-extraction/add-broadcast-channel-listener.ts@@ -44,6 +44,7 @@ export type MessageFromMainTab =}| {type: 'main-tab-ready';+ mainTabId: string;};export type ExtractFrameRequest = {@@ -69,16 +70,16 @@ export type ExtractFrameRequest = {// 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.+// Keep announcing readiness so newly opened tabs can also send requests.const emitReadiness = (channel: BroadcastChannel) => {- channel.postMessage({+ const message: MessageFromMainTab = {type: 'main-tab-ready',- } as MessageFromMainTab);+ mainTabId: crypto.getRandomValues(new Uint32Array(4)).join('-'),+ };+ channel.postMessage(message);setInterval(() => {- channel.postMessage({- type: 'main-tab-ready',- } as MessageFromMainTab);+ channel.postMessage(message);}, 300);};@@ -223,23 +224,24 @@ export const addBroadcastChannelListener = () => {};let mainTabIsReadyProm = null as Promise<void> | null;+let mainTabId: string | null = null;++export const waitForMainTabToBeReady = async (channel: BroadcastChannel) => {+ if (!mainTabIsReadyProm) {+ mainTabIsReadyProm = new Promise<void>((resolve) => {+ const onMessage = (event: MessageEvent) => {+ const data = event.data as MessageFromMainTab;+ if (data.type === 'main-tab-ready') {+ mainTabId = data.mainTabId;+ resolve();+ }+ };-export const waitForMainTabToBeReady = (channel: BroadcastChannel) => {- if (mainTabIsReadyProm) {- return mainTabIsReadyProm;+ // Track replacements for requests started after the first main tab loaded.+ channel.addEventListener('message', onMessage);+ });}- 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;+ await mainTabIsReadyProm;+ return mainTabId!;};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 b10e2d8d65..5047b54374 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@@ -91,137 +91,14 @@ export const extractFrameViaBroadcastChannel = async ({});}- await waitForMainTabToBeReady(window.remotion_broadcastChannel!);-- const requestId = crypto.randomUUID();-- const resolvePromise = new Promise<- | {- type: 'success';- frame: ImageBitmap | null;- audio: PcmS16AudioData | null;- durationInSeconds: number | null;- }- | {type: 'cannot-decode'; durationInSeconds: number | null}- | {type: 'cannot-decode-prores'; durationInSeconds: number | null}- | {type: 'cannot-decode-alpha'; durationInSeconds: number | null}- | {type: 'network-error'; error: Error | null}- | {type: 'unknown-container-format'; error: Error | null}- >((resolve, reject) => {- const onMessage = (event: MessageEvent) => {- const data = event.data as MessageFromMainTab;-- if (!data) {- return;- }-- if (data.type === 'main-tab-ready') {- return;- }-- if (data.id !== requestId) {- return;- }-- if (data.type === 'response-success') {- resolve({- type: 'success',- frame: data.frame ? data.frame : null,- audio: data.audio ? data.audio : null,- durationInSeconds: data.durationInSeconds- ? data.durationInSeconds- : null,- });- window.remotion_broadcastChannel!.removeEventListener(- 'message',- onMessage,- );- return;- }-- if (data.type === 'response-error') {- reject(data.errorStack);- window.remotion_broadcastChannel!.removeEventListener(- 'message',- onMessage,- );- return;- }-- if (data.type === 'response-cannot-decode') {- resolve({- type: 'cannot-decode',- durationInSeconds: data.durationInSeconds,- });- window.remotion_broadcastChannel!.removeEventListener(- 'message',- onMessage,- );- return;- }-- if (data.type === 'response-cannot-decode-prores') {- resolve({- type: 'cannot-decode-prores',- durationInSeconds: data.durationInSeconds,- });- window.remotion_broadcastChannel!.removeEventListener(- 'message',- onMessage,- );- return;- }-- if (- data.type === 'response-network-error' ||- data.type === 'response-unknown-container-format'- ) {- const error = data.error ? new Error(data.error.message) : null;- if (error && data.error) {- error.name = data.error.name;- error.stack = data.error.stack ?? undefined;- }-- resolve({- type:- data.type === 'response-network-error'- ? 'network-error'- : 'unknown-container-format',- error,- });- window.remotion_broadcastChannel!.removeEventListener(- 'message',- onMessage,- );- return;- }-- if (data.type === 'response-cannot-decode-alpha') {- resolve({- type: 'cannot-decode-alpha',- durationInSeconds: data.durationInSeconds,- });- window.remotion_broadcastChannel!.removeEventListener(- 'message',- onMessage,- );- return;- }-- throw new Error(- `Invalid message: ${JSON.stringify(data satisfies never)}`,- );- };-- window.remotion_broadcastChannel!.addEventListener('message', onMessage);- });-+ const channel = window.remotion_broadcastChannel!;+ let mainTabId = await waitForMainTabToBeReady(channel);const request: ExtractFrameRequest = {type: 'request',sampleRate,src,timeInSeconds,- id: requestId,+ id: crypto.randomUUID(),logLevel,durationInSeconds,playbackRate,@@ -236,27 +113,125 @@ export const extractFrameViaBroadcastChannel = async ({credentials,requestInit: normalizeMediaRequestInit(requestInit),};+ let cleanup = () => {};- window.remotion_broadcastChannel!.postMessage(request);+ const resolvePromise = new Promise<ExtractFrameViaBroadcastChannelResult>(+ (resolve, reject) => {+ const onMessage = (event: MessageEvent) => {+ const data = event.data as MessageFromMainTab;- let timeoutId: NodeJS.Timeout | undefined;+ if (!data) {+ return;+ }++ if (data.type === 'main-tab-ready') {+ if (data.mainTabId !== mainTabId) {+ mainTabId = data.mainTabId;+ // The old tab may have closed with this request still pending.+ channel.postMessage(request);+ }++ return;+ }++ if (data.id !== request.id) {+ return;+ }++ if (data.type === 'response-success') {+ resolve({+ type: 'success',+ frame: data.frame ? data.frame : null,+ audio: data.audio ? data.audio : null,+ durationInSeconds: data.durationInSeconds+ ? data.durationInSeconds+ : null,+ });+ return;+ }++ if (data.type === 'response-error') {+ reject(data.errorStack);+ return;+ }++ if (data.type === 'response-cannot-decode') {+ resolve({+ type: 'cannot-decode',+ durationInSeconds: data.durationInSeconds,+ });+ return;+ }++ if (data.type === 'response-cannot-decode-prores') {+ resolve({+ type: 'cannot-decode-prores',+ durationInSeconds: data.durationInSeconds,+ });+ return;+ }- return Promise.race([- resolvePromise.then((res) => {+ if (+ data.type === 'response-network-error' ||+ data.type === 'response-unknown-container-format'+ ) {+ const error = data.error ? new Error(data.error.message) : null;+ if (error && data.error) {+ error.name = data.error.name;+ error.stack = data.error.stack ?? undefined;+ }++ resolve({+ type:+ data.type === 'response-network-error'+ ? 'network-error'+ : 'unknown-container-format',+ error,+ });+ return;+ }++ if (data.type === 'response-cannot-decode-alpha') {+ resolve({+ type: 'cannot-decode-alpha',+ durationInSeconds: data.durationInSeconds,+ });+ return;+ }++ throw new Error(+ `Invalid message: ${JSON.stringify(data satisfies never)}`,+ );+ };++ channel.addEventListener('message', onMessage);+ cleanup = () => channel.removeEventListener('message', onMessage);+ },+ );++ let timeoutId: NodeJS.Timeout | null = null;+ try {+ channel.postMessage(request);+ return await Promise.race([+ resolvePromise,+ new Promise<never>((_, reject) => {+ timeoutId = setTimeout(+ () => {+ reject(+ new Error(+ `Timeout while extracting frame at time ${timeInSeconds}sec from ${src}`,+ ),+ );+ },+ Math.max(3_000, window.remotion_puppeteerTimeout - 5_000),+ );+ }),+ ]);+ } finally {+ if (timeoutId !== null) {clearTimeout(timeoutId);- return res;- }),- new Promise<never>((_, reject) => {- timeoutId = setTimeout(- () => {- reject(- new Error(- `Timeout while extracting frame at time ${timeInSeconds}sec from ${src}`,- ),- );- },- Math.max(3_000, window.remotion_puppeteerTimeout - 5_000),- );- }),- ]);+ }++ cleanup();+ }};diff --git a/packages/renderer/src/render-frame-and-retry-target-close.ts b/packages/renderer/src/render-frame-and-retry-target-close.tsindex 2b39dbd27b..3ba6975858 100644--- a/packages/renderer/src/render-frame-and-retry-target-close.ts+++ b/packages/renderer/src/render-frame-and-retry-target-close.ts@@ -187,7 +187,15 @@ export const renderFrameAndRetryTargetClose = async ({if (shouldRetryError) {const pool = await poolPromise;- // Replace the closed page+ // Close the timed-out page before creating another main tab at index 0.+ try {+ await freePage.close();+ } catch (closeError) {+ if (!(closeError instanceof Error) || !isTargetClosedErr(closeError)) {+ throw closeError;+ }+ }+const newPage = await makeNewPage(frame, freePage.pageIndex);pool.release(newPage);Log.warn(