Skip to content

🎥 Make videos programmatically with React

`remotion`: Fix WebGL contexts of canvas effects not being released on unmount and size change

Jonny Burgerd38126da80c3
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsx
index 6b1546735c..44ef404284 100644
--- a/packages/core/src/HtmlInCanvas.tsx
+++ b/packages/core/src/HtmlInCanvas.tsx
@@ -585,14 +585,18 @@ const HtmlInCanvasContent = forwardRef<
});
}
- await runEffectChain({
- state: chainState.get(canvasWidth, canvasHeight)!,
- source: paintTarget,
- effects: effectsRef.current,
- output: paintTarget,
- width: canvasWidth,
- height: canvasHeight,
- });
+ // `null` once unmounted, e.g. when an async `onPaint` resolves late.
+ const state = chainState.get(canvasWidth, canvasHeight);
+ if (state) {
+ await runEffectChain({
+ state,
+ source: paintTarget,
+ effects: effectsRef.current,
+ output: paintTarget,
+ width: canvasWidth,
+ height: canvasHeight,
+ });
+ }
} finally {
elImage.close();
}
diff --git a/packages/core/src/effects/canvas-pool.ts b/packages/core/src/effects/canvas-pool.ts
index 42c9212fc7..7f925e051f 100644
--- a/packages/core/src/effects/canvas-pool.ts
+++ b/packages/core/src/effects/canvas-pool.ts
@@ -11,18 +11,44 @@ type CanvasPair = readonly [HTMLCanvasElement, HTMLCanvasElement];
// allocated, they are reused every frame for the chain's lifetime. Contexts
// are created with the cross-backend alpha/sRGB contract enforced (see
// `effect-types.ts`).
+//
+// Browsers keep only a limited number of WebGL contexts alive (16 in Chrome
+// and Safari) and force-lose the oldest one beyond that, while unreferenced
+// canvases are only collected lazily. `dispose()` therefore releases the
+// contexts and backing stores as soon as the chain is torn down instead of
+// leaving that to the garbage collector.
export class CanvasPool {
private readonly width: number;
private readonly height: number;
private readonly pairs: Map<Backend, CanvasPair> = new Map();
+ // Tracked individually rather than through `pairs` so that a canvas whose
+ // sibling failed to allocate still gets released.
+ private readonly allocated: Array<{
+ canvas: HTMLCanvasElement;
+ gl: WebGL2RenderingContext | null;
+ }> = [];
+
private readonly lostContexts: Set<HTMLCanvasElement> = new Set();
+ private readonly onContextLost: (canvas: HTMLCanvasElement) => void;
+ private disposed = false;
- public constructor(width: number, height: number) {
+ public constructor(
+ width: number,
+ height: number,
+ onContextLost: (canvas: HTMLCanvasElement) => void,
+ ) {
this.width = width;
this.height = height;
+ this.onContextLost = onContextLost;
}
public getPair(backend: Backend): CanvasPair {
+ if (this.disposed) {
+ throw new Error(
+ 'Effect chain state was used after it had been cleaned up',
+ );
+ }
+
const existing = this.pairs.get(backend);
if (existing) {
return existing;
@@ -46,6 +72,27 @@ export class CanvasPool {
}
}
+ // Makes the pool unusable and releases its resources right away.
+ public dispose(): void {
+ if (this.disposed) {
+ return;
+ }
+
+ this.disposed = true;
+ for (const {canvas, gl} of this.allocated) {
+ // Frees the slot in the browser's live-context budget immediately.
+ // Resizing to 0x0 drops the backing store even where the extension
+ // is unavailable.
+ gl?.getExtension('WEBGL_lose_context')?.loseContext();
+ canvas.width = 0;
+ canvas.height = 0;
+ }
+
+ this.allocated.length = 0;
+ this.pairs.clear();
+ this.lostContexts.clear();
+ }
+
private allocateCanvas(backend: Backend): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.width = this.width;
@@ -60,6 +107,7 @@ export class CanvasPool {
throw new Error('Failed to acquire 2D context for canvas effect');
}
+ this.allocated.push({canvas, gl: null});
return canvas;
}
@@ -74,14 +122,28 @@ export class CanvasPool {
}
canvas.addEventListener('webglcontextlost', (e) => {
+ // `dispose()` loses the context on purpose. Not preventing the
+ // default keeps the browser from restoring a context nobody uses.
+ if (this.disposed) {
+ return;
+ }
+
e.preventDefault();
this.lostContexts.add(canvas);
+ this.onContextLost(canvas);
});
canvas.addEventListener('webglcontextrestored', () => {
+ if (this.disposed) {
+ return;
+ }
+
+ // A restored context starts from the initial GL state.
+ ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
this.lostContexts.delete(canvas);
});
ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ this.allocated.push({canvas, gl: ctx});
return canvas;
}
@@ -92,6 +154,7 @@ export class CanvasPool {
);
}
+ this.allocated.push({canvas, gl: null});
return canvas;
}
diff --git a/packages/core/src/effects/run-effect-chain.ts b/packages/core/src/effects/run-effect-chain.ts
index cdadf643a1..2ea367ead7 100644
--- a/packages/core/src/effects/run-effect-chain.ts
+++ b/packages/core/src/effects/run-effect-chain.ts
@@ -15,6 +15,7 @@ export type EffectChainState = {
cleanupRegistry: Array<{
definition: EffectDefinition<unknown, unknown>;
state: unknown;
+ target: HTMLCanvasElement;
}>;
currentRunId: number;
};
@@ -22,17 +23,47 @@ export type EffectChainState = {
export const createEffectChainState = (
width: number,
height: number,
-): EffectChainState => ({
- pool: new CanvasPool(width, height),
- setupCache: new WeakMap(),
- cleanupRegistry: [],
- currentRunId: 0,
-});
+): EffectChainState => {
+ const state: EffectChainState = {
+ pool: new CanvasPool(width, height, (canvas) => {
+ // The GL objects these setups hold died with the context and stay
+ // invalid on a restored one, so the next run has to recreate them.
+ // While the context is lost, GL calls are no-ops, which makes this
+ // the moment to run the cleanups without side effects on the
+ // context's error state.
+ const dead = state.cleanupRegistry.filter(
+ (entry) => entry.target === canvas,
+ );
+ state.cleanupRegistry = state.cleanupRegistry.filter(
+ (entry) => entry.target !== canvas,
+ );
+ for (const entry of dead) {
+ state.setupCache.get(entry.definition)?.delete(canvas);
+ }
+
+ for (const entry of dead) {
+ entry.definition.cleanup(entry.state);
+ }
+ }),
+ setupCache: new WeakMap(),
+ cleanupRegistry: [],
+ currentRunId: 0,
+ };
+ return state;
+};
+
+// Cancels in-flight runs, releases per-effect resources and then the pool's
+// canvases and contexts. The state must not be used afterwards.
export const cleanupEffectChainState = (state: EffectChainState): void => {
state.currentRunId++;
- for (const entry of state.cleanupRegistry) {
- entry.definition.cleanup(entry.state);
+ try {
+ for (const entry of state.cleanupRegistry) {
+ entry.definition.cleanup(entry.state);
+ }
+ } finally {
+ state.cleanupRegistry.length = 0;
+ state.pool.dispose();
}
};
@@ -54,7 +85,7 @@ const ensureSetup = <S>(
const setupState = def.setup(target);
cacheForDefinition.set(target, setupState);
- state.cleanupRegistry.push({definition: widened, state: setupState});
+ state.cleanupRegistry.push({definition: widened, state: setupState, target});
return setupState;
};
@@ -138,6 +169,12 @@ export const runEffectChain = async ({
for (const eff of run.effects) {
const def = eff.definition as EffectDefinition<unknown, unknown>;
+ if (run.backend === 'webgl2') {
+ // Checked before `setup()`: a lost context cannot compile shaders,
+ // and this surfaces the dedicated error instead of an effect's own.
+ state.pool.assertContextNotLost(dst);
+ }
+
const setupState = ensureSetup(state, def, dst);
def.apply({
@@ -156,7 +193,6 @@ export const runEffectChain = async ({
// through `texImage2D()`. That source is still a DOM canvas, so the
// next upload also needs to be flipped.
flipWebGLSourceY = true;
- state.pool.assertContextNotLost(dst);
}
currentImage = dst;
diff --git a/packages/core/src/effects/use-effect-chain-state.ts b/packages/core/src/effects/use-effect-chain-state.ts
index aaa5fe1c38..22d7309bbb 100644
--- a/packages/core/src/effects/use-effect-chain-state.ts
+++ b/packages/core/src/effects/use-effect-chain-state.ts
@@ -10,11 +10,19 @@ export const useEffectChainState = (): {
} => {
const chainStateRef = useRef<EffectChainState | null>(null);
const sizeRef = useRef<{width: number; height: number} | null>(null);
+ const unmountedRef = useRef(false);
useEffect(() => {
+ // StrictMode and Fast Refresh run the cleanup below and then this effect
+ // again, after which `get()` must hand out a fresh state.
+ unmountedRef.current = false;
+
return () => {
+ unmountedRef.current = true;
if (chainStateRef.current) {
cleanupEffectChainState(chainStateRef.current);
+ chainStateRef.current = null;
+ sizeRef.current = null;
}
};
}, []);
@@ -22,6 +30,12 @@ export const useEffectChainState = (): {
return useMemo(
() => ({
get: (width, height) => {
+ // Async work such as a late decoded video frame can still get here
+ // after unmount. Nothing would release a pool created at this point.
+ if (unmountedRef.current) {
+ return null;
+ }
+
if (
!sizeRef.current ||
sizeRef.current.width !== width ||