π₯ Make videos programmatically with React
`remotion`: Fix stacked WebGL effects (#7759)
Igor Samokhovets7878f0c8cbc2
diff --git a/bun.lock b/bun.lockindex 36435cdb69..d87d8598f7 100644--- a/bun.lock+++ b/bun.lock@@ -556,7 +556,9 @@"devDependencies": {"@remotion/eslint-config-internal": "workspace:*","@typescript/native-preview": "catalog:",+ "@vitest/browser-playwright": "catalog:","eslint": "catalog:",+ "vitest": "catalog:",},},"packages/elevenlabs": {diff --git a/package.json b/package.jsonindex 3dfef0112c..13e702caa5 100644--- a/package.json+++ b/package.json@@ -17,6 +17,7 @@"testwebcodecs": "turbo run testwebcodecs --no-update-notifier","testwebrenderer": "turbo run testwebrenderer --concurrency=1 --no-update-notifier","testlayoututils": "turbo run testlayoututils --concurrency=1 --no-update-notifier",+ "testeffectsvisual": "turbo run testeffectsvisual --concurrency=1 --no-update-notifier","testlambda": "turbo run testlambda --concurrency=1 --no-update-notifier","ci": "turbo run make test --concurrency=1 --no-update-notifier","watch": "turbo watch make --concurrency=2 --experimental-write-cache",diff --git a/packages/core/src/effects/effect-types.ts b/packages/core/src/effects/effect-types.tsindex 503c83d1b1..bc2ed3538f 100644--- a/packages/core/src/effects/effect-types.ts+++ b/packages/core/src/effects/effect-types.ts@@ -28,8 +28,8 @@ export type EffectApplyParams<P, S> = {readonly gpuDevice: AnyGpuDevice | null;/*** When `true`, WebGL `texImage2D` uploads use `UNPACK_FLIP_Y_WEBGL` so DOM-style- * 2D frame canvases match clip-space UVs. Set by `runEffectChain` β `false` for- * prior WebGL outputs and `ImageBitmap` bridges from WebGL.+ * canvas sources match clip-space UVs. Set by `runEffectChain` β `false` for+ * `ImageBitmap` bridges from WebGL, which are already oriented for upload.*/readonly flipSourceY: boolean;};diff --git a/packages/core/src/effects/run-effect-chain.ts b/packages/core/src/effects/run-effect-chain.tsindex 233d5f92e4..cdadf643a1 100644--- a/packages/core/src/effects/run-effect-chain.ts+++ b/packages/core/src/effects/run-effect-chain.ts@@ -8,7 +8,10 @@ import {getGpuDevice} from './gpu-device.js';export type EffectChainState = {pool: CanvasPool;- setupCache: WeakMap<EffectDefinition<unknown, unknown>, unknown>;+ setupCache: WeakMap<+ EffectDefinition<unknown, unknown>,+ WeakMap<HTMLCanvasElement, unknown>+ >;cleanupRegistry: Array<{definition: EffectDefinition<unknown, unknown>;state: unknown;@@ -39,12 +42,18 @@ const ensureSetup = <S>(target: HTMLCanvasElement,): S => {const widened = def as EffectDefinition<unknown, unknown>;- if (state.setupCache.has(widened)) {- return state.setupCache.get(widened) as S;+ let cacheForDefinition = state.setupCache.get(widened);+ if (!cacheForDefinition) {+ cacheForDefinition = new WeakMap<HTMLCanvasElement, unknown>();+ state.setupCache.set(widened, cacheForDefinition);+ }++ if (cacheForDefinition.has(target)) {+ return cacheForDefinition.get(target) as S;}const setupState = def.setup(target);- state.setupCache.set(widened, setupState);+ cacheForDefinition.set(target, setupState);state.cleanupRegistry.push({definition: widened, state: setupState});return setupState;};@@ -117,7 +126,9 @@ export const runEffectChain = async ({return false;}- // Raw component sources are 2D frame canvases (Gif, WrappedCanvas.canvas, β¦).+ // Canvas sources are DOM-oriented. Flip them when uploading into WebGL so+ // texture coordinates match clip-space output. `ImageBitmap` bridges below+ // opt out because they are already oriented for upload.let flipWebGLSourceY = true;for (let runIndex = 0; runIndex < runs.length; runIndex++) {@@ -141,7 +152,10 @@ export const runEffectChain = async ({});if (run.backend === 'webgl2') {- flipWebGLSourceY = false;+ // Same-backend ping-pong passes feed the previous WebGL canvas back+ // through `texImage2D()`. That source is still a DOM canvas, so the+ // next upload also needs to be flipped.+ flipWebGLSourceY = true;state.pool.assertContextNotLost(dst);}diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.tsindex a09476f5ac..dc31a77fda 100644--- a/packages/core/src/internals.ts+++ b/packages/core/src/internals.ts@@ -47,7 +47,11 @@ import {timeValueRef,} from './EditorProps.js';import {createEffect} from './effects/create-effect.js';-import {runEffectChain} from './effects/run-effect-chain.js';+import {+ cleanupEffectChainState,+ createEffectChainState,+ runEffectChain,+} from './effects/run-effect-chain.js';import {useEffectChainState} from './effects/use-effect-chain-state.js';import {getCodeValuesCtx,@@ -354,6 +358,8 @@ export const Internals = {getEffectiveVisualModeValue,CompositionRenderErrorContext,useEffectChainState,+ createEffectChainState,+ cleanupEffectChainState,runEffectChain,useMemoizedEffects,useMemoizedEffectDefinitions,diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex 673b708e45..ffbe121118 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -11,6 +11,8 @@"type": "module","scripts": {"test": "bun test src/test",+ "testvisual": "vitest src/visual-test/effects-visual.test.ts",+ "testeffectsvisual": "vitest src/visual-test/effects-visual.test.ts --browser --run","formatting": "oxfmt src --check","format": "oxfmt src","lint": "eslint src",@@ -241,7 +243,9 @@"homepage": "https://www.remotion.dev/docs/effects/api","devDependencies": {"@remotion/eslint-config-internal": "workspace:*",+ "@vitest/browser-playwright": "catalog:","eslint": "catalog:",+ "vitest": "catalog:","@typescript/native-preview": "catalog:"},"keywords": [diff --git a/packages/effects/src/visual-test/__screenshots__/effects-visual.test.ts/stacked-blur-blur-noise-chromium-darwin.png b/packages/effects/src/visual-test/__screenshots__/effects-visual.test.ts/stacked-blur-blur-noise-chromium-darwin.pngnew file mode 100644index 0000000000..b558dfd9f8Binary files /dev/null and b/packages/effects/src/visual-test/__screenshots__/effects-visual.test.ts/stacked-blur-blur-noise-chromium-darwin.png differdiff --git a/packages/effects/src/visual-test/effects-visual.test.ts b/packages/effects/src/visual-test/effects-visual.test.tsnew file mode 100644index 0000000000..97742cc10a--- /dev/null+++ b/packages/effects/src/visual-test/effects-visual.test.ts@@ -0,0 +1,23 @@+import {test} from 'vitest';+import {blur} from '../blur.js';+import {noise} from '../noise.js';+import {+ descriptorsToMemoizedEffects,+ renderEffectChainToBlob,+ testImage,+} from './visual-utils.js';++test('stacks repeated WebGL effects without blanking or flipping the image', async () => {+ const blob = await renderEffectChainToBlob({+ effects: descriptorsToMemoizedEffects([+ blur({radius: 12}),+ blur({radius: 12}),+ noise({amount: 0.08, seed: 1}),+ ]),+ });++ await testImage({+ blob,+ testId: 'stacked-blur-blur-noise',+ });+});diff --git a/packages/effects/src/visual-test/visual-utils.ts b/packages/effects/src/visual-test/visual-utils.tsnew file mode 100644index 0000000000..dbbb8d5e15--- /dev/null+++ b/packages/effects/src/visual-test/visual-utils.ts@@ -0,0 +1,136 @@+import {+ Internals,+ type EffectDefinitionAndStack,+ type EffectDescriptor,+} from 'remotion';+import {expect, onTestFinished} from 'vitest';+import {page} from 'vitest/browser';++export const testImage = async ({+ blob,+ testId,+ threshold = 0.15,+ allowedMismatchedPixelRatio = 0.001,+}: {+ blob: Blob;+ testId: string;+ threshold?: number;+ allowedMismatchedPixelRatio?: number;+}) => {+ const img = document.createElement('img');+ img.src = URL.createObjectURL(blob);+ img.dataset.testid = testId;+ document.body.appendChild(img);++ onTestFinished(() => {+ document.body.removeChild(img);+ URL.revokeObjectURL(img.src);+ });++ await new Promise<void>((resolve, reject) => {+ img.onload = () => resolve();+ img.onerror = () => reject(new Error('Image failed to load'));+ });++ await expect(page.getByTestId(testId)).toMatchScreenshot(testId, {+ comparatorOptions: {+ threshold,+ allowedMismatchedPixelRatio,+ },+ });+};++export const descriptorsToMemoizedEffects = (+ effects: EffectDescriptor<unknown>[],+): EffectDefinitionAndStack<unknown>[] => {+ return effects.map((effect) => ({+ ...effect,+ memoized: true,+ }));+};++const makeTestSource = (width: number, height: number): HTMLCanvasElement => {+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;++ const ctx = canvas.getContext('2d');+ if (!ctx) {+ throw new Error('Could not get 2D context');+ }++ ctx.fillStyle = '#f8f8f8';+ ctx.fillRect(0, 0, width, height);++ ctx.fillStyle = '#e31b23';+ ctx.fillRect(0, 0, width / 2, height / 2);+ ctx.fillStyle = '#0aa83f';+ ctx.fillRect(width / 2, 0, width / 2, height / 2);+ ctx.fillStyle = '#1d4ed8';+ ctx.fillRect(0, height / 2, width / 2, height / 2);+ ctx.fillStyle = '#facc15';+ ctx.fillRect(width / 2, height / 2, width / 2, height / 2);++ ctx.fillStyle = 'white';+ ctx.font = 'bold 38px sans-serif';+ ctx.textBaseline = 'top';+ ctx.fillText('TOP', 12, 10);+ ctx.fillStyle = 'black';+ ctx.textBaseline = 'bottom';+ ctx.fillText('BOTTOM', 12, height - 8);++ ctx.fillStyle = 'white';+ ctx.beginPath();+ ctx.moveTo(width - 30, 12);+ ctx.lineTo(width - 12, 46);+ ctx.lineTo(width - 48, 46);+ ctx.closePath();+ ctx.fill();++ return canvas;+};++export const renderEffectChainToBlob = async ({+ effects,+ width = 320,+ height = 180,+}: {+ effects: EffectDefinitionAndStack<unknown>[];+ width?: number;+ height?: number;+}): Promise<Blob> => {+ const source = makeTestSource(width, height);+ const output = document.createElement('canvas');+ output.width = width;+ output.height = height;++ const state = Internals.createEffectChainState(width, height);+ try {+ const completed = await Internals.runEffectChain({+ state,+ source,+ effects,+ output,+ width,+ height,+ });++ if (!completed) {+ throw new Error('Effect chain was cancelled');+ }+ } finally {+ Internals.cleanupEffectChainState(state);+ }++ const blob = await new Promise<Blob>((resolve, reject) => {+ output.toBlob((result) => {+ if (result) {+ resolve(result);+ } else {+ reject(new Error('Could not encode canvas as PNG'));+ }+ }, 'image/png');+ });++ return blob;+};diff --git a/packages/effects/vitest.config.ts b/packages/effects/vitest.config.tsnew file mode 100644index 0000000000..f0da0dd105--- /dev/null+++ b/packages/effects/vitest.config.ts@@ -0,0 +1,28 @@+import {playwright} from '@vitest/browser-playwright';+import {defineConfig} from 'vitest/config';++export default defineConfig({+ test: {+ browser: {+ enabled: true,+ provider: playwright(),+ instances: [+ {+ browser: 'chromium',+ provider: playwright({+ launchOptions: {+ channel: 'chrome',+ },+ actionTimeout: 5000,+ }),+ viewport: {width: 640, height: 480},+ } as const,+ ],+ headless: true,+ screenshotFailures: false,+ },+ },+ esbuild: {+ target: 'es2022',+ },+});diff --git a/turbo.json b/turbo.jsonindex 2cf544216c..a7eb340e9e 100644--- a/turbo.json+++ b/turbo.json@@ -33,6 +33,9 @@"testlayoututils": {"dependsOn": ["@remotion/layout-utils#make"]},+ "testeffectsvisual": {+ "dependsOn": ["@remotion/effects#make"]+ },"build": {"dependsOn": ["^make"],"outputs": ["dist"],