🎥 Make videos programmatically with React
`@remotion/web-renderer`: Reuse WebGL context for more performance
JonnyBurger8aaccad978bc
diff --git a/packages/web-renderer/src/drawing/handle-3d-transform.ts b/packages/web-renderer/src/drawing/handle-3d-transform.tsindex 59b9ad1a65..19a508cad8 100644--- a/packages/web-renderer/src/drawing/handle-3d-transform.ts+++ b/packages/web-renderer/src/drawing/handle-3d-transform.ts@@ -1,4 +1,5 @@import {getBiggestBoundingClientRect} from '../get-biggest-bounding-client-rect';+import type {InternalState} from '../internal-state';import {getNarrowerRect} from './clamp-rect-to-parent-bounds';import {getPreTransformRect} from './get-pretransform-rect';import {transformIn3d} from './transform-in-3d';@@ -32,26 +33,25 @@ export const handle3dTransform = ({precomposeRect,tempCanvas,rectAfterTransforms,+ internalState,}: {matrix: DOMMatrix;precomposeRect: DOMRect;tempCanvas: OffscreenCanvas;rectAfterTransforms: DOMRect;+ internalState: InternalState;}) => {- const {- canvas: transformed,- rect: transformedRect,- cleanup,- } = transformIn3d({+ const {canvas: transformed, rect: transformedRect} = transformIn3d({untransformedRect: precomposeRect,matrix,sourceCanvas: tempCanvas,rectAfterTransforms,+ internalState,});if (transformedRect.width <= 0 || transformedRect.height <= 0) {return null;}- return [transformed, cleanup] as const;+ return transformed;};diff --git a/packages/web-renderer/src/drawing/process-node.ts b/packages/web-renderer/src/drawing/process-node.tsindex 7620407eb1..0c8b9bed13 100644--- a/packages/web-renderer/src/drawing/process-node.ts+++ b/packages/web-renderer/src/drawing/process-node.ts@@ -106,7 +106,6 @@ export const processNode = async ({});let drawable: OffscreenCanvas | null = tempCanvas;- let cleanupWebGL: () => void = () => {};const rectAfterTransforms = roundToExpandRect(transformDOMRect({@@ -130,11 +129,10 @@ export const processNode = async ({precomposeRect,tempCanvas: drawable,rectAfterTransforms,+ internalState,});if (t) {- const [transformed, cleanup] = t;- drawable = transformed;- cleanupWebGL = cleanup;+ drawable = t;}}@@ -143,6 +141,10 @@ export const processNode = async ({context.setTransform(new DOMMatrix());context.drawImage(drawable,+ 0,+ drawable.height - rectAfterTransforms.height,+ rectAfterTransforms.width,+ rectAfterTransforms.height,rectAfterTransforms.left - parentRect.x,rectAfterTransforms.top - parentRect.y,rectAfterTransforms.width,@@ -165,7 +167,6 @@ export const processNode = async ({}reset();- cleanupWebGL();return {type: 'skip-children'};}diff --git a/packages/web-renderer/src/drawing/transform-in-3d.ts b/packages/web-renderer/src/drawing/transform-in-3d.tsindex 1238604b73..b15f067ff6 100644--- a/packages/web-renderer/src/drawing/transform-in-3d.ts+++ b/packages/web-renderer/src/drawing/transform-in-3d.ts@@ -1,3 +1,30 @@+import type {HelperCanvasState, InternalState} from '../internal-state';++// Vertex shader - now includes texture coordinates+const vsSource = `+ attribute vec2 aPosition;+ attribute vec2 aTexCoord;+ uniform mat4 uTransform;+ uniform mat4 uProjection;+ varying vec2 vTexCoord;++ void main() {+ gl_Position = uProjection * uTransform * vec4(aPosition, 0.0, 1.0);+ vTexCoord = aTexCoord;+ }+`;++// Fragment shader - samples from texture and unpremultiplies alpha+const fsSource = `+ precision mediump float;+ uniform sampler2D uTexture;+ varying vec2 vTexCoord;++ void main() {+ gl_FragColor = texture2D(uTexture, vTexCoord);+ }+`;+function compileShader(shaderGl: WebGLRenderingContext,source: string,@@ -23,49 +50,52 @@ function compileShader(const createHelperCanvas = ({canvasWidth,canvasHeight,+ helperCanvasState,}: {canvasWidth: number;canvasHeight: number;+ helperCanvasState: HelperCanvasState;}) => {+ if (helperCanvasState.current) {+ // Resize canvas if dimensions changed+ if (+ helperCanvasState.current.canvas.width !== canvasWidth ||+ helperCanvasState.current.canvas.height !== canvasHeight+ ) {+ helperCanvasState.current.canvas.width = canvasWidth;+ helperCanvasState.current.canvas.height = canvasHeight;+ }++ // Always reset viewport and clear when reusing+ helperCanvasState.current.gl.viewport(0, 0, canvasWidth, canvasHeight);+ helperCanvasState.current.gl.clearColor(0, 0, 0, 0);+ helperCanvasState.current.gl.clear(+ helperCanvasState.current.gl.COLOR_BUFFER_BIT,+ );++ return helperCanvasState.current;+ }+const canvas = new OffscreenCanvas(canvasWidth, canvasHeight);- const gl = canvas.getContext('webgl', {- premultipliedAlpha: true,- });++ const gl =+ canvas.getContext('webgl', {+ premultipliedAlpha: true,+ }) ?? undefined;if (!gl) {throw new Error('WebGL not supported');}- // Vertex shader - now includes texture coordinates- const vsSource = `- attribute vec2 aPosition;- attribute vec2 aTexCoord;- uniform mat4 uTransform;- uniform mat4 uProjection;- varying vec2 vTexCoord;-- void main() {- gl_Position = uProjection * uTransform * vec4(aPosition, 0.0, 1.0);- vTexCoord = aTexCoord;- }- `;-- // Fragment shader - samples from texture and unpremultiplies alpha- const fsSource = `- precision mediump float;- uniform sampler2D uTexture;- varying vec2 vTexCoord;-- void main() {- gl_FragColor = texture2D(uTexture, vTexCoord);- }- `;-- // Create program+ // Compile shaders and create program onceconst vertexShader = compileShader(gl, vsSource, gl.VERTEX_SHADER);const fragmentShader = compileShader(gl, fsSource, gl.FRAGMENT_SHADER);const program = gl.createProgram();+ if (!program) {+ throw new Error('Could not create program');+ }+gl.attachShader(program, vertexShader);gl.attachShader(program, fragmentShader);gl.linkProgram(program);@@ -74,17 +104,32 @@ const createHelperCanvas = ({throw new Error('Program link error: ' + gl.getProgramInfoLog(program));}- gl.useProgram(program);+ // Get attribute and uniform locations once+ const locations = {+ aPosition: gl.getAttribLocation(program, 'aPosition'),+ aTexCoord: gl.getAttribLocation(program, 'aTexCoord'),+ uTransform: gl.getUniformLocation(program, 'uTransform'),+ uProjection: gl.getUniformLocation(program, 'uProjection'),+ uTexture: gl.getUniformLocation(program, 'uTexture'),+ };- // Clear and draw- gl.clearColor(0, 0, 0, 0); // Transparent background- gl.clear(gl.COLOR_BUFFER_BIT);+ // Shaders can be deleted after linking+ gl.deleteShader(vertexShader);+ gl.deleteShader(fragmentShader);++ const cleanup = () => {+ gl.deleteShader(vertexShader);+ gl.deleteShader(fragmentShader);+ gl.deleteProgram(program);+ const loseContext = gl.getExtension('WEBGL_lose_context');+ if (loseContext) {+ loseContext.loseContext();+ }+ };- // Enable blending for transparency- gl.enable(gl.BLEND);- gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);+ helperCanvasState.current = {canvas, gl, program, locations, cleanup};- return {canvas, gl, program, vertexShader, fragmentShader};+ return helperCanvasState.current;};export const transformIn3d = ({@@ -92,61 +137,64 @@ export const transformIn3d = ({sourceCanvas,untransformedRect,rectAfterTransforms,+ internalState,}: {untransformedRect: DOMRect;matrix: DOMMatrix;sourceCanvas: OffscreenCanvas;rectAfterTransforms: DOMRect;+ internalState: InternalState;}) => {- const {canvas, gl, program} = createHelperCanvas({+ const {canvas, gl, program, locations} = createHelperCanvas({canvasWidth: rectAfterTransforms.width,canvasHeight: rectAfterTransforms.height,+ helperCanvasState: internalState.helperCanvasState,});+ // Use the cached program+ gl.useProgram(program);++ // Setup viewport and clear (already done in createHelperCanvas, but ensure it's set)+ gl.viewport(0, 0, rectAfterTransforms.width, rectAfterTransforms.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);++ // Enable blending+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);++ // Create vertex bufferconst vertexBuffer = gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);- // Create a quad (two triangles) with texture coordinates// prettier-ignoreconst vertices = new Float32Array([- // Position (x, y) + TexCoord (u, v)- // First:- untransformedRect.x, untransformedRect.y, 0, 0, // bottom-left- untransformedRect.x + untransformedRect.width, untransformedRect.y, 1, 0, // bottom-right- untransformedRect.x, untransformedRect.y + untransformedRect.height, 0, 1, // top-left- // Second:- untransformedRect.x, untransformedRect.y + untransformedRect.height, 0, 1, // top-left- untransformedRect.x + untransformedRect.width, untransformedRect.y, 1, 0, // bottom-right- untransformedRect.x + untransformedRect.width, untransformedRect.y + untransformedRect.height, 1, 1, // top-right+ untransformedRect.x, untransformedRect.y, 0, 0,+ untransformedRect.x + untransformedRect.width, untransformedRect.y, 1, 0,+ untransformedRect.x, untransformedRect.y + untransformedRect.height, 0, 1,+ untransformedRect.x, untransformedRect.y + untransformedRect.height, 0, 1,+ untransformedRect.x + untransformedRect.width, untransformedRect.y, 1, 0,+ untransformedRect.x + untransformedRect.width, untransformedRect.y + untransformedRect.height, 1, 1,]);gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);- const aPosition = gl.getAttribLocation(program, 'aPosition');- const aTexCoord = gl.getAttribLocation(program, 'aTexCoord');+ // Setup attributes using cached locations+ gl.enableVertexAttribArray(locations.aPosition);+ gl.vertexAttribPointer(locations.aPosition, 2, gl.FLOAT, false, 4 * 4, 0);- // Position attribute (2 floats, stride 4 floats, offset 0)- gl.enableVertexAttribArray(aPosition);- gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 4 * 4, 0);-- // Texture coordinate attribute (2 floats, stride 4 floats, offset 2)- gl.enableVertexAttribArray(aTexCoord);- gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, 4 * 4, 2 * 4);+ gl.enableVertexAttribArray(locations.aTexCoord);+ gl.vertexAttribPointer(locations.aTexCoord, 2, gl.FLOAT, false, 4 * 4, 2 * 4);// Create and configure textureconst texture = gl.createTexture();gl.bindTexture(gl.TEXTURE_2D, texture);-- // Set texture parametersgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);-gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);-- // Upload the source canvas as a texturegl.texImage2D(gl.TEXTURE_2D,0,@@ -156,69 +204,51 @@ export const transformIn3d = ({sourceCanvas,);- gl.enable(gl.BLEND);- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);-- // The transform matrix+ // Set uniforms using cached locationsconst transformMatrix = matrix.toFloat32Array();+ const zScale = 1_000_000_000;- const zScale = 1_000_000_000; // By default infinite in chrome-- // Create orthographic projection matrix for pixel coordinates with offset+ // Projection matrix accounts for the output canvas dimensionsconst projectionMatrix = new Float32Array([- 2 / canvas.width,+ 2 / rectAfterTransforms.width,0,0,0,0,- -2 / canvas.height,+ -2 / rectAfterTransforms.height,0,0,0,0,-2 / zScale,0,- -1 + (2 * -rectAfterTransforms.x) / canvas.width,- 1 - (2 * -rectAfterTransforms.y) / canvas.height,+ -1 + (2 * -rectAfterTransforms.x) / rectAfterTransforms.width,+ 1 - (2 * -rectAfterTransforms.y) / rectAfterTransforms.height,0,1,]);- const uTransform = gl.getUniformLocation(program, 'uTransform');- const uProjection = gl.getUniformLocation(program, 'uProjection');- const uTexture = gl.getUniformLocation(program, 'uTexture');-- gl.uniformMatrix4fv(uTransform, false, transformMatrix);- gl.uniformMatrix4fv(uProjection, false, projectionMatrix);- gl.uniform1i(uTexture, 0); // Use texture unit 0+ gl.uniformMatrix4fv(locations.uTransform, false, transformMatrix);+ gl.uniformMatrix4fv(locations.uProjection, false, projectionMatrix);+ gl.uniform1i(locations.uTexture, 0);+ // Drawgl.drawArrays(gl.TRIANGLES, 0, 6);- // Clean up resources to prevent leaks and ensure clean state for reuse- gl.disableVertexAttribArray(aPosition);- gl.disableVertexAttribArray(aTexCoord);-- // Clean up resources to prevent leaks and ensure clean state for reuse+ // Clean up per-frame resources only+ gl.disableVertexAttribArray(locations.aPosition);+ gl.disableVertexAttribArray(locations.aTexCoord);gl.deleteTexture(texture);gl.deleteBuffer(vertexBuffer);-gl.bindTexture(gl.TEXTURE_2D, null);- gl.deleteTexture(texture);+ gl.bindBuffer(gl.ARRAY_BUFFER, null);- // Reset pixel store state+ // Reset state+ gl.disable(gl.BLEND);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);- // Reset blend function to the initial state- gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);-return {canvas,rect: rectAfterTransforms,- cleanup: () => {- const loseContext = gl.getExtension('WEBGL_lose_context');- if (loseContext) {- loseContext.loseContext();- }- },};};diff --git a/packages/web-renderer/src/internal-state.ts b/packages/web-renderer/src/internal-state.tsindex 39f4b14c65..40731db272 100644--- a/packages/web-renderer/src/internal-state.ts+++ b/packages/web-renderer/src/internal-state.ts@@ -1,7 +1,29 @@+type HelperCanvas = {+ canvas: OffscreenCanvas;+ gl: WebGLRenderingContext;+ program: WebGLProgram; // Cache the program+ locations: {+ aPosition: number;+ aTexCoord: number;+ uTransform: WebGLUniformLocation | null;+ uProjection: WebGLUniformLocation | null;+ uTexture: WebGLUniformLocation | null;+ };+ cleanup: () => void;+};++export type HelperCanvasState = {+ current: HelperCanvas | null;+};+export const makeInternalState = () => {let drawnPrecomposedPixels = 0;let precomposedTextures = 0;+ const helperCanvasState: HelperCanvasState = {+ current: null,+ };+return {getDrawn3dPixels: () => drawnPrecomposedPixels,getPrecomposedTiles: () => precomposedTextures,@@ -15,6 +37,14 @@ export const makeInternalState = () => {drawnPrecomposedPixels += canvasWidth * canvasHeight;precomposedTextures++;},+ helperCanvasState,+ cleanup: () => {+ drawnPrecomposedPixels = 0;+ precomposedTextures = 0;+ if (helperCanvasState.current) {+ helperCanvasState.current.cleanup();+ }+ },};};diff --git a/packages/web-renderer/src/render-still-on-web.tsx b/packages/web-renderer/src/render-still-on-web.tsxindex 345a45f7ea..d5dcde382c 100644--- a/packages/web-renderer/src/render-still-on-web.tsx+++ b/packages/web-renderer/src/render-still-on-web.tsx@@ -165,6 +165,7 @@ async function internalRenderStillOnWeb<});throw err;} finally {+ internalState.cleanup();cleanupScaffold();}}diff --git a/packages/web-renderer/src/test/many-layers.test.tsx b/packages/web-renderer/src/test/many-layers.test.tsxindex d5a9afc16a..75b208d364 100644--- a/packages/web-renderer/src/test/many-layers.test.tsx+++ b/packages/web-renderer/src/test/many-layers.test.tsx@@ -1,4 +1,4 @@-import {test} from 'vitest';+import {expect, test} from 'vitest';import {page} from 'vitest/browser';import {renderStillOnWeb} from '../render-still-on-web';import {manyLayers} from './fixtures/many-layers';@@ -6,14 +6,17 @@ import {testImage} from './utils';test('should render many layers efficiently', async () => {page.viewport(1080, 1080);- const {blob} = await renderStillOnWeb({+ const {blob, internalState} = await renderStillOnWeb({licenseKey: 'free-license',composition: manyLayers,frame: 0,inputProps: {},imageFormat: 'png',- logLevel: 'trace',});await testImage({blob, testId: 'many layers'});+ expect(internalState.getDrawn3dPixels()).toBeGreaterThanOrEqual(2300113);+ expect(internalState.getDrawn3dPixels()).toBeLessThanOrEqual(2559467);+ expect(internalState.getPrecomposedTiles()).toBeGreaterThanOrEqual(21);+ expect(internalState.getPrecomposedTiles()).toBeLessThanOrEqual(23);});