🎥 Make videos programmatically with React
`remotion`: Add canvas effects runtime, `<Solid>`, and `<Experimental.HtmlInCanvas>`
JonnyBurger0f3a4ab707f7
diff --git a/packages/core/src/canvas-effects/HtmlInCanvas.tsx b/packages/core/src/canvas-effects/HtmlInCanvas.tsxnew file mode 100644index 0000000000..25fb799428--- /dev/null+++ b/packages/core/src/canvas-effects/HtmlInCanvas.tsx@@ -0,0 +1,174 @@+import React, {useCallback, useEffect, useRef, useState} from 'react';+import {cancelRender} from '../cancel-render.js';+import type {EffectsProp} from './effect-types.js';+import {useEffectChain} from './use-effect-chain.js';++// Type augmentation for the WICG html-in-canvas proposal:+// https://github.com/WICG/html-in-canvas+//+// Requires Chrome Canary with chrome://flags/#canvas-draw-element enabled, so+// that both drawElementImage() and canvas.requestPaint() are available.+//+// The current Chromium implementation requires the element passed to+// drawElementImage() to be an immediate child of the canvas, and the canvas+// must have its `layoutSubtree` property set to true so the children are+// actually laid out (instead of being treated as fallback content).+type Canvas2DWithDrawElement = CanvasRenderingContext2D & {+ drawElementImage: (+ element: Element,+ dx: number,+ dy: number,+ dwidth: number,+ dheight: number,+ ) => DOMMatrix;+};++type HTMLCanvasWithLayoutSubtree = HTMLCanvasElement & {+ layoutSubtree?: boolean;+ requestPaint: () => void;+};++const isHtmlInCanvasSupported = () => {+ if (typeof document === 'undefined') {+ return false;+ }++ const canvas = document.createElement(+ 'canvas',+ ) as HTMLCanvasWithLayoutSubtree;+ const ctx = canvas.getContext('2d') as Canvas2DWithDrawElement | null;+ return (+ typeof ctx?.drawElementImage === 'function' &&+ typeof canvas.requestPaint === 'function'+ );+};++export type HtmlInCanvasProps = {+ readonly width: number;+ readonly height: number;+ readonly effects?: EffectsProp;+ readonly children: React.ReactNode;+ readonly className?: string;+ readonly style?: React.CSSProperties;+ readonly pixelRatio?: number;+};++// `<HtmlInCanvas>` rasterizes its DOM children into a canvas using the WICG+// html-in-canvas proposal, then runs the resulting image through an+// effect chain. The captured DOM image is the source for the chain; effects+// then transform it just like with any other source component.+//+// Requires Chrome Canary with `chrome://flags/#canvas-draw-element` enabled.+export const HtmlInCanvas: React.FC<HtmlInCanvasProps> = ({+ width,+ height,+ effects = [],+ children,+ className,+ style,+ pixelRatio,+}) => {+ const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const sceneRef = useRef<HTMLDivElement | null>(null);+ const [outputCanvas, setOutputCanvas] = useState<HTMLCanvasElement | null>(+ null,+ );++ useEffect(() => {+ if (!isHtmlInCanvasSupported()) {+ cancelRender(+ new Error(+ 'HTML in Canvas is not supported. Open this page in Chrome Canary with chrome://flags/#canvas-draw-element enabled.',+ ),+ );+ return;+ }++ const sourceCanvas =+ sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ if (!sourceCanvas) {+ return;+ }++ sourceCanvas.layoutSubtree = true;+ }, []);++ const source = useCallback(() => {+ const sourceCanvas =+ sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ const sceneEl = sceneRef.current;+ if (!sourceCanvas || !sceneEl) {+ return null;+ }++ const ctx = sourceCanvas.getContext('2d') as Canvas2DWithDrawElement | null;+ if (!ctx) {+ throw new Error('Failed to acquire 2D context for <HtmlInCanvas> source');+ }++ return new Promise<CanvasImageSource>((resolve, reject) => {+ const onPaint = () => {+ sourceCanvas.removeEventListener('paint', onPaint);+ try {+ ctx.reset();+ ctx.drawElementImage(sceneEl, 0, 0, width, height);+ resolve(sourceCanvas);+ } catch (err) {+ reject(err instanceof Error ? err : new Error(String(err)));+ }+ };++ sourceCanvas.addEventListener('paint', onPaint);+ sourceCanvas.requestPaint();+ });+ }, [width, height]);++ useEffectChain({+ source,+ effects,+ width,+ height,+ pixelRatio,+ output: outputCanvas,+ sourceDeps: [],+ });++ return (+ <>+ <canvas+ ref={sourceCanvasRef}+ width={width}+ height={height}+ style={{+ position: 'absolute',+ inset: 0,+ width,+ height,+ }}+ >+ <div+ ref={sceneRef}+ style={{+ width,+ height,+ }}+ >+ {children}+ </div>+ </canvas>+ <canvas+ ref={setOutputCanvas}+ width={width}+ height={height}+ className={className}+ style={{+ position: 'absolute',+ inset: 0,+ width,+ height,+ ...style,+ }}+ />+ </>+ );+};diff --git a/packages/core/src/canvas-effects/Solid.tsx b/packages/core/src/canvas-effects/Solid.tsxnew file mode 100644index 0000000000..5c9ba55801--- /dev/null+++ b/packages/core/src/canvas-effects/Solid.tsx@@ -0,0 +1,81 @@+import React, {useCallback, useMemo, useState} from 'react';+import type {EffectsProp} from './effect-types.js';+import {useEffectChain} from './use-effect-chain.js';++export type SolidProps = {+ readonly color: string;+ readonly width: number;+ readonly height: number;+ readonly effects?: EffectsProp;+ readonly className?: string;+ readonly style?: React.CSSProperties;+ readonly pixelRatio?: number;+};++// `<Solid>` is the simplest source component: it produces a flat-color image+// to feed into the canvas-effect chain. Combined with an effect chain it can+// generate procedural content (gradients, blurs, noise patches, ...) without+// needing to mount a DOM source.+//+// Internally the source is a 1x1 canvas filled with `color`; the chain runtime+// scales it to the chain's `width`/`height` when the next stage samples it,+// which is correct because every pixel is the same color.+export const Solid: React.FC<SolidProps> = ({+ color,+ width,+ height,+ effects = [],+ className,+ style,+ pixelRatio,+}) => {+ const [outputCanvas, setOutputCanvas] = useState<HTMLCanvasElement | null>(+ null,+ );++ const sourceCanvas = useMemo(() => {+ if (typeof document === 'undefined') {+ return null;+ }++ const canvas = document.createElement('canvas');+ canvas.width = 1;+ canvas.height = 1;+ return canvas;+ }, []);++ const source = useCallback(() => {+ if (!sourceCanvas) {+ return null;+ }++ const ctx = sourceCanvas.getContext('2d', {colorSpace: 'srgb'});+ if (!ctx) {+ throw new Error('Failed to acquire 2D context for <Solid> source');+ }++ ctx.fillStyle = color;+ ctx.fillRect(0, 0, 1, 1);+ return sourceCanvas;+ }, [color, sourceCanvas]);++ useEffectChain({+ source,+ effects,+ width,+ height,+ pixelRatio,+ output: outputCanvas,+ sourceDeps: [color],+ });++ return (+ <canvas+ ref={setOutputCanvas}+ width={width}+ height={height}+ className={className}+ style={style}+ />+ );+};diff --git a/packages/core/src/canvas-effects/canvas-pool.ts b/packages/core/src/canvas-effects/canvas-pool.tsnew file mode 100644index 0000000000..e52c4587b0--- /dev/null+++ b/packages/core/src/canvas-effects/canvas-pool.ts@@ -0,0 +1,84 @@+import type {Backend} from './effect-types.js';++// A pair of scratch canvases for ping-ponging within a same-backend run.+type CanvasPair = readonly [HTMLCanvasElement, HTMLCanvasElement];++// Per-chain canvas pool. Each chain owns its own pool; pools are not shared+// across chains because dimensions are chain-specific.+//+// Canvases are allocated lazily on first use of a given backend. Once+// 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`).+export class CanvasPool {+ private readonly width: number;+ private readonly height: number;+ private readonly pairs: Map<Backend, CanvasPair> = new Map();++ public constructor(width: number, height: number) {+ this.width = width;+ this.height = height;+ }++ public getPair(backend: Backend): CanvasPair {+ const existing = this.pairs.get(backend);+ if (existing) {+ return existing;+ }++ const pair = [+ this.allocateCanvas(backend),+ this.allocateCanvas(backend),+ ] as const;+ this.pairs.set(backend, pair);+ return pair;+ }++ private allocateCanvas(backend: Backend): HTMLCanvasElement {+ const canvas = document.createElement('canvas');+ canvas.width = this.width;+ canvas.height = this.height;++ switch (backend) {+ case '2d': {+ const ctx = canvas.getContext('2d', {+ colorSpace: 'srgb',+ });+ if (!ctx) {+ throw new Error('Failed to acquire 2D context for canvas effect');+ }++ return canvas;+ }++ case 'webgl2': {+ const ctx = canvas.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!ctx) {+ throw new Error('Failed to acquire WebGL2 context for canvas effect');+ }++ ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);+ return canvas;+ }++ case 'webgpu': {+ if (typeof navigator === 'undefined' || !('gpu' in navigator)) {+ throw new Error(+ 'WebGPU is not available in this environment for canvas effect',+ );+ }++ return canvas;+ }++ default: {+ const exhaustive: never = backend;+ throw new Error(`Unknown effect backend: ${exhaustive as string}`);+ }+ }+ }+}diff --git a/packages/core/src/canvas-effects/define-effect.ts b/packages/core/src/canvas-effects/define-effect.tsnew file mode 100644index 0000000000..73fd31f1ba--- /dev/null+++ b/packages/core/src/canvas-effects/define-effect.ts@@ -0,0 +1,24 @@+import type {EffectDefinition, EffectDescriptor} from './effect-types.js';++// Identity helper for declaring an effect definition with proper type+// inference. Wrapping the literal in `defineEffect(...)` lets TypeScript infer+// `<P, S>` from the `setup` and `apply` signatures while still enforcing the+// shape of the definition.+export const defineEffect = <P, S>(+ definition: EffectDefinition<P, S>,+): EffectDefinition<P, S> => definition;++// Factory helper for constructing per-frame descriptors from a definition.+// Effect authors typically expose a small wrapper (e.g.+// `export const blur = (params) => createDescriptor(blurDef, params)`) so users+// don't reach into the internal definition object. The state type `S` is+// erased to `unknown` in the descriptor because consumers (the chain runtime,+// other effects in the chain) treat state as opaque; only the definition's+// own `setup`, `apply`, and `cleanup` functions ever see the real shape.+export const createDescriptor = <P, S>(+ definition: EffectDefinition<P, S>,+ params: P,+): EffectDescriptor<P> => ({+ definition: definition as unknown as EffectDefinition<P, unknown>,+ params,+});diff --git a/packages/core/src/canvas-effects/effect-internals.ts b/packages/core/src/canvas-effects/effect-internals.tsnew file mode 100644index 0000000000..b599735bfc--- /dev/null+++ b/packages/core/src/canvas-effects/effect-internals.ts@@ -0,0 +1,51 @@+import type {Backend, EffectDescriptor, EffectsProp} from './effect-types.js';++// Internal helpers for the chain runtime. Exported separately so they can be+// unit-tested without spinning up the React lifecycle / canvas mocking.++export const flattenEffects = (+ effects: EffectsProp,+): EffectDescriptor<unknown>[] => {+ const out: EffectDescriptor<unknown>[] = [];+ for (const item of effects) {+ if (Array.isArray(item)) {+ for (const inner of item) {+ out.push(inner);+ }+ } else {+ out.push(item as EffectDescriptor<unknown>);+ }+ }++ return out;+};++export type Run = {+ readonly backend: Backend;+ readonly effects: ReadonlyArray<EffectDescriptor<unknown>>;+};++export const groupByBackend = (+ effects: ReadonlyArray<EffectDescriptor<unknown>>,+): Run[] => {+ const runs: Run[] = [];+ let current: EffectDescriptor<unknown>[] = [];+ let currentBackend: Backend | null = null;+ for (const eff of effects) {+ const {backend} = eff.definition;+ if (currentBackend === null || backend === currentBackend) {+ current.push(eff);+ currentBackend = backend;+ } else {+ runs.push({backend: currentBackend, effects: current});+ current = [eff];+ currentBackend = backend;+ }+ }++ if (currentBackend !== null && current.length > 0) {+ runs.push({backend: currentBackend, effects: current});+ }++ return runs;+};diff --git a/packages/core/src/canvas-effects/effect-types.ts b/packages/core/src/canvas-effects/effect-types.tsnew file mode 100644index 0000000000..5663c693d3--- /dev/null+++ b/packages/core/src/canvas-effects/effect-types.ts@@ -0,0 +1,60 @@+// Public types for the canvas-effects system.+//+// An effect is a description of how to transform an input image into an output+// image, executed inside a per-frame chain runtime owned by a source component+// (`<Solid>`, `<HtmlInCanvas>`, ...). The chain runtime owns scratch canvases+// and ping-pongs between them, so effects do not allocate per frame.+//+// Cross-backend contract: all canvases store premultiplied alpha and are+// sRGB-encoded. Effects that perform color math in linear space are responsible+// for converting to/from sRGB themselves.++export type Backend = '2d' | 'webgl2' | 'webgpu';++// `GPUDevice` is left as `unknown` to avoid pulling `@webgpu/types` into core.+// Effects that target the `webgpu` backend should narrow this themselves+// (e.g. via a local type assertion or by depending on `@webgpu/types`).+type AnyGpuDevice = unknown;++export type EffectApplyParams<P, S> = {+ readonly source: CanvasImageSource;+ readonly target: HTMLCanvasElement;+ readonly state: S;+ readonly params: P;+ readonly frame: number;+ readonly width: number;+ readonly height: number;+ readonly pixelRatio: number;+ readonly gpuDevice: AnyGpuDevice | null;+};++export type EffectDefinition<P, S = unknown> = {+ readonly type: string;+ readonly backend: Backend;+ readonly setup: (target: HTMLCanvasElement) => S | Promise<S>;+ readonly apply: (params: EffectApplyParams<P, S>) => void | Promise<void>;+ readonly cleanup?: (state: S) => void;+};++export type EffectDescriptor<P = unknown> = {+ readonly definition: EffectDefinition<P, unknown>;+ readonly params: P;+};++// Public prop type for `effects`: callers may interleave single descriptors+// with arrays of descriptors. The runtime calls `.flat()` once before+// processing, which lets a single factory call (e.g. `blur(...)`) expand into+// multiple passes (e.g. horizontal + vertical) without leaking that detail to+// the call site.+//+// The element type uses `EffectDescriptor<any>` instead of+// `EffectDescriptor<unknown>` because TypeScript treats the `params` field of+// `EffectApplyParams` contravariantly (it is the parameter of `apply`), which+// would otherwise prevent a concrete `EffectDescriptor<MyParams>` from being+// assigned into a slot typed as `EffectDescriptor<unknown>`. The chain+// runtime handles params opaquely, so the variance loss is benign here.+/* eslint-disable @typescript-eslint/no-explicit-any */+export type EffectsProp = ReadonlyArray<+ EffectDescriptor<any> | ReadonlyArray<EffectDescriptor<any>>+>;+/* eslint-enable @typescript-eslint/no-explicit-any */diff --git a/packages/core/src/canvas-effects/gpu-device.ts b/packages/core/src/canvas-effects/gpu-device.tsnew file mode 100644index 0000000000..70451f5175--- /dev/null+++ b/packages/core/src/canvas-effects/gpu-device.ts@@ -0,0 +1,42 @@+// Singleton accessor for the WebGPU device.+//+// `navigator.gpu.requestAdapter()` and `adapter.requestDevice()` are async and+// non-trivially expensive (~10-100ms on first call). The device is cached+// globally so every webgpu effect / chain shares the same one.+//+// `GPUDevice` is intentionally typed as `unknown` here to avoid pulling+// `@webgpu/types` into core; effects targeting webgpu narrow the type+// themselves.++let devicePromise: Promise<unknown> | null = null;++export const getGpuDevice = (): Promise<unknown> => {+ if (devicePromise) {+ return devicePromise;+ }++ devicePromise = (async () => {+ if (typeof navigator === 'undefined' || !('gpu' in navigator)) {+ throw new Error('WebGPU is not available in this environment');+ }++ const {gpu} = navigator as unknown as {+ gpu: {requestAdapter: () => Promise<unknown>};+ };+ const adapter = (await gpu.requestAdapter()) as {+ requestDevice: () => Promise<unknown>;+ } | null;+ if (!adapter) {+ throw new Error('No WebGPU adapter available');+ }++ return adapter.requestDevice();+ })();++ return devicePromise;+};++// Test-only: reset the cached device. Not exported from `remotion`.+export const _resetGpuDeviceForTesting = (): void => {+ devicePromise = null;+};diff --git a/packages/core/src/canvas-effects/index.ts b/packages/core/src/canvas-effects/index.tsnew file mode 100644index 0000000000..28d51bae8b--- /dev/null+++ b/packages/core/src/canvas-effects/index.ts@@ -0,0 +1,12 @@+export {createDescriptor, defineEffect} from './define-effect.js';+export type {+ Backend,+ EffectApplyParams,+ EffectDefinition,+ EffectDescriptor,+ EffectsProp,+} from './effect-types.js';+export {HtmlInCanvas} from './HtmlInCanvas.js';+export type {HtmlInCanvasProps} from './HtmlInCanvas.js';+export {Solid} from './Solid.js';+export type {SolidProps} from './Solid.js';diff --git a/packages/core/src/canvas-effects/use-effect-chain.ts b/packages/core/src/canvas-effects/use-effect-chain.tsnew file mode 100644index 0000000000..3c90ec789e--- /dev/null+++ b/packages/core/src/canvas-effects/use-effect-chain.ts@@ -0,0 +1,266 @@+import {useEffect, useMemo, useRef} from 'react';+import {useCurrentFrame} from '../use-current-frame.js';+import {useDelayRender} from '../use-delay-render.js';+import {CanvasPool} from './canvas-pool.js';+import {flattenEffects, groupByBackend} from './effect-internals.js';+import type {EffectDefinition, EffectsProp} from './effect-types.js';+import {getGpuDevice} from './gpu-device.js';++type SourceFn = () =>+ | CanvasImageSource+ | Promise<CanvasImageSource>+ | null+ | undefined;++export type UseEffectChainOptions = {+ readonly source: SourceFn;+ readonly effects: EffectsProp;+ readonly width: number;+ readonly height: number;+ readonly pixelRatio?: number;+ readonly output: HTMLCanvasElement | null;+ // Stable React-deps to re-trigger the effect when callers change anything+ // that should invalidate the source (e.g. children, color, ...).+ readonly sourceDeps: ReadonlyArray<unknown>;+};++// Per-chain runtime state. Owned by the hook; recreated when width/height+// change (since the canvas pool is sized at construction).+type ChainState = {+ pool: CanvasPool;+ setupCache: WeakMap<EffectDefinition<unknown, unknown>, Promise<unknown>>;+ cleanupRegistry: Array<{+ definition: EffectDefinition<unknown, unknown>;+ statePromise: Promise<unknown>;+ }>;+};++const ensureSetup = (+ state: ChainState,+ def: EffectDefinition<unknown, unknown>,+ target: HTMLCanvasElement,+): Promise<unknown> => {+ const cached = state.setupCache.get(def);+ if (cached) {+ return cached;+ }++ const promise = Promise.resolve(def.setup(target));+ state.setupCache.set(def, promise);+ state.cleanupRegistry.push({definition: def, statePromise: promise});+ return promise;+};++// `useEffectChain` is the shared per-frame runtime that powers source+// components like `<Solid>` and `<HtmlInCanvas>`. Source components are+// responsible for producing a `CanvasImageSource` via the `source` callback;+// the runtime owns the rest of the pipeline (scratch canvases, ping-pong,+// cross-backend transfer via `createImageBitmap`, single `delayRender` per+// frame).+export const useEffectChain = ({+ source,+ effects,+ width,+ height,+ pixelRatio = 1,+ output,+ sourceDeps,+}: UseEffectChainOptions): void => {+ const frame = useCurrentFrame();+ const {delayRender, continueRender, cancelRender} = useDelayRender();++ const stateRef = useRef<ChainState | null>(null);+ const sizeRef = useRef<{width: number; height: number} | null>(null);++ // Reset pool if dimensions changed.+ if (+ !sizeRef.current ||+ sizeRef.current.width !== width ||+ sizeRef.current.height !== height+ ) {+ stateRef.current = {+ pool: new CanvasPool(width, height),+ setupCache: new WeakMap(),+ cleanupRegistry: [],+ };+ sizeRef.current = {width, height};+ }++ const flattened = useMemo(() => flattenEffects(effects), [effects]);+ const runs = useMemo(() => groupByBackend(flattened), [flattened]);++ useEffect(() => {+ const state = stateRef.current;+ if (!state || !output) {+ return;+ }++ const handle = delayRender(`Canvas effect chain (frame ${frame})`);+ let cancelled = false;+ let resolved = false;++ const finish = () => {+ if (resolved) {+ return;+ }++ resolved = true;+ continueRender(handle);+ };++ const fail = (err: unknown) => {+ if (resolved) {+ return;+ }++ resolved = true;+ cancelRender(err);+ };++ (async () => {+ try {+ const sourceImage = await source();+ if (cancelled) {+ return;+ }++ if (!sourceImage) {+ finish();+ return;+ }++ let currentImage: CanvasImageSource = sourceImage;+ let lastTarget: HTMLCanvasElement | null = null;++ if (runs.length === 0) {+ // No effects: blit source directly into output.+ const ctx = output.getContext('2d');+ if (!ctx) {+ throw new Error('Failed to acquire 2D context for output canvas');+ }++ ctx.clearRect(0, 0, width, height);+ ctx.drawImage(currentImage, 0, 0, width, height);+ finish();+ return;+ }++ let needsGpuDevice = false;+ for (const run of runs) {+ if (run.backend === 'webgpu') {+ needsGpuDevice = true;+ break;+ }+ }++ const gpuDevice = needsGpuDevice ? await getGpuDevice() : null;+ if (cancelled) {+ return;+ }++ for (let runIndex = 0; runIndex < runs.length; runIndex++) {+ const run = runs[runIndex];+ const [a, b] = state.pool.getPair(run.backend);+ let dst = a;++ for (const eff of run.effects) {+ const def = eff.definition as EffectDefinition<unknown, unknown>;+ const setupState = await ensureSetup(state, def, dst);+ if (cancelled) {+ return;+ }++ await def.apply({+ source: currentImage,+ target: dst,+ state: setupState,+ params: eff.params,+ frame,+ width,+ height,+ pixelRatio,+ gpuDevice,+ });+ if (cancelled) {+ return;+ }++ currentImage = dst;+ dst = dst === a ? b : a;+ }++ lastTarget = (currentImage as HTMLCanvasElement | null) ?? lastTarget;++ // If another run follows with a different backend, transfer via+ // `createImageBitmap` so the next backend can sample from a+ // neutral GPU-resident handle.+ const nextRun = runs[runIndex + 1];+ if (nextRun && nextRun.backend !== run.backend && lastTarget) {+ const bitmap = await createImageBitmap(lastTarget);+ if (cancelled) {+ bitmap.close?.();+ return;+ }++ currentImage = bitmap;+ }+ }++ if (!lastTarget) {+ finish();+ return;+ }++ const outCtx = output.getContext('2d');+ if (!outCtx) {+ throw new Error('Failed to acquire 2D context for output canvas');+ }++ outCtx.clearRect(0, 0, width, height);+ outCtx.drawImage(lastTarget, 0, 0, width, height);+ finish();+ } catch (err) {+ if (!cancelled) {+ fail(err);+ }+ }+ })();++ return () => {+ cancelled = true;+ if (!resolved) {+ continueRender(handle);+ }+ };+ /* eslint-disable react-hooks/exhaustive-deps */+ }, [+ frame,+ width,+ height,+ pixelRatio,+ output,+ runs,+ delayRender,+ continueRender,+ cancelRender,+ ...sourceDeps,+ ]);+ /* eslint-enable react-hooks/exhaustive-deps */++ // Cleanup on unmount: invoke `cleanup` for every cached state.+ useEffect(() => {+ return () => {+ const state = stateRef.current;+ if (!state) {+ return;+ }++ for (const entry of state.cleanupRegistry) {+ entry.statePromise.then(+ (s) => entry.definition.cleanup?.(s),+ () => undefined,+ );+ }+ };+ }, []);+};diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex eeb9ce3cd4..0107fa997f 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -130,6 +130,19 @@ export type BundleState =checkMultipleRemotionVersions();export * from './AbsoluteFill.js';export * from './animated-image/index.js';+export {+ Backend,+ createDescriptor,+ defineEffect,+ EffectApplyParams,+ EffectDefinition,+ EffectDescriptor,+ EffectsProp,+ Solid,+ SolidProps,+} from './canvas-effects/index.js';+import {HtmlInCanvas} from './canvas-effects/index.js';+export type {HtmlInCanvasProps} from './canvas-effects/index.js';export type {AnyZodObject} from './any-zod-type.js';export {Artifact} from './Artifact.js';export {Audio, Html5Audio, RemotionAudioProps} from './audio/index.js';@@ -221,6 +234,11 @@ export const Experimental = {* @see [Documentation](https://www.remotion.dev/docs/null)*/Null,+ /**+ * @description Rasterizes its DOM children into a canvas using the WICG html-in-canvas proposal, then runs the result through a canvas-effect chain. Requires Chrome Canary with chrome://flags/#canvas-draw-element enabled.+ * @see [Documentation](https://www.remotion.dev/docs/canvas-effects/html-in-canvas)+ */+ HtmlInCanvas,useIsPlayer,};diff --git a/packages/core/src/test/effect-internals.test.ts b/packages/core/src/test/effect-internals.test.tsnew file mode 100644index 0000000000..66aaacee46--- /dev/null+++ b/packages/core/src/test/effect-internals.test.ts@@ -0,0 +1,100 @@+import {expect, test} from 'bun:test';+import {+ flattenEffects,+ groupByBackend,+} from '../canvas-effects/effect-internals.js';+import type {+ Backend,+ EffectDefinition,+ EffectDescriptor,+} from '../canvas-effects/effect-types.js';++const makeDef = (+ type: string,+ backend: Backend,+): EffectDefinition<unknown, unknown> => ({+ type,+ backend,+ setup: () => null,+ apply: () => undefined,+});++const makeDesc = (+ type: string,+ backend: Backend,+): EffectDescriptor<unknown> => ({+ definition: makeDef(type, backend),+ params: {},+});++test('flattenEffects unwraps nested-array descriptors', () => {+ const a = makeDesc('a', '2d');+ const b1 = makeDesc('b1', '2d');+ const b2 = makeDesc('b2', '2d');+ const c = makeDesc('c', 'webgl2');++ const result = flattenEffects([a, [b1, b2], c]);+ expect(result.map((d) => d.definition.type)).toEqual(['a', 'b1', 'b2', 'c']);+});++test('flattenEffects handles empty input', () => {+ expect(flattenEffects([])).toEqual([]);+});++test('flattenEffects handles only-nested input', () => {+ const a = makeDesc('a', '2d');+ const b = makeDesc('b', '2d');+ expect(flattenEffects([[a, b]]).map((d) => d.definition.type)).toEqual([+ 'a',+ 'b',+ ]);+});++test('groupByBackend collapses adjacent same-backend effects', () => {+ const effects = [+ makeDesc('a', '2d'),+ makeDesc('b', '2d'),+ makeDesc('c', 'webgl2'),+ makeDesc('d', 'webgl2'),+ makeDesc('e', '2d'),+ ];++ const runs = groupByBackend(effects);+ expect(runs).toHaveLength(3);+ expect(runs[0].backend).toBe('2d');+ expect(runs[0].effects.map((e) => e.definition.type)).toEqual(['a', 'b']);+ expect(runs[1].backend).toBe('webgl2');+ expect(runs[1].effects.map((e) => e.definition.type)).toEqual(['c', 'd']);+ expect(runs[2].backend).toBe('2d');+ expect(runs[2].effects.map((e) => e.definition.type)).toEqual(['e']);+});++test('groupByBackend returns single run for uniform backend', () => {+ const effects = [+ makeDesc('a', '2d'),+ makeDesc('b', '2d'),+ makeDesc('c', '2d'),+ ];++ const runs = groupByBackend(effects);+ expect(runs).toHaveLength(1);+ expect(runs[0].backend).toBe('2d');+ expect(runs[0].effects).toHaveLength(3);+});++test('groupByBackend returns empty for empty input', () => {+ expect(groupByBackend([])).toEqual([]);+});++test('groupByBackend returns one run per backend transition', () => {+ const effects = [+ makeDesc('a', '2d'),+ makeDesc('b', 'webgl2'),+ makeDesc('c', '2d'),+ makeDesc('d', 'webgl2'),+ ];++ const runs = groupByBackend(effects);+ expect(runs).toHaveLength(4);+ expect(runs.map((r) => r.backend)).toEqual(['2d', 'webgl2', '2d', 'webgl2']);+});diff --git a/packages/core/src/test/solid.test.tsx b/packages/core/src/test/solid.test.tsxnew file mode 100644index 0000000000..22ddc9732e--- /dev/null+++ b/packages/core/src/test/solid.test.tsx@@ -0,0 +1,80 @@+import {afterEach, expect, test} from 'bun:test';+import {cleanup, render} from '@testing-library/react';+import {Solid} from '../canvas-effects/Solid.js';+import {WrapSequenceContext} from './wrap-sequence-context.js';++// happy-dom doesn't implement canvas; install a no-op stub so the chain+// runtime can execute without throwing on `getContext('2d')`.+const stub2dContext = () => ({+ canvas: null as unknown as HTMLCanvasElement,+ fillStyle: '',+ fillRect: () => undefined,+ clearRect: () => undefined,+ drawImage: () => undefined,+ reset: () => undefined,+ getImageData: () => ({+ data: new Uint8ClampedArray(4),+ width: 1,+ height: 1,+ }),+ putImageData: () => undefined,+});++(+ HTMLCanvasElement.prototype as unknown as {+ getContext: (kind: string) => unknown;+ }+).getContext = function (kind: string) {+ if (kind === '2d') {+ const ctx = stub2dContext();+ ctx.canvas = this as HTMLCanvasElement;+ return ctx;+ }++ return null;+};++afterEach(() => {+ cleanup();+});++test('<Solid> renders a canvas element with the given dimensions', () => {+ const {container} = render(+ <WrapSequenceContext>+ <Solid color="red" width={120} height={80} />+ </WrapSequenceContext>,+ );++ const canvas = container.querySelector('canvas');+ expect(canvas).not.toBeNull();+ expect(canvas?.getAttribute('width')).toBe('120');+ expect(canvas?.getAttribute('height')).toBe('80');+});++test('<Solid> forwards className and style', () => {+ const {container} = render(+ <WrapSequenceContext>+ <Solid+ color="blue"+ width={100}+ height={100}+ className="my-solid"+ style={{opacity: 0.5}}+ />+ </WrapSequenceContext>,+ );++ const canvas = container.querySelector('canvas');+ expect(canvas?.className).toBe('my-solid');+ expect(canvas?.style.opacity).toBe('0.5');+});++test('<Solid> accepts an empty effects array', () => {+ const {container} = render(+ <WrapSequenceContext>+ <Solid color="green" width={64} height={64} effects={[]} />+ </WrapSequenceContext>,+ );++ expect(container.querySelector('canvas')).not.toBeNull();+});