Skip to content

🎥 Make videos programmatically with React

perf(core): allocate effect canvases on first use

Alec Watts99e3eab8bf0c
diff --git a/packages/core/src/effects/canvas-pool.ts b/packages/core/src/effects/canvas-pool.ts
index 7f925e051f..e76e625c3d 100644
--- a/packages/core/src/effects/canvas-pool.ts
+++ b/packages/core/src/effects/canvas-pool.ts
@@ -20,7 +20,11 @@ type CanvasPair = readonly [HTMLCanvasElement, HTMLCanvasElement];
export class CanvasPool {
private readonly width: number;
private readonly height: number;
- private readonly pairs: Map<Backend, CanvasPair> = new Map();
+ private readonly pairs: Map<
+ Backend,
+ [HTMLCanvasElement | null, HTMLCanvasElement | null]
+ > = new Map();
+
// Tracked individually rather than through `pairs` so that a canvas whose
// sibling failed to allocate still gets released.
private readonly allocated: Array<{
@@ -42,24 +46,29 @@ export class CanvasPool {
this.onContextLost = onContextLost;
}
- public getPair(backend: Backend): CanvasPair {
+ public getCanvas(backend: Backend, index: 0 | 1): HTMLCanvasElement {
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;
+ let pair = this.pairs.get(backend);
+ if (!pair) {
+ pair = [null, null];
+ this.pairs.set(backend, pair);
}
- const pair = [
- this.allocateCanvas(backend),
- this.allocateCanvas(backend),
- ] as const;
- this.pairs.set(backend, pair);
- return pair;
+ // A single effect needs one target. Allocate its ping-pong partner only
+ // when a later pass actually uses it.
+ pair[index] ??= this.allocateCanvas(backend);
+ return pair[index];
+ }
+
+ public getPair(backend: Backend): CanvasPair {
+ this.getCanvas(backend, 0);
+ this.getCanvas(backend, 1);
+ return this.pairs.get(backend) as CanvasPair;
}
public assertContextNotLost(canvas: HTMLCanvasElement): void {
diff --git a/packages/core/src/effects/run-effect-chain.ts b/packages/core/src/effects/run-effect-chain.ts
index 2ea367ead7..9970352b97 100644
--- a/packages/core/src/effects/run-effect-chain.ts
+++ b/packages/core/src/effects/run-effect-chain.ts
@@ -164,10 +164,10 @@ export const runEffectChain = async ({
for (let runIndex = 0; runIndex < runs.length; runIndex++) {
const run = runs[runIndex];
- const [a, b] = state.pool.getPair(run.backend);
- let dst = a;
+ let canvasIndex: 0 | 1 = 0;
for (const eff of run.effects) {
+ const dst = state.pool.getCanvas(run.backend, canvasIndex);
const def = eff.definition as EffectDefinition<unknown, unknown>;
if (run.backend === 'webgl2') {
// Checked before `setup()`: a lost context cannot compile shaders,
@@ -196,7 +196,7 @@ export const runEffectChain = async ({
}
currentImage = dst;
- dst = dst === a ? b : a;
+ canvasIndex = canvasIndex === 0 ? 1 : 0;
}
lastTarget = (currentImage as HTMLCanvasElement | null) ?? lastTarget;
diff --git a/packages/core/src/test/effect-internals.test.ts b/packages/core/src/test/effect-internals.test.ts
index 1e24da45d3..0ed07c8fa6 100644
--- a/packages/core/src/test/effect-internals.test.ts
+++ b/packages/core/src/test/effect-internals.test.ts
@@ -1,4 +1,5 @@
-import {expect, test} from 'bun:test';
+import {expect, mock, test} from 'bun:test';
+import {CanvasPool} from '../effects/canvas-pool.js';
import {groupByBackend} from '../effects/effect-internals.js';
import type {
Backend,
@@ -6,6 +7,11 @@ import type {
EffectDefinitionAndStack,
EffectDescriptor,
} from '../effects/effect-types.js';
+import {
+ cleanupEffectChainState,
+ createEffectChainState,
+ runEffectChain,
+} from '../effects/run-effect-chain.js';
const makeDef = (
type: string,
@@ -109,3 +115,124 @@ test('runEffectChain filters disabled effects before grouping', () => {
expect(runs[0].effects.map((e) => e.definition.type)).toEqual(['a']);
expect(runs[1].effects.map((e) => e.definition.type)).toEqual(['c']);
});
+
+test.each(['2d', 'webgl2'] as const)(
+ 'runEffectChain allocates only needed %s targets and releases them',
+ async (backend) => {
+ const source = document.createElement('canvas');
+ const output = document.createElement('canvas');
+ const contents = new WeakMap<object, string>([[source, 'raw']]);
+ const allocated: HTMLCanvasElement[] = [];
+ const loseContext = mock(() => undefined);
+ const original = Object.getOwnPropertyDescriptor(
+ HTMLCanvasElement.prototype,
+ 'getContext',
+ );
+ const getContext = mock(function (this: HTMLCanvasElement, kind: string) {
+ if (this !== output) allocated.push(this);
+ return (kind === 'webgl2'
+ ? {
+ UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241,
+ pixelStorei: () => undefined,
+ getExtension: () => ({loseContext}),
+ }
+ : {
+ clearRect: () => contents.delete(this),
+ drawImage: (image: object) =>
+ contents.set(this, contents.get(image)!),
+ }) as unknown as ReturnType<HTMLCanvasElement['getContext']>;
+ });
+ Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {
+ configurable: true,
+ value: getContext,
+ });
+ const state = createEffectChainState(4, 4);
+ const definition: EffectDefinition<unknown, unknown> = {
+ ...makeDef('append', backend),
+ apply: ({source: input, target, params}) => {
+ contents.set(target, contents.get(input as object)! + params);
+ },
+ };
+ const render = (texts: string[]) =>
+ runEffectChain({
+ state,
+ source,
+ output,
+ width: 4,
+ height: 4,
+ effects: texts.map((text) => ({
+ definition,
+ params: text,
+ effectKey: text,
+ memoized: true as const,
+ })),
+ });
+ try {
+ await render(['A']);
+ expect(contents.get(output)).toBe('rawA');
+ expect(allocated).toHaveLength(1);
+ await render(['A', 'B', 'C']);
+ expect(contents.get(output)).toBe('rawABC');
+ expect(allocated).toHaveLength(2);
+ await render(['D']);
+ expect(contents.get(output)).toBe('rawD');
+ expect(allocated).toHaveLength(2);
+ } finally {
+ cleanupEffectChainState(state);
+ if (original) {
+ Object.defineProperty(
+ HTMLCanvasElement.prototype,
+ 'getContext',
+ original,
+ );
+ } else {
+ Reflect.deleteProperty(HTMLCanvasElement.prototype, 'getContext');
+ }
+ }
+
+ for (const canvas of allocated) {
+ expect([canvas.width, canvas.height]).toEqual([0, 0]);
+ }
+
+ expect(loseContext).toHaveBeenCalledTimes(backend === 'webgl2' ? 2 : 0);
+ },
+);
+
+test('CanvasPool preserves getPair and releases a lone second slot', () => {
+ const original = Object.getOwnPropertyDescriptor(
+ HTMLCanvasElement.prototype,
+ 'getContext',
+ );
+ const getContext = mock(() => ({}));
+ Object.defineProperty(HTMLCanvasElement.prototype, 'getContext', {
+ configurable: true,
+ value: getContext,
+ });
+ const pool = new CanvasPool(4, 4, () => undefined);
+ const partial = new CanvasPool(4, 4, () => undefined);
+ try {
+ const second = pool.getCanvas('2d', 1);
+ expect(getContext).toHaveBeenCalledTimes(1);
+ const pair = pool.getPair('2d');
+ expect(pair[1]).toBe(second);
+ expect(pair[0]).toBe(pool.getCanvas('2d', 0));
+ expect(pool.getPair('2d')).toBe(pair);
+ expect(getContext).toHaveBeenCalledTimes(2);
+ const lone = partial.getCanvas('2d', 1);
+ partial.dispose();
+ expect([lone.width, lone.height]).toEqual([0, 0]);
+ expect(() => partial.getCanvas('2d', 0)).toThrow('cleaned up');
+ } finally {
+ pool.dispose();
+ partial.dispose();
+ if (original) {
+ Object.defineProperty(
+ HTMLCanvasElement.prototype,
+ 'getContext',
+ original,
+ );
+ } else {
+ Reflect.deleteProperty(HTMLCanvasElement.prototype, 'getContext');
+ }
+ }
+});