Skip to content

🎥 Make videos programmatically with React

Close extracted video frames on parallel audio failures

Alec Watts11a7dff56503
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.ts
index f4a596f3c7..7b921caeee 100644
--- a/packages/media/src/extract-frame-and-audio.ts
+++ b/packages/media/src/extract-frame-and-audio.ts
@@ -44,6 +44,7 @@ export const extractFrameAndAudio = async ({
requestInit?: MediaRequestInit;
mediaCache: MediaCache;
}): Promise<ExtractFrameViaBroadcastChannelResult> => {
+ let extractedFrame: VideoFrame | null = null;
try {
if (includeVideo || includeAudio) {
const sink = await mediaCache.sinkManager.getSink(
@@ -63,7 +64,7 @@ export const extractFrameAndAudio = async ({
}
}
- const [video, audio] = await Promise.all([
+ const [videoResult, audioResult] = await Promise.allSettled([
includeVideo
? extractFrame({
src,
@@ -101,6 +102,20 @@ export const extractFrameAndAudio = async ({
: null,
]);
+ // Wait for both branches before releasing a frame: audio can reject
+ // while video extraction is still producing its owned VideoFrame.
+ if (videoResult.status === 'rejected') {
+ throw videoResult.reason;
+ }
+
+ const video = videoResult.value;
+ extractedFrame = video?.type === 'success' ? video.frame : null;
+ if (audioResult.status === 'rejected') {
+ throw audioResult.reason;
+ }
+
+ const audio = audioResult.value;
+
if (video?.type === 'cannot-decode') {
return {
type: 'cannot-decode',
@@ -164,5 +179,7 @@ export const extractFrameAndAudio = async ({
}
throw err;
+ } finally {
+ extractedFrame?.close();
}
};
diff --git a/packages/media/src/test/extraction-frame-cleanup.test.ts b/packages/media/src/test/extraction-frame-cleanup.test.ts
new file mode 100644
index 0000000000..69dfa273fa
--- /dev/null
+++ b/packages/media/src/test/extraction-frame-cleanup.test.ts
@@ -0,0 +1,89 @@
+import {expect, test, vi} from 'vitest';
+import {extractAudio} from '../audio-extraction/extract-audio';
+import type {MediaCache} from '../caches';
+import {extractFrameAndAudio} from '../extract-frame-and-audio';
+import {extractFrame} from '../video-extraction/extract-frame';
+
+vi.mock('../audio-extraction/extract-audio', () => ({extractAudio: vi.fn()}));
+vi.mock('../video-extraction/extract-frame', () => ({extractFrame: vi.fn()}));
+
+const params = {
+ src: 'blob:frame-cleanup',
+ sampleRate: 48000,
+ timeInSeconds: 0,
+ durationInSeconds: 1 / 30,
+ playbackRate: 1,
+ logLevel: 'error' as const,
+ includeAudio: true,
+ includeVideo: true,
+ loop: false,
+ audioStreamIndex: null,
+ trimAfter: undefined,
+ trimBefore: undefined,
+ fps: 30,
+ maxCacheSize: 1024,
+ credentials: undefined,
+ mediaCache: {
+ sinkManager: {getSink: () => Promise.resolve({formatDetectionError: null})},
+ } as unknown as MediaCache,
+};
+
+// A real VideoFrame makes this a resource-ownership regression, not a close mock.
+for (const outcome of [
+ 'success',
+ 'unsupported-audio',
+ 'rejected-audio',
+ 'bitmap-error',
+] as const) {
+ test(`releases the extracted frame after ${outcome}`, async () => {
+ const frame = new VideoFrame(new Uint8Array(16), {
+ format: 'RGBA',
+ codedWidth: 2,
+ codedHeight: 2,
+ timestamp: 0,
+ });
+ const failure = new Error('audio extraction failed');
+ vi.mocked(extractFrame).mockImplementation(async () => {
+ // Ensure an audio rejection can happen before the frame arrives.
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ return {type: 'success', frame, rotation: 0, durationInSeconds: 1};
+ });
+ if (outcome === 'rejected-audio') {
+ vi.mocked(extractAudio).mockRejectedValue(failure);
+ } else if (outcome === 'unsupported-audio') {
+ vi.mocked(extractAudio).mockResolvedValue('cannot-decode');
+ } else {
+ vi.mocked(extractAudio).mockResolvedValue({
+ data: null,
+ durationInSeconds: 1,
+ });
+ }
+
+ const bitmap =
+ outcome === 'bitmap-error'
+ ? vi
+ .spyOn(globalThis, 'createImageBitmap')
+ .mockRejectedValue(new Error('bitmap failed'))
+ : null;
+ try {
+ if (outcome === 'rejected-audio') {
+ await expect(extractFrameAndAudio(params)).rejects.toBe(failure);
+ } else if (outcome === 'bitmap-error') {
+ await expect(extractFrameAndAudio(params)).rejects.toThrow(
+ 'bitmap failed',
+ );
+ } else {
+ const result = await extractFrameAndAudio(params);
+ expect(result.type).toBe(
+ outcome === 'success' ? 'success' : 'cannot-decode',
+ );
+ if (result.type === 'success') result.frame?.close();
+ }
+
+ expect(() => frame.allocationSize()).toThrow();
+ } finally {
+ frame.close();
+ bitmap?.mockRestore();
+ }
+ });
+}
diff --git a/packages/media/src/video-extraction/rotate-frame.ts b/packages/media/src/video-extraction/rotate-frame.ts
index 25d7e3dbc6..40c04cd1a4 100644
--- a/packages/media/src/video-extraction/rotate-frame.ts
+++ b/packages/media/src/video-extraction/rotate-frame.ts
@@ -7,7 +7,6 @@ export const rotateFrame = async ({
}): Promise<ImageBitmap> => {
if (rotation === 0) {
const directBitmap = await createImageBitmap(frame);
- frame.close();
return directBitmap;
}
@@ -41,6 +40,5 @@ export const rotateFrame = async ({
ctx.drawImage(frame, 0, 0);
const bitmap = await createImageBitmap(canvas);
- frame.close();
return bitmap;
};