🎥 Make videos programmatically with React
@remotion/effects: Add barrel distortion effect
JonnyBurger33fa6115e852
diff --git a/packages/docs/components/effects/effects-barrel-distortion-preview.tsx b/packages/docs/components/effects/effects-barrel-distortion-preview.tsxnew file mode 100644index 0000000000..ec4cebb2bd--- /dev/null+++ b/packages/docs/components/effects/effects-barrel-distortion-preview.tsx@@ -0,0 +1,18 @@+import {barrelDistortion} from '@remotion/effects/barrel-distortion';+import React from 'react';+import {HtmlInCanvas, useVideoConfig} from 'remotion';+import {EffectsPreviewImage} from './effects-preview-image';++export const EffectsBarrelDistortionPreview: React.FC = () => {+ const {width, height} = useVideoConfig();++ return (+ <HtmlInCanvas+ width={width}+ height={height}+ effects={[barrelDistortion({amount: 0.28})]}+ >+ <EffectsPreviewImage />+ </HtmlInCanvas>+ );+};diff --git a/packages/docs/docs/effects/barrel-distortion.mdx b/packages/docs/docs/effects/barrel-distortion.mdxnew file mode 100644index 0000000000..16f2d694d8--- /dev/null+++ b/packages/docs/docs/effects/barrel-distortion.mdx@@ -0,0 +1,62 @@+---+image: /generated/articles-docs-effects-barrel-distortion.png+slug: /effects/barrel-distortion+title: barrelDistortion()+sidebar_label: barrelDistortion()+crumb: '@remotion/effects'+---++# barrelDistortion()<AvailableFrom v="4.0.466" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++A barrel distortion effect that bends canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).++It only applies geometric curvature. It does not add scanlines, blur, glow, chromatic aberration, noise, vignette, or color changes.++## Example++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill} from 'remotion';+import {Video} from '@remotion/media';+import {barrelDistortion} from '@remotion/effects/barrel-distortion';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Video+ src="https://remotion.media/video.mp4"+ effects={[+ barrelDistortion({+ amount: 0.25,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties.++### `amount?`++Curvature strength from `0` to `1`. Defaults to `0.25`.++Use `0` for no distortion.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`barrelDistortion()` uses a WebGL2 backend. During renders, enable WebGL via [`Config.setChromiumOpenGlRenderer()`](/docs/config#setchromiumopenglrenderer) (for example `'angle'`). See [Using WebGL during renders](/docs/remotion/html-in-canvas#using-webgl-during-renders).++## See also++- [`@remotion/effects`](/docs/effects/api)+- [`wave()`](/docs/effects/wave)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/barrel-distortion/index.ts)diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsxindex 51eec11db4..a49e799f9c 100644--- a/packages/docs/docs/effects/table-of-contents.tsx+++ b/packages/docs/docs/effects/table-of-contents.tsx@@ -20,6 +20,21 @@ export const TableOfContents: React.FC = () => {return (<div><Grid>+ <TOCItem link="/docs/effects/barrel-distortion">+ <div style={row}>+ <img+ src="/img/effects-barrel-distortion-preview.jpg"+ alt="barrel distortion effect preview"+ style={previewImage}+ />+ <div style={{flex: 1, marginLeft: 10}}>+ <strong>+ <code>{'barrelDistortion()'}</code>+ </strong>+ <div>Barrel distortion effect</div>+ </div>+ </div>+ </TOCItem><TOCItem link="/docs/effects/blur"><div style={row}><imgdiff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex c4f2640266..3e135f54b3 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -267,6 +267,7 @@ const sidebars: SidebarsConfig = {id: 'effects/effects-api',},items: [+ 'effects/barrel-distortion','effects/blur','effects/brightness','effects/grayscale',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex cddeae52ee..910aaf97f5 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1709,6 +1709,15 @@ export const articles = [noAi: false,slug: 'editor-starter/vs-studio',},+ {+ id: 'effects/barrel-distortion',+ title: 'barrelDistortion()',+ relativePath: 'docs/effects/barrel-distortion.mdx',+ compId: 'articles-docs-effects-barrel-distortion',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/barrel-distortion',+ },{id: 'effects/blur',title: 'blur()',diff --git a/packages/docs/static/generated/articles-docs-effects-barrel-distortion.png b/packages/docs/static/generated/articles-docs-effects-barrel-distortion.pngnew file mode 100644index 0000000000..add15ff306Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-barrel-distortion.png differdiff --git a/packages/docs/static/img/effects-barrel-distortion-preview.jpg b/packages/docs/static/img/effects-barrel-distortion-preview.jpgnew file mode 100644index 0000000000..320cc95d19Binary files /dev/null and b/packages/docs/static/img/effects-barrel-distortion-preview.jpg differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 0a34b8a2bb..e07270d26e 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -7,6 +7,7 @@ if (process.env.NODE_ENV !== 'production') {const effectEntrypoints = ['src/index.ts',+ 'src/barrel-distortion.ts','src/blur.ts','src/brightness.ts','src/grayscale.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex 359c55bda2..a9a06f580b 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -32,6 +32,11 @@"module": "./dist/esm/index.mjs","import": "./dist/esm/index.mjs"},+ "./barrel-distortion": {+ "types": "./dist/barrel-distortion.d.ts",+ "module": "./dist/esm/barrel-distortion.mjs",+ "import": "./dist/esm/barrel-distortion.mjs"+ },"./blur": {"types": "./dist/blur.d.ts","module": "./dist/esm/blur.mjs",@@ -91,6 +96,9 @@},"typesVersions": {">=1.0": {+ "barrel-distortion": [+ "dist/barrel-distortion.d.ts"+ ],"blur": ["dist/blur.d.ts"],diff --git a/packages/effects/src/barrel-distortion.ts b/packages/effects/src/barrel-distortion.tsnew file mode 100644index 0000000000..f84006e934--- /dev/null+++ b/packages/effects/src/barrel-distortion.ts@@ -0,0 +1,4 @@+export {+ barrelDistortion,+ type BarrelDistortionParams,+} from './barrel-distortion/index.js';diff --git a/packages/effects/src/barrel-distortion/barrel-distortion-runtime.ts b/packages/effects/src/barrel-distortion/barrel-distortion-runtime.tsnew file mode 100644index 0000000000..176b0cbdcf--- /dev/null+++ b/packages/effects/src/barrel-distortion/barrel-distortion-runtime.ts@@ -0,0 +1,207 @@+import {Internals} from 'remotion';+import {+ BARREL_DISTORTION_FS,+ BARREL_DISTORTION_VS,+} from './barrel-distortion-shaders.js';++const {createWebGL2ContextError} = Internals;++export type BarrelDistortionState = {+ gl: WebGL2RenderingContext;+ program: WebGLProgram;+ vao: WebGLVertexArrayObject;+ vbo: WebGLBuffer;+ textureSource: WebGLTexture;+ uniforms: {+ uSource: WebGLUniformLocation | null;+ uAmount: WebGLUniformLocation | null;+ };+};++const compileShader = (+ gl: WebGL2RenderingContext,+ type: number,+ source: string,+): WebGLShader => {+ const shader = gl.createShader(type);+ if (!shader) {+ throw new Error('Failed to create WebGL shader');+ }++ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {+ const log = gl.getShaderInfoLog(shader);+ gl.deleteShader(shader);+ throw new Error(`Shader compile failed: ${log ?? '(no log)'}`);+ }++ return shader;+};++const linkProgram = (+ gl: WebGL2RenderingContext,+ vs: WebGLShader,+ fs: WebGLShader,+): WebGLProgram => {+ const program = gl.createProgram();+ if (!program) {+ throw new Error('Failed to create WebGL program');+ }++ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ const log = gl.getProgramInfoLog(program);+ gl.deleteProgram(program);+ throw new Error(`Program link failed: ${log ?? '(no log)'}`);+ }++ return program;+};++const createProgram = (+ gl: WebGL2RenderingContext,+ vertexSource: string,+ fragmentSource: string,+): 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 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 setupBarrelDistortion = (+ target: HTMLCanvasElement,+): BarrelDistortionState => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('barrel distortion effect');+ }++ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);++ const program = createProgram(gl, BARREL_DISTORTION_VS, BARREL_DISTORTION_FS);++ const vao = gl.createVertexArray();+ if (!vao) {+ throw new Error('Failed to create WebGL vertex array');+ }++ gl.bindVertexArray(vao);++ const data = new Float32Array([+ -1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1,+ ]);++ const vbo = gl.createBuffer();+ if (!vbo) {+ throw new Error('Failed to create WebGL buffer');+ }++ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);+ gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);++ 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 textureSource = createRgbaTexture(gl);++ return {+ gl,+ program,+ vao,+ vbo,+ textureSource,+ uniforms: {+ uSource: gl.getUniformLocation(program, 'uSource'),+ uAmount: gl.getUniformLocation(program, 'uAmount'),+ },+ };+};++export const cleanupBarrelDistortion = (state: BarrelDistortionState): void => {+ const {gl, program, vao, vbo, textureSource} = state;+ gl.deleteTexture(textureSource);+ gl.deleteBuffer(vbo);+ gl.deleteProgram(program);+ gl.deleteVertexArray(vao);+};++const drawFullscreenQuad = (state: BarrelDistortionState): void => {+ const {gl, vao} = state;+ gl.bindVertexArray(vao);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ gl.bindVertexArray(null);+};++export const applyBarrelDistortion = ({+ state,+ source,+ width,+ height,+ amount,+ flipSourceY,+}: {+ readonly state: BarrelDistortionState;+ readonly source: CanvasImageSource;+ readonly width: number;+ readonly height: number;+ readonly amount: number;+ readonly flipSourceY: boolean;+}): void => {+ const {gl, program, textureSource, uniforms} = state;++ gl.viewport(0, 0, width, height);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);+ gl.bindTexture(gl.TEXTURE_2D, textureSource);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ source as TexImageSource,+ );+ gl.bindTexture(gl.TEXTURE_2D, null);++ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);++ gl.useProgram(program);+ if (uniforms.uSource) gl.uniform1i(uniforms.uSource, 0);+ if (uniforms.uAmount) gl.uniform1f(uniforms.uAmount, amount);++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, textureSource);+ drawFullscreenQuad(state);+ gl.bindTexture(gl.TEXTURE_2D, null);+ gl.useProgram(null);+};diff --git a/packages/effects/src/barrel-distortion/barrel-distortion-shaders.ts b/packages/effects/src/barrel-distortion/barrel-distortion-shaders.tsnew file mode 100644index 0000000000..aceabdb999--- /dev/null+++ b/packages/effects/src/barrel-distortion/barrel-distortion-shaders.ts@@ -0,0 +1,39 @@+export const BARREL_DISTORTION_VS = /* glsl */ `#version 300 es+layout(location = 0) in vec2 aPos;+layout(location = 1) in vec2 aUv;+out vec2 vUv;+void main() {+ vUv = aUv;+ gl_Position = vec4(aPos, 0.0, 1.0);+}+`;++export const BARREL_DISTORTION_FS = /* glsl */ `#version 300 es+precision highp float;+in vec2 vUv;+out vec4 fragColor;++uniform sampler2D uSource;+uniform float uAmount;++void main() {+ vec2 centered = vUv * 2.0 - 1.0;+ vec2 warped = centered;+ warped.x *= 1.0 + uAmount * centered.y * centered.y;+ warped.y *= 1.0 + uAmount * centered.x * centered.x;++ vec2 srcUv = warped * 0.5 + 0.5;++ if (+ srcUv.x < 0.0 ||+ srcUv.x > 1.0 ||+ srcUv.y < 0.0 ||+ srcUv.y > 1.0+ ) {+ fragColor = vec4(0.0);+ return;+ }++ fragColor = texture(uSource, srcUv);+}+`;diff --git a/packages/effects/src/barrel-distortion/index.ts b/packages/effects/src/barrel-distortion/index.tsnew file mode 100644index 0000000000..bb32ff610e--- /dev/null+++ b/packages/effects/src/barrel-distortion/index.ts@@ -0,0 +1,80 @@+import type {SequenceSchema} from 'remotion';+import {Internals} from 'remotion';+import {+ assertOptionalFiniteNumber,+ validateUnitInterval,+} from '../color-utils.js';+import {assertEffectParamsObject} from '../validate-effect-param.js';+import {+ applyBarrelDistortion,+ cleanupBarrelDistortion,+ setupBarrelDistortion,+ type BarrelDistortionState,+} from './barrel-distortion-runtime.js';++const {createEffect} = Internals;++const DEFAULT_BARREL_DISTORTION_AMOUNT = 0.25 as const;++const barrelDistortionSchema = {+ amount: {+ type: 'number',+ min: 0,+ max: 1,+ step: 0.01,+ default: DEFAULT_BARREL_DISTORTION_AMOUNT,+ description: 'Amount',+ },+} as const satisfies SequenceSchema;++export type BarrelDistortionParams = {+ /** Distortion strength from `0` to `1`. Defaults to `0.25`. */+ readonly amount?: number;+};++type BarrelDistortionResolved = {+ amount: number;+};++const resolve = (p: BarrelDistortionParams): BarrelDistortionResolved => ({+ amount: p.amount ?? DEFAULT_BARREL_DISTORTION_AMOUNT,+});++const validateBarrelDistortionParams = (+ params: BarrelDistortionParams,+): void => {+ assertEffectParamsObject(params, 'Barrel distortion');+ assertOptionalFiniteNumber(params.amount, 'amount');++ const resolved = resolve(params);+ validateUnitInterval(resolved.amount, 'amount');+};++export const barrelDistortion = createEffect<+ BarrelDistortionParams,+ BarrelDistortionState+>({+ type: 'remotion/barrel-distortion',+ label: 'Barrel Distortion',+ documentationLink: 'https://www.remotion.dev/docs/effects/barrel-distortion',+ backend: 'webgl2',+ calculateKey: (params) => {+ const r = resolve(params);+ return `barrel-distortion-${r.amount}`;+ },+ setup: (target) => setupBarrelDistortion(target),+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const r = resolve(params);+ applyBarrelDistortion({+ state,+ source,+ width,+ height,+ amount: r.amount,+ flipSourceY,+ });+ },+ cleanup: (state) => cleanupBarrelDistortion(state),+ schema: barrelDistortionSchema,+ validateParams: validateBarrelDistortionParams,+});diff --git a/packages/effects/src/mirror/index.ts b/packages/effects/src/mirror/index.tsindex 195ce38127..3bc89def19 100644--- a/packages/effects/src/mirror/index.ts+++ b/packages/effects/src/mirror/index.ts@@ -90,6 +90,7 @@ const validateMirrorParams = (params: MirrorParams): void => {export const mirror = createEffect<MirrorParams, MirrorState>({type: 'remotion/mirror',label: 'Mirror',+ documentationLink: 'https://www.remotion.dev/docs/effects/mirror',backend: 'webgl2',calculateKey: (params) => {const r = resolve(params);diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex 75b5b87387..8693512630 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -1,4 +1,5 @@import {expect, test} from 'bun:test';+import {barrelDistortion} from '../barrel-distortion/index.js';import {blur} from '../blur/index.js';import {brightness} from '../brightness.js';import {grayscale} from '../grayscale.js';@@ -12,6 +13,9 @@ import {tint} from '../tint.js';import {wave} from '../wave/index.js';test('@remotion/effects expose documentation links', () => {+ expect(barrelDistortion().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/barrel-distortion',+ );expect(blur({radius: 1}).definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/blur',);@@ -30,6 +34,9 @@ test('@remotion/effects expose documentation links', () => {expect(invert().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/invert',);+ expect(mirror().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/mirror',+ );expect(saturation().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/saturation',);@@ -44,6 +51,34 @@ test('@remotion/effects expose documentation links', () => {);});+test('barrelDistortion() accepts default params', () => {+ expect(() => barrelDistortion()).not.toThrow();+});++test('barrelDistortion() rejects non-finite amount', () => {+ expect(() => barrelDistortion({amount: Number.NaN})).toThrow(+ '"amount" must be a finite number',+ );+});++test('barrelDistortion() rejects amount below range', () => {+ expect(() => barrelDistortion({amount: -0.1})).toThrow(+ '"amount" must be >= 0',+ );+});++test('barrelDistortion() rejects amount above range', () => {+ expect(() => barrelDistortion({amount: 1.1})).toThrow(+ '"amount" must be <= 1',+ );+});++test('barrelDistortion() amount produces distinct effect keys', () => {+ const none = barrelDistortion({amount: 0});+ const strong = barrelDistortion({amount: 0.5});+ expect(none.effectKey).not.toBe(strong.effectKey);+});+test('tint() throws when color is not passed', () => {expect(() => tint({} as Parameters<typeof tint>[0])).toThrow('"color" must be a non-empty string, but got undefined',