🎥 Make videos programmatically with React
ok great simplification
JonnyBurger80d742280d29
diff --git a/packages/core/src/effects/effect-internals.ts b/packages/core/src/effects/effect-internals.tsindex fa97396010..5275992740 100644--- a/packages/core/src/effects/effect-internals.ts+++ b/packages/core/src/effects/effect-internals.ts@@ -10,22 +10,11 @@ import type {export const flattenEffects = (effects: EffectsProp,-): EffectDescriptor<unknown>[] => {- const out: EffectDescriptor<unknown>[] = [];- for (let sourceIndex = 0; sourceIndex < effects.length; sourceIndex++) {- const item = effects[sourceIndex];- if (Array.isArray(item)) {- for (const inner of item) {- out.push({...inner, sourceIndex});- }- } else {- const descriptor = item as EffectDescriptor<unknown>;- out.push({...descriptor, sourceIndex});- }- }-- return out;-};+): EffectDescriptor<unknown>[] =>+ effects.map((descriptor, sourceIndex) => ({+ ...descriptor,+ sourceIndex,+ }));export type Run = {readonly backend: Backend;diff --git a/packages/core/src/effects/effect-types.ts b/packages/core/src/effects/effect-types.tsindex 674506fdde..a8e0ea08a2 100644--- a/packages/core/src/effects/effect-types.ts+++ b/packages/core/src/effects/effect-types.ts@@ -52,10 +52,9 @@ type BaseEffectDescriptor<P = unknown> = {readonly effectKey: string;readonly params: P;/**- * Index of this descriptor in the user's `_experimentalEffects` source array- * (pre-flatten). Compound factories like `blur()` produce multiple- * descriptors that share the same `sourceIndex`. `-1` means the descriptor- * has not yet been placed in an effects array (e.g. fresh from `createEffect`).+ * Index of this descriptor in the user's `_experimentalEffects` array.+ * `-1` means the descriptor has not yet been placed in an effects array+ * (e.g. fresh from `createEffect`).*/readonly sourceIndex: number;};@@ -69,11 +68,4 @@ export type EffectDefinitionAndStack<P = unknown> = BaseEffectDescriptor<P> & {readonly memoized: true;};-// 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.-export type EffectsProp = ReadonlyArray<- EffectDescriptor<unknown> | ReadonlyArray<EffectDescriptor<unknown>>->;+export type EffectsProp = ReadonlyArray<EffectDescriptor<unknown>>;diff --git a/packages/core/src/test/effect-internals.test.ts b/packages/core/src/test/effect-internals.test.tsindex 5b3a18ad4e..94ae03b44a 100644--- a/packages/core/src/test/effect-internals.test.ts+++ b/packages/core/src/test/effect-internals.test.ts@@ -42,29 +42,20 @@ const memoizeEffects = (}));};-test('flattenEffects unwraps nested-array descriptors', () => {+test('flattenEffects assigns sourceIndex from array order', () => {const a = makeDesc('a', '2d');- const b1 = makeDesc('b1', '2d');- const b2 = makeDesc('b2', '2d');+ const b = makeDesc('b', '2d');const c = makeDesc('c', 'webgl2');- const result = memoizeEffects(flattenEffects([a, [b1, b2], c]));- expect(result.map((d) => d.definition.type)).toEqual(['a', 'b1', 'b2', 'c']);+ const result = memoizeEffects(flattenEffects([a, b, c]));+ expect(result.map((d) => d.definition.type)).toEqual(['a', 'b', 'c']);+ expect(result.map((d) => d.sourceIndex)).toEqual([0, 1, 2]);});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'),diff --git a/packages/effects/src/blur/blur-horizontal.ts b/packages/effects/src/blur/blur-horizontal.tsdeleted file mode 100644index d3735c49d2..0000000000--- a/packages/effects/src/blur/blur-horizontal.ts+++ /dev/null@@ -1,29 +0,0 @@-import {Internals} from 'remotion';--const {createEffect} = Internals;-import {- applyBlur,- cleanupBlur,- setupBlur,- type BlurState,-} from './blur-runtime.js';-import {BLUR_FS_HORIZONTAL} from './blur-shaders.js';--export type BlurHorizontalParams = {- readonly radius: number;-};--// Single horizontal pass of the separable Gaussian blur. Most callers should-// use [`blur`](./index.ts) which composes both horizontal and vertical passes.-export const blurHorizontal = createEffect<BlurHorizontalParams, BlurState>({- type: 'remotion/blur-horizontal',- label: 'Blur (horizontal)',- backend: 'webgl2',- calculateKey: (params) => String(params.radius),- setup: (target) => setupBlur(target, BLUR_FS_HORIZONTAL),- apply: ({source, width, height, params, state}) => {- applyBlur(state, source, width, height, params.radius);- },- cleanup: (state) => cleanupBlur(state),- schema: null,-});diff --git a/packages/effects/src/blur/blur-runtime.ts b/packages/effects/src/blur/blur-runtime.tsindex e95e0d3153..39418dd74e 100644--- a/packages/effects/src/blur/blur-runtime.ts+++ b/packages/effects/src/blur/blur-runtime.ts@@ -1,19 +1,28 @@-import {BLUR_VS} from './blur-shaders.js';+import {BLUR_FS_HORIZONTAL, BLUR_FS_VERTICAL, BLUR_VS} from './blur-shaders.js';-// Shared WebGL2 plumbing for the separable Gaussian blur passes.-// `setupBlur` compiles a fullscreen-quad VS + the supplied FS, allocates-// the quad VBO/VAO, and creates a sampling texture. `applyBlur` uploads-// the source into the sampling texture, sets uniforms, and draws.+// WebGL2 separable Gaussian blur: horizontal pass renders into an intermediate+// texture (FBO), vertical pass samples that texture and draws to the canvas.+// Both passes share the same fullscreen quad (VAO/VBO).export type BlurState = {gl: WebGL2RenderingContext;- program: WebGLProgram;+ programHorizontal: WebGLProgram;+ programVertical: WebGLProgram;vao: WebGLVertexArrayObject;vbo: WebGLBuffer;- texture: WebGLTexture;- uRadius: WebGLUniformLocation | null;- uTexelSize: WebGLUniformLocation | null;- uSource: WebGLUniformLocation | null;+ textureSource: WebGLTexture;+ textureIntermediate: WebGLTexture;+ framebuffer: WebGLFramebuffer;+ horizontal: {+ uRadius: WebGLUniformLocation | null;+ uTexelSize: WebGLUniformLocation | null;+ uSource: WebGLUniformLocation | null;+ };+ vertical: {+ uRadius: WebGLUniformLocation | null;+ uTexelSize: WebGLUniformLocation | null;+ uSource: WebGLUniformLocation | null;+ };};const compileShader = (@@ -59,10 +68,44 @@ const linkProgram = (return program;};-export const setupBlur = (- target: HTMLCanvasElement,+const createProgram = (+ gl: WebGL2RenderingContext,+ vertexSource: string,fragmentSource: string,-): BlurState => {+): WebGLProgram => {+ const vs = compileShader(gl, gl.VERTEX_SHADER, vertexSource);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSource);+ const program = linkProgram(gl, vs, fs);+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ return program;+};++const getBlurUniforms = (+ gl: WebGL2RenderingContext,+ program: WebGLProgram,+): BlurState['horizontal'] => ({+ uRadius: gl.getUniformLocation(program, 'uRadius'),+ uTexelSize: gl.getUniformLocation(program, 'uTexelSize'),+ uSource: gl.getUniformLocation(program, 'uSource'),+});++const createRgbaTexture = (gl: WebGL2RenderingContext): WebGLTexture => {+ const texture = gl.createTexture();+ if (!texture) {+ throw new Error('Failed to create WebGL texture');+ }++ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.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.bindTexture(gl.TEXTURE_2D, null);+ return texture;+};++export const setupBlur = (target: HTMLCanvasElement): BlurState => {const gl = target.getContext('webgl2', {premultipliedAlpha: true,alpha: true,@@ -73,14 +116,10 @@ export const setupBlur = (}gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);- // Align DOM image/video rows with texture coords used by the fullscreen quad.gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);- const vs = compileShader(gl, gl.VERTEX_SHADER, BLUR_VS);- const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSource);- const program = linkProgram(gl, vs, fs);- gl.deleteShader(vs);- gl.deleteShader(fs);+ const programHorizontal = createProgram(gl, BLUR_VS, BLUR_FS_HORIZONTAL);+ const programVertical = createProgram(gl, BLUR_VS, BLUR_FS_VERTICAL);const vao = gl.createVertexArray();if (!vao) {@@ -89,8 +128,6 @@ export const setupBlur = (gl.bindVertexArray(vao);- // Fullscreen-quad: positions in clip space + matching uv coords.- // Using a triangle strip (4 verts) avoids an index buffer.const data = new Float32Array([-1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1,]);@@ -103,60 +140,140 @@ export const setupBlur = (gl.bindBuffer(gl.ARRAY_BUFFER, vbo);gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);- const aPos = gl.getAttribLocation(program, 'aPos');- const aUv = gl.getAttribLocation(program, 'aUv');- gl.enableVertexAttribArray(aPos);- gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 16, 0);- gl.enableVertexAttribArray(aUv);- gl.vertexAttribPointer(aUv, 2, gl.FLOAT, false, 16, 8);+ gl.enableVertexAttribArray(0);+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(1);+ gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 16, 8);gl.bindVertexArray(null);- const texture = gl.createTexture();- if (!texture) {- throw new Error('Failed to create WebGL texture');+ const textureSource = createRgbaTexture(gl);+ const textureIntermediate = createRgbaTexture(gl);++ const framebuffer = gl.createFramebuffer();+ if (!framebuffer) {+ throw new Error('Failed to create WebGL framebuffer');}- gl.bindTexture(gl.TEXTURE_2D, texture);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);- gl.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);+ const w = Math.max(1, target.width);+ const h = Math.max(1, target.height);+ gl.bindTexture(gl.TEXTURE_2D, textureIntermediate);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ w,+ h,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ null,+ );gl.bindTexture(gl.TEXTURE_2D, null);- const uRadius = gl.getUniformLocation(program, 'uRadius');- const uTexelSize = gl.getUniformLocation(program, 'uTexelSize');- const uSource = gl.getUniformLocation(program, 'uSource');+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ gl.framebufferTexture2D(+ gl.FRAMEBUFFER,+ gl.COLOR_ATTACHMENT0,+ gl.TEXTURE_2D,+ textureIntermediate,+ 0,+ );+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ if (status !== gl.FRAMEBUFFER_COMPLETE) {+ throw new Error(`Blur framebuffer incomplete: 0x${status.toString(16)}`);+ }- return {gl, program, vao, vbo, texture, uRadius, uTexelSize, uSource};+ return {+ gl,+ programHorizontal,+ programVertical,+ vao,+ vbo,+ textureSource,+ textureIntermediate,+ framebuffer,+ horizontal: getBlurUniforms(gl, programHorizontal),+ vertical: getBlurUniforms(gl, programVertical),+ };};export const cleanupBlur = (state: BlurState): void => {- const {gl, program, vao, vbo, texture} = state;+ const {+ gl,+ programHorizontal,+ programVertical,+ vao,+ vbo,+ textureSource,+ textureIntermediate,+ framebuffer,+ } = state;+ gl.deleteFramebuffer(framebuffer);+ gl.deleteTexture(textureSource);+ gl.deleteTexture(textureIntermediate);gl.deleteBuffer(vbo);- gl.deleteProgram(program);+ gl.deleteProgram(programHorizontal);+ gl.deleteProgram(programVertical);gl.deleteVertexArray(vao);- gl.deleteTexture(texture);};-export const applyBlur = (- state: BlurState,- source: CanvasImageSource,- width: number,- height: number,- radius: number,-): void => {- const {gl, program, vao, texture, uRadius, uTexelSize, uSource} = state;+type SetBlurUniformsParams = {+ readonly gl: WebGL2RenderingContext;+ readonly uniforms: BlurState['horizontal'];+ readonly radius: number;+ readonly width: number;+ readonly height: number;+};- gl.viewport(0, 0, width, height);- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT);+const setBlurUniforms = ({+ gl,+ uniforms,+ radius,+ width,+ height,+}: SetBlurUniformsParams): void => {+ if (uniforms.uSource) gl.uniform1i(uniforms.uSource, 0);+ if (uniforms.uRadius) gl.uniform1f(uniforms.uRadius, radius);+ if (uniforms.uTexelSize)+ gl.uniform2f(uniforms.uTexelSize, 1 / width, 1 / height);+};- gl.useProgram(program);+const drawFullscreenQuad = (state: BlurState): void => {+ const {gl, vao} = state;gl.bindVertexArray(vao);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ gl.bindVertexArray(null);+};- gl.activeTexture(gl.TEXTURE0);- gl.bindTexture(gl.TEXTURE_2D, texture);+type ApplyBlurParams = {+ readonly state: BlurState;+ readonly source: CanvasImageSource;+ readonly width: number;+ readonly height: number;+ readonly radius: number;+};++export const applyBlur = ({+ state,+ source,+ width,+ height,+ radius,+}: ApplyBlurParams): void => {+ const {+ gl,+ programHorizontal,+ programVertical,+ textureSource,+ textureIntermediate,+ framebuffer,+ } = state;++ gl.viewport(0, 0, width, height);++ gl.bindTexture(gl.TEXTURE_2D, textureSource);gl.texImage2D(gl.TEXTURE_2D,0,@@ -166,13 +283,51 @@ export const applyBlur = (source as TexImageSource,);- if (uSource) gl.uniform1i(uSource, 0);- if (uRadius) gl.uniform1f(uRadius, radius);- if (uTexelSize) gl.uniform2f(uTexelSize, 1 / width, 1 / height);+ gl.bindTexture(gl.TEXTURE_2D, textureIntermediate);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ width,+ height,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ null,+ );+ gl.bindTexture(gl.TEXTURE_2D, null);++ gl.clearColor(0, 0, 0, 0);- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ // Pass 1: horizontal blur from `textureSource` into `textureIntermediate`.+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, textureSource);+ gl.useProgram(programHorizontal);+ setBlurUniforms({+ gl,+ uniforms: state.horizontal,+ radius,+ width,+ height,+ });+ drawFullscreenQuad(state);++ // Pass 2: vertical blur from `textureIntermediate` onto the default framebuffer.+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.bindTexture(gl.TEXTURE_2D, textureIntermediate);+ gl.useProgram(programVertical);+ setBlurUniforms({+ gl,+ uniforms: state.vertical,+ radius,+ width,+ height,+ });+ drawFullscreenQuad(state);- gl.bindVertexArray(null);gl.bindTexture(gl.TEXTURE_2D, null);gl.useProgram(null);};diff --git a/packages/effects/src/blur/blur-shaders.ts b/packages/effects/src/blur/blur-shaders.tsindex 4c9ca35aaf..2ccf2cf03a 100644--- a/packages/effects/src/blur/blur-shaders.ts+++ b/packages/effects/src/blur/blur-shaders.ts@@ -1,16 +1,13 @@-// Shared GLSL sources for the separable Gaussian blur passes.+// GLSL for the WebGL2 Gaussian blur: one fragment shader per separable axis.+// `blur-runtime` runs horizontal into an offscreen texture, then vertical onto+// the canvas, so both passes stay branch-free (direction is a `const vec2`).//-// The blur is implemented as a 9-tap kernel (KERNEL_HALF = 4) with the sample-// stride scaled by `uRadius` so the kernel always spans approximately-// ±uRadius pixels. Sigma is set to uRadius / 3 (the standard 3-sigma rule)-// so weights at the kernel edges are small but non-zero.-//-// The sampling direction is baked into the fragment shader as a vec2 constant-// to keep the inner loop branch-free.+// 9 taps (KERNEL_HALF = 4), stride scaled by `uRadius` (~±uRadius span),+// sigma = uRadius / 3.export const BLUR_VS = /* glsl */ `#version 300 es-in vec2 aPos;-in vec2 aUv;+layout(location = 0) in vec2 aPos;+layout(location = 1) in vec2 aUv;out vec2 vUv;void main() {vUv = aUv;diff --git a/packages/effects/src/blur/blur-vertical.ts b/packages/effects/src/blur/blur-vertical.tsdeleted file mode 100644index 2e06a929f5..0000000000--- a/packages/effects/src/blur/blur-vertical.ts+++ /dev/null@@ -1,29 +0,0 @@-import {Internals} from 'remotion';--const {createEffect} = Internals;-import {- applyBlur,- cleanupBlur,- setupBlur,- type BlurState,-} from './blur-runtime.js';-import {BLUR_FS_VERTICAL} from './blur-shaders.js';--export type BlurVerticalParams = {- readonly radius: number;-};--// Single vertical pass of the separable Gaussian blur. Most callers should-// use [`blur`](./index.ts) which composes both horizontal and vertical passes.-export const blurVertical = createEffect<BlurVerticalParams, BlurState>({- type: 'remotion/blur-vertical',- label: 'Blur (vertical)',- backend: 'webgl2',- calculateKey: (params) => String(params.radius),- setup: (target) => setupBlur(target, BLUR_FS_VERTICAL),- apply: ({source, width, height, params, state}) => {- applyBlur(state, source, width, height, params.radius);- },- cleanup: (state) => cleanupBlur(state),- schema: null,-});diff --git a/packages/effects/src/blur/index.ts b/packages/effects/src/blur/index.tsindex ab0246885d..143447a80c 100644--- a/packages/effects/src/blur/index.ts+++ b/packages/effects/src/blur/index.ts@@ -1,25 +1,32 @@-import type {EffectDescriptor} from 'remotion';-import {blurHorizontal} from './blur-horizontal.js';-import {blurVertical} from './blur-vertical.js';+import {Internals} from 'remotion';++const {createEffect} = Internals;+import {+ applyBlur,+ cleanupBlur,+ setupBlur,+ type BlurState,+} from './blur-runtime.js';export type BlurParams = {readonly radius: number;};-// Separable Gaussian blur. Returns a tuple of horizontal + vertical passes.-// Both passes share the same WebGL2 program structure but bake the sampling-// direction into the fragment shader at compile time. Callers spread the-// result into the `effects` prop or pass the whole tuple thanks to the-// runtime's automatic flattening.-export const blur = (- params: BlurParams,-): readonly [EffectDescriptor<unknown>, EffectDescriptor<unknown>] =>- [- blurHorizontal({radius: params.radius}),- blurVertical({radius: params.radius}),- ] as const;--export {blurHorizontal} from './blur-horizontal.js';-export type {BlurHorizontalParams} from './blur-horizontal.js';-export {blurVertical} from './blur-vertical.js';-export type {BlurVerticalParams} from './blur-vertical.js';+export const blur = createEffect<BlurParams, BlurState>({+ type: 'remotion/blur',+ label: 'Blur',+ backend: 'webgl2',+ calculateKey: (params) => String(params.radius),+ setup: (target) => setupBlur(target),+ apply: ({source, width, height, params, state}) => {+ applyBlur({+ state,+ source,+ width,+ height,+ radius: params.radius,+ });+ },+ cleanup: (state) => cleanupBlur(state),+ schema: null,+});diff --git a/packages/effects/src/entrypoints/blur.ts b/packages/effects/src/entrypoints/blur.tsindex 30d36fc456..471f0ffe70 100644--- a/packages/effects/src/entrypoints/blur.ts+++ b/packages/effects/src/entrypoints/blur.ts@@ -1,11 +1,7 @@import * as blurExports from '../blur/index.js';-export type {- BlurHorizontalParams,- BlurParams,- BlurVerticalParams,-} from '../blur/index.js';+export type {BlurParams} from '../blur/index.js';-const {blur, blurHorizontal, blurVertical} = blurExports;+const {blur} = blurExports;-export {blur, blurHorizontal, blurVertical};+export {blur};