Skip to content

🎥 Make videos programmatically with React

fix(media): cancel owned effect paints during disposal

Alec Wattsf18e197ce785
diff --git a/packages/media/src/test/media-player.test.ts b/packages/media/src/test/media-player.test.ts
index 248151b8cf..ad43ab8649 100644
--- a/packages/media/src/test/media-player.test.ts
+++ b/packages/media/src/test/media-player.test.ts
@@ -1,4 +1,6 @@
import {AudioBufferSink, CanvasSink, InputVideoTrack} from 'mediabunny';
+import type {EffectDefinitionAndStack} from 'remotion';
+import {Internals} from 'remotion';
import {expect, test, vi} from 'vitest';
import {MediaPlayer} from '../media-player';
import type {SharedAudioContextForMediaPlayer} from '../shared-audio-context-for-media-player';
@@ -38,10 +40,18 @@ const makeAudioPlayer = (
sharedAudioContext: SharedAudioContextForMediaPlayer | null,
onError: ((error: Error) => void) | null = null,
tagType: 'audio' | 'video' = 'audio',
- options: Pick<
- ConstructorParameters<typeof MediaPlayer>[0],
- 'canvas' | 'onVideoFrameCallback' | 'src'
- > | null = null,
+ options:
+ | (Pick<
+ ConstructorParameters<typeof MediaPlayer>[0],
+ 'canvas' | 'onVideoFrameCallback' | 'src'
+ > &
+ Partial<
+ Pick<
+ ConstructorParameters<typeof MediaPlayer>[0],
+ 'getEffects' | 'getEffectChainState'
+ >
+ >)
+ | null = null,
) => {
return new MediaPlayer({
canvas: options?.canvas ?? null,
@@ -69,8 +79,8 @@ const makeAudioPlayer = (
credentials: undefined,
requestInit: undefined,
tagType,
- getEffects: () => [],
- getEffectChainState: () => null,
+ getEffects: options?.getEffects ?? (() => []),
+ getEffectChainState: options?.getEffectChainState ?? (() => null),
maxCanvasSinkFrameSize: null,
onError,
});
@@ -333,7 +343,7 @@ test('ignores pending seek failures after disposal and skips new seeks', async (
});
// A disposed initialization must not repaint a canvas reused by its replacement.
-test.each(['dimensions', 'first frame'] as const)(
+test.each(['dimensions', 'first frame', 'effect bridge'] as const)(
'disposing during %s initialization preserves the replacement picture',
async (boundary) => {
let release = () => {};
@@ -345,11 +355,41 @@ test.each(['dimensions', 'first frame'] as const)(
reached = resolve;
});
const canvas = document.createElement('canvas');
+ const chainState = Internals.createEffectChainState(1920, 1080);
+ const effects: EffectDefinitionAndStack<unknown>[] = (
+ ['webgl2', '2d'] as const
+ ).map((backend) => ({
+ memoized: true,
+ effectKey: backend,
+ params: {},
+ definition: {
+ type: backend,
+ label: backend,
+ documentationLink: null,
+ backend,
+ calculateKey: () => backend,
+ schema: {},
+ validateParams: () => {},
+ setup: () => null,
+ cleanup: () => {},
+ apply: ({target, source}) => {
+ if (backend === 'webgl2') {
+ const gl = target.getContext('webgl2')!;
+ gl.clearColor(0, 1, 0, 1);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ } else {
+ target.getContext('2d')!.drawImage(source, 0, 0);
+ }
+ },
+ },
+ }));
const onFrame = vi.fn();
const oldPlayer = makeAudioPlayer(null, null, 'video', {
canvas,
onVideoFrameCallback: onFrame,
src: '/bigbuckbunny.mp4',
+ getEffects: () => (boundary === 'effect bridge' ? effects : []),
+ getEffectChainState: () => chainState,
});
const replacement = makeAudioPlayer(null, null, 'video', {
canvas,
@@ -358,6 +398,7 @@ test.each(['dimensions', 'first frame'] as const)(
});
const originalWidth = InputVideoTrack.prototype.getDisplayWidth;
const originalCanvases = CanvasSink.prototype.canvases;
+ const originalBitmap = window.createImageBitmap.bind(window);
const spy =
boundary === 'dimensions'
? vi
@@ -368,20 +409,29 @@ test.each(['dimensions', 'first frame'] as const)(
await gate;
return width;
})
- : vi
- .spyOn(CanvasSink.prototype, 'canvases')
- .mockImplementationOnce(function (this: CanvasSink, ...args) {
- const iterator = originalCanvases.apply(this, args);
- const next = iterator.next.bind(iterator);
- iterator.next = async (...nextArgs) => {
- const frame = await next(...nextArgs);
+ : boundary === 'effect bridge'
+ ? vi
+ .spyOn(window, 'createImageBitmap')
+ .mockImplementationOnce(async (...args) => {
+ const bitmap = await originalBitmap(...args);
reached();
await gate;
- return frame;
- };
-
- return iterator;
- });
+ return bitmap;
+ })
+ : vi
+ .spyOn(CanvasSink.prototype, 'canvases')
+ .mockImplementationOnce(function (this: CanvasSink, ...args) {
+ const iterator = originalCanvases.apply(this, args);
+ const next = iterator.next.bind(iterator);
+ iterator.next = async (...nextArgs) => {
+ const frame = await next(...nextArgs);
+ reached();
+ await gate;
+ return frame;
+ };
+
+ return iterator;
+ });
const initialization = oldPlayer.initialize(1, true, 1);
let disposal: Promise<void> | null = null;
const picture = async () => {
@@ -413,6 +463,7 @@ test.each(['dimensions', 'first frame'] as const)(
spy.mockRestore();
await oldPlayer.dispose();
await replacement.dispose();
+ Internals.cleanupEffectChainState(chainState);
}
},
);
diff --git a/packages/media/src/video-iterator-manager.ts b/packages/media/src/video-iterator-manager.ts
index d3ea81423e..4b8507eb2f 100644
--- a/packages/media/src/video-iterator-manager.ts
+++ b/packages/media/src/video-iterator-manager.ts
@@ -84,6 +84,7 @@ export const videoIteratorManager = async ({
let lastDrawnFrame: WrappedCanvas | null = null;
let currentSeek: number | null = null;
let destroyed = false;
+ let pendingEffectRun: {state: EffectChainState; runId: number} | null = null;
const clearLastDrawnFrame = () => {
lastDrawnFrame = null;
@@ -127,6 +128,10 @@ export const videoIteratorManager = async ({
makePrewarmedVideoIteratorCache(canvasSink);
const paintFrame = async (frame: WrappedCanvas): Promise<void> => {
+ if (destroyed) {
+ return;
+ }
+
if (context && canvas) {
const effects = getEffects();
const chainState = getEffectChainState(canvas.width, canvas.height);
@@ -153,14 +158,22 @@ export const videoIteratorManager = async ({
source = upscaledFrame;
}
- await runEffectChain({
- state: chainState,
- source,
- effects,
- output: canvas,
- width: canvas.width,
- height: canvas.height,
- });
+ const run = {state: chainState, runId: chainState.currentRunId + 1};
+ pendingEffectRun = run;
+ try {
+ await runEffectChain({
+ state: chainState,
+ source,
+ effects,
+ output: canvas,
+ width: canvas.width,
+ height: canvas.height,
+ });
+ } finally {
+ if (pendingEffectRun === run) {
+ pendingEffectRun = null;
+ }
+ }
} else {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(frame.canvas, 0, 0, canvas.width, canvas.height);
@@ -170,6 +183,10 @@ export const videoIteratorManager = async ({
const drawFrame = async (frame: WrappedCanvas): Promise<void> => {
await paintFrame(frame);
+ if (destroyed) {
+ return;
+ }
+
lastDrawnFrame = frame;
framesRendered++;
@@ -192,6 +209,9 @@ export const videoIteratorManager = async ({
}
await paintFrame(lastDrawnFrame);
+ if (destroyed) {
+ return;
+ }
drawDebugOverlay();
const callback = getOnVideoFrameCallback();
@@ -355,6 +375,15 @@ export const videoIteratorManager = async ({
}
destroyed = true;
+ // Cancel only this manager's pending run, not a newer run sharing its state.
+ if (
+ pendingEffectRun &&
+ pendingEffectRun.state.currentRunId === pendingEffectRun.runId
+ ) {
+ pendingEffectRun.state.currentRunId++;
+ }
+
+ pendingEffectRun = null;
clearLastDrawnFrame();
prewarmedVideoIteratorCache.destroy();
videoFrameIterator?.destroy();