Skip to content

🎥 Make videos programmatically with React

@remotion/effects: Add mirror effect

JonnyBurger73fb3960a96c
diff --git a/packages/docs/components/effects/effects-mirror-preview.tsx b/packages/docs/components/effects/effects-mirror-preview.tsx
new file mode 100644
index 0000000000..f36619b508
--- /dev/null
+++ b/packages/docs/components/effects/effects-mirror-preview.tsx
@@ -0,0 +1,18 @@
+import {mirror} from '@remotion/effects/mirror';
+import React from 'react';
+import {HtmlInCanvas, useVideoConfig} from 'remotion';
+import {EffectsPreviewImage} from './effects-preview-image';
+
+export const EffectsMirrorPreview: React.FC = () => {
+ const {width, height} = useVideoConfig();
+
+ return (
+ <HtmlInCanvas
+ width={width}
+ height={height}
+ effects={[mirror({direction: 'horizontal', position: 0.5})]}
+ >
+ <EffectsPreviewImage />
+ </HtmlInCanvas>
+ );
+};
diff --git a/packages/docs/docs/effects/mirror.mdx b/packages/docs/docs/effects/mirror.mdx
new file mode 100644
index 0000000000..3498739e68
--- /dev/null
+++ b/packages/docs/docs/effects/mirror.mdx
@@ -0,0 +1,71 @@
+---
+image: /generated/articles-docs-effects-mirror.png
+slug: /effects/mirror
+title: mirror()
+sidebar_label: mirror()
+crumb: '@remotion/effects'
+---
+
+# mirror()<AvailableFrom v="4.0.466" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+A mirror effect that can be applied to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill} from 'remotion';
+import {Video} from '@remotion/media';
+import {mirror} from '@remotion/effects/mirror';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ mirror({
+ direction: 'horizontal',
+ position: 0.5,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties.
+
+### `direction?`
+
+Mirror direction. Defaults to `'horizontal'`.
+
+- `'horizontal'` mirrors left and right. The `position` is interpreted on the X axis.
+- `'vertical'` mirrors top and bottom. The `position` is interpreted on the Y axis.
+
+### `position?`
+
+Mirror position in UV coordinates from `0` to `1`. Defaults to `0.5`.
+
+### `invert?`
+
+When `true`, mirrors the other side of the image. Defaults to `false`.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`mirror()` 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)
+- [`scale()`](/docs/effects/scale)
+- [`wave()`](/docs/effects/wave)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/mirror/index.ts)
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index 2524e8b554..51eec11db4 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -110,6 +110,21 @@ export const TableOfContents: React.FC = () => {
</div>
</div>
</TOCItem>
+ <TOCItem link="/docs/effects/mirror">
+ <div style={row}>
+ <img
+ src="/img/effects-mirror-preview.jpg"
+ alt="mirror effect preview"
+ style={previewImage}
+ />
+ <div style={{flex: 1, marginLeft: 10}}>
+ <strong>
+ <code>{'mirror()'}</code>
+ </strong>
+ <div>Mirror reflection effect</div>
+ </div>
+ </div>
+ </TOCItem>
<TOCItem link="/docs/effects/saturation">
<div style={row}>
<img
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 22ca20e56b..2c5dac820b 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -273,6 +273,7 @@ const sidebars: SidebarsConfig = {
'effects/halftone',
'effects/hue',
'effects/invert',
+ 'effects/mirror',
'effects/saturation',
'effects/scale',
'effects/tint',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index aa1c2f9a92..fd87df4575 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1772,6 +1772,15 @@ export const articles = [
noAi: false,
slug: 'effects/invert',
},
+ {
+ id: 'effects/mirror',
+ title: 'mirror()',
+ relativePath: 'docs/effects/mirror.mdx',
+ compId: 'articles-docs-effects-mirror',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/mirror',
+ },
{
id: 'effects/saturation',
title: 'saturation()',
diff --git a/packages/docs/static/generated/articles-docs-effects-mirror.png b/packages/docs/static/generated/articles-docs-effects-mirror.png
new file mode 100644
index 0000000000..ee292d1e0a
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-mirror.png differ
diff --git a/packages/docs/static/img/effects-mirror-preview.jpg b/packages/docs/static/img/effects-mirror-preview.jpg
new file mode 100644
index 0000000000..b0866f5aa7
Binary files /dev/null and b/packages/docs/static/img/effects-mirror-preview.jpg differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index 912da08c63..0a34b8a2bb 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -13,6 +13,7 @@ const effectEntrypoints = [
'src/halftone.ts',
'src/hue.ts',
'src/invert.ts',
+ 'src/mirror.ts',
'src/saturation.ts',
'src/scale.ts',
'src/tint.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 02d955e14d..359c55bda2 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -62,6 +62,11 @@
"module": "./dist/esm/invert.mjs",
"import": "./dist/esm/invert.mjs"
},
+ "./mirror": {
+ "types": "./dist/mirror.d.ts",
+ "module": "./dist/esm/mirror.mjs",
+ "import": "./dist/esm/mirror.mjs"
+ },
"./saturation": {
"types": "./dist/saturation.d.ts",
"module": "./dist/esm/saturation.mjs",
@@ -104,6 +109,9 @@
"invert": [
"dist/invert.d.ts"
],
+ "mirror": [
+ "dist/mirror.d.ts"
+ ],
"saturation": [
"dist/saturation.d.ts"
],
diff --git a/packages/effects/src/mirror.ts b/packages/effects/src/mirror.ts
new file mode 100644
index 0000000000..f74f279120
--- /dev/null
+++ b/packages/effects/src/mirror.ts
@@ -0,0 +1,5 @@
+export {
+ mirror,
+ type MirrorDirection,
+ type MirrorParams,
+} from './mirror/index.js';
diff --git a/packages/effects/src/mirror/index.ts b/packages/effects/src/mirror/index.ts
new file mode 100644
index 0000000000..195ce38127
--- /dev/null
+++ b/packages/effects/src/mirror/index.ts
@@ -0,0 +1,115 @@
+import type {SequenceSchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ validateUnitInterval,
+} from '../color-utils.js';
+import {assertEffectParamsObject} from '../validate-effect-param.js';
+import {
+ applyMirror,
+ cleanupMirror,
+ setupMirror,
+ type MirrorDirection,
+ type MirrorState,
+} from './mirror-runtime.js';
+
+const {createEffect} = Internals;
+
+const mirrorSchema = {
+ direction: {
+ type: 'enum',
+ variants: {
+ horizontal: {},
+ vertical: {},
+ },
+ default: 'horizontal' as const,
+ description: 'Direction',
+ },
+ position: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: 0.5,
+ description: 'Position',
+ },
+ invert: {
+ type: 'boolean',
+ default: false,
+ description: 'Invert',
+ },
+} as const satisfies SequenceSchema;
+
+export type {MirrorDirection};
+
+export type MirrorParams = {
+ /** Mirror direction. Defaults to `horizontal`. */
+ readonly direction?: MirrorDirection;
+ /** Mirror position in UV coordinates. Defaults to `0.5`. */
+ readonly position?: number;
+ /** Mirror the other side of the image. Defaults to `false`. */
+ readonly invert?: boolean;
+};
+
+type MirrorResolved = {
+ direction: MirrorDirection;
+ position: number;
+ invert: boolean;
+};
+
+const resolve = (p: MirrorParams): MirrorResolved => ({
+ direction: p.direction ?? 'horizontal',
+ position: p.position ?? 0.5,
+ invert: p.invert ?? false,
+});
+
+const validateMirrorParams = (params: MirrorParams): void => {
+ assertEffectParamsObject(params, 'Mirror');
+ assertOptionalFiniteNumber(params.position, 'position');
+
+ if (
+ params.direction !== undefined &&
+ params.direction !== 'horizontal' &&
+ params.direction !== 'vertical'
+ ) {
+ throw new TypeError(
+ `"direction" must be "horizontal" or "vertical", but got ${JSON.stringify(params.direction)}`,
+ );
+ }
+
+ if (params.invert !== undefined && typeof params.invert !== 'boolean') {
+ throw new TypeError(
+ `"invert" must be a boolean, but got ${JSON.stringify(params.invert)}`,
+ );
+ }
+
+ const {position} = resolve(params);
+ validateUnitInterval(position, 'position');
+};
+
+export const mirror = createEffect<MirrorParams, MirrorState>({
+ type: 'remotion/mirror',
+ label: 'Mirror',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `mirror-${r.direction}-${r.position}-${r.invert ? 1 : 0}`;
+ },
+ setup: (target) => setupMirror(target),
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ applyMirror({
+ state,
+ source,
+ width,
+ height,
+ position: r.position,
+ direction: r.direction,
+ invert: r.invert,
+ flipSourceY,
+ });
+ },
+ cleanup: (state) => cleanupMirror(state),
+ schema: mirrorSchema,
+ validateParams: validateMirrorParams,
+});
diff --git a/packages/effects/src/mirror/mirror-runtime.ts b/packages/effects/src/mirror/mirror-runtime.ts
new file mode 100644
index 0000000000..48fa391594
--- /dev/null
+++ b/packages/effects/src/mirror/mirror-runtime.ts
@@ -0,0 +1,215 @@
+import {Internals} from 'remotion';
+import {MIRROR_FS, MIRROR_VS} from './mirror-shaders.js';
+
+const {createWebGL2ContextError} = Internals;
+
+export type MirrorDirection = 'horizontal' | 'vertical';
+
+export type MirrorState = {
+ gl: WebGL2RenderingContext;
+ program: WebGLProgram;
+ vao: WebGLVertexArrayObject;
+ vbo: WebGLBuffer;
+ textureSource: WebGLTexture;
+ uniforms: {
+ uSource: WebGLUniformLocation | null;
+ uPosition: WebGLUniformLocation | null;
+ uDirection: WebGLUniformLocation | null;
+ uInvert: 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 setupMirror = (target: HTMLCanvasElement): MirrorState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('mirror effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const program = createProgram(gl, MIRROR_VS, MIRROR_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'),
+ uPosition: gl.getUniformLocation(program, 'uPosition'),
+ uDirection: gl.getUniformLocation(program, 'uDirection'),
+ uInvert: gl.getUniformLocation(program, 'uInvert'),
+ },
+ };
+};
+
+export const cleanupMirror = (state: MirrorState): void => {
+ const {gl, program, vao, vbo, textureSource} = state;
+ gl.deleteTexture(textureSource);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+};
+
+const drawFullscreenQuad = (state: MirrorState): void => {
+ const {gl, vao} = state;
+ gl.bindVertexArray(vao);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ gl.bindVertexArray(null);
+};
+
+export const applyMirror = ({
+ state,
+ source,
+ width,
+ height,
+ position,
+ direction,
+ invert,
+ flipSourceY,
+}: {
+ readonly state: MirrorState;
+ readonly source: CanvasImageSource;
+ readonly width: number;
+ readonly height: number;
+ readonly position: number;
+ readonly direction: MirrorDirection;
+ readonly invert: boolean;
+ 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.uPosition) gl.uniform1f(uniforms.uPosition, position);
+ if (uniforms.uDirection)
+ gl.uniform1i(uniforms.uDirection, direction === 'horizontal' ? 0 : 1);
+ if (uniforms.uInvert) gl.uniform1i(uniforms.uInvert, invert ? 1 : 0);
+
+ 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/mirror/mirror-shaders.ts b/packages/effects/src/mirror/mirror-shaders.ts
new file mode 100644
index 0000000000..c2c6554d6c
--- /dev/null
+++ b/packages/effects/src/mirror/mirror-shaders.ts
@@ -0,0 +1,37 @@
+export const MIRROR_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 MIRROR_FS = /* glsl */ `#version 300 es
+precision highp float;
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform float uPosition;
+uniform int uDirection;
+uniform bool uInvert;
+
+void main() {
+ vec2 srcUv = vUv;
+ float coord = uDirection == 0 ? vUv.x : vUv.y;
+ bool shouldMirror = uInvert ? coord < uPosition : coord > uPosition;
+
+ if (shouldMirror) {
+ float mirrored = 2.0 * uPosition - coord;
+ if (uDirection == 0) {
+ srcUv.x = mirrored;
+ } else {
+ srcUv.y = mirrored;
+ }
+ }
+
+ fragColor = texture(uSource, clamp(srcUv, vec2(0.0), vec2(1.0)));
+}
+`;
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index e05f1182ea..6785b0e159 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -5,6 +5,7 @@ import {grayscale} from '../grayscale.js';
import {halftone} from '../halftone.js';
import {hue} from '../hue.js';
import {invert} from '../invert.js';
+import {mirror} from '../mirror.js';
import {saturation} from '../saturation.js';
import {scale} from '../scale.js';
import {tint} from '../tint.js';
@@ -216,6 +217,52 @@ test('invert() amount produces distinct effect keys', () => {
expect(none.effectKey).not.toBe(full.effectKey);
});
+test('mirror() accepts default params', () => {
+ expect(() => mirror()).not.toThrow();
+});
+
+test('mirror() rejects invalid direction', () => {
+ expect(() => mirror({direction: 'diagonal' as 'horizontal'})).toThrow(
+ '"direction" must be "horizontal" or "vertical"',
+ );
+});
+
+test('mirror() rejects non-finite position', () => {
+ expect(() => mirror({position: Number.NaN})).toThrow(
+ '"position" must be a finite number',
+ );
+});
+
+test('mirror() rejects position below range', () => {
+ expect(() => mirror({position: -0.1})).toThrow('"position" must be >= 0');
+});
+
+test('mirror() rejects position above range', () => {
+ expect(() => mirror({position: 1.1})).toThrow('"position" must be <= 1');
+});
+
+test('mirror() rejects non-boolean invert', () => {
+ expect(() => mirror({invert: 'yes' as unknown as boolean})).toThrow(
+ '"invert" must be a boolean',
+ );
+});
+
+test('mirror() parameters produce distinct effect keys', () => {
+ const horizontal = mirror({direction: 'horizontal'});
+ const vertical = mirror({direction: 'vertical'});
+ const shifted = mirror({position: 0.25});
+ const inverted = mirror({invert: true});
+
+ expect(
+ new Set([
+ horizontal.effectKey,
+ vertical.effectKey,
+ shifted.effectKey,
+ inverted.effectKey,
+ ]).size,
+ ).toBe(4);
+});
+
test('saturation() accepts default params', () => {
expect(() => saturation()).not.toThrow();
});