Skip to content

🎥 Make videos programmatically with React

Add lensBlur effect with shaped bokeh and focus demo

Jonny Burger5fbb1546556f
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index 7da0e6a645..4e211f313f 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -25,6 +25,7 @@ import {
pageTurnDemo,
fractalNoiseDemo,
turbulentDisplaceDemo,
+ lensBlurDemo,
customPresentationDemo,
customTimingDemo,
dissolvePresentationDemo,
@@ -163,6 +164,7 @@ const demos: DemoType[] = [
pageTurnDemo,
fractalNoiseDemo,
turbulentDisplaceDemo,
+ lensBlurDemo,
animationMathDemo,
roundedTextBoxDemo,
springDemo,
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 817b606c48..df0e6fde5b 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -1,5 +1,6 @@
import type {LogLevel} from 'remotion';
import {FractalNoiseDemo} from '../effects/effects-fractal-noise-preview';
+import {LensBlurDemo} from '../effects/effects-lens-blur-preview';
import {PageTurnDemo} from '../effects/effects-page-turn-preview';
import {SpinningGlobeDemo} from '../effects/effects-sphere-preview';
import {TurbulentDisplaceDemo} from '../effects/effects-turbulent-displace-preview';
@@ -1813,3 +1814,16 @@ export const turbulentDisplaceDemo: DemoType = {
logLevel: 'info',
options: [],
};
+
+export const lensBlurDemo: DemoType = {
+ comp: LensBlurDemo,
+ compWidth: 1280,
+ compHeight: 720,
+ fps: 30,
+ durationInFrames: 120,
+ id: 'lens-blur',
+ autoPlay: true,
+ controls: true,
+ logLevel: 'info',
+ options: [],
+};
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.ts
index 74f83bf77e..ba97238b86 100644
--- a/packages/docs/components/effects-demos/registry.ts
+++ b/packages/docs/components/effects-demos/registry.ts
@@ -26,6 +26,7 @@ import {halftone} from '@remotion/effects/halftone';
import {halftoneLinearGradient} from '@remotion/effects/halftone-linear-gradient';
import {hue} from '@remotion/effects/hue';
import {invert} from '@remotion/effects/invert';
+import {lensBlur} from '@remotion/effects/lens-blur';
import {levels} from '@remotion/effects/levels';
import {lightLeak} from '@remotion/effects/light-leak';
import {lightTrail} from '@remotion/effects/light-trail';
@@ -104,6 +105,7 @@ import {EffectsHalftoneLinearGradientPreview} from '../effects/effects-halftone-
import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';
import {EffectsHuePreview} from '../effects/effects-hue-preview';
import {EffectsInvertPreview} from '../effects/effects-invert-preview';
+import {EffectsLensBlurPreview} from '../effects/effects-lens-blur-preview';
import {EffectsLevelsPreview} from '../effects/effects-levels-preview';
import {EffectsLightLeakPreview} from '../effects/effects-light-leak-preview';
import {
@@ -206,6 +208,14 @@ const shrinkwrapDemoSchema = {
const cylinderDemoSchema = cylinder().definition.schema;
export const effectsDemos: EffectsDemoType[] = [
+ {
+ ...defaults,
+ id: 'effects-lens-blur',
+ effectName: 'lensBlur',
+ effectImportPath: '@remotion/effects/lens-blur',
+ comp: EffectsLensBlurPreview,
+ schema: lensBlur().definition.schema,
+ },
{
...defaults,
id: 'effects-turbulent-displace',
diff --git a/packages/docs/components/effects/effects-lens-blur-preview.tsx b/packages/docs/components/effects/effects-lens-blur-preview.tsx
new file mode 100644
index 0000000000..20c444b404
--- /dev/null
+++ b/packages/docs/components/effects/effects-lens-blur-preview.tsx
@@ -0,0 +1,110 @@
+import {lensBlur, type LensBlurParams} from '@remotion/effects/lens-blur';
+import {Video} from '@remotion/media';
+import React from 'react';
+import {
+ AbsoluteFill,
+ CanvasImage,
+ Easing,
+ HtmlInCanvas,
+ Interactive,
+ interpolate,
+ useCurrentFrame,
+} from 'remotion';
+import {useHtmlInCanvasDocsDemoBranch} from '../demos/useHtmlInCanvasDocsDemoBranch';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const EffectsLensBlurPreview: React.FC<Required<LensBlurParams>> = ({
+ radius,
+ irisShape,
+ irisRoundness,
+ irisRotation,
+ irisAspectRatio,
+ highlightGain,
+ highlightThreshold,
+ highlightSaturation,
+ repeatEdgePixels,
+ samples,
+ linearLight,
+}) => {
+ return (
+ <CanvasImage
+ name="Lens blur preview"
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ fit="cover"
+ effects={[
+ lensBlur({
+ radius,
+ irisShape,
+ irisRoundness,
+ irisRotation,
+ irisAspectRatio,
+ highlightGain,
+ highlightThreshold,
+ highlightSaturation,
+ repeatEdgePixels,
+ samples,
+ linearLight,
+ }),
+ ]}
+ />
+ );
+};
+
+const LensBlurScene: React.FC = () => {
+ const frame = useCurrentFrame();
+ return (
+ <AbsoluteFill style={{backgroundColor: 'black'}}>
+ <HtmlInCanvas
+ name="Focus pull"
+ width={1280}
+ height={720}
+ effects={[
+ lensBlur({
+ radius: interpolate(frame, [0, 40, 80, 120], [40, 0, 0, 40], {
+ easing: Easing.bezier(0.42, 0, 0.58, 1),
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ }),
+ irisShape: 'hexagon',
+ samples: 512,
+ }),
+ ]}
+ >
+ <Interactive.Div
+ name="Focus text"
+ style={{
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontFamily: 'Arial, Helvetica, sans-serif',
+ fontSize: 180,
+ fontWeight: 900,
+ lineHeight: 1,
+ color: 'white',
+ }}
+ >
+ FOCUS
+ </Interactive.Div>
+ </HtmlInCanvas>
+ </AbsoluteFill>
+ );
+};
+
+export const LensBlurDemo: React.FC = () => {
+ const branch = useHtmlInCanvasDocsDemoBranch('webgl2');
+ if (branch === 'pending')
+ return <AbsoluteFill style={{backgroundColor: 'black'}} />;
+ if (branch === 'live') return <LensBlurScene />;
+ return (
+ <Video
+ name="Lens blur video preview"
+ muted
+ src="https://remotion.media/lens-blur-demo-b127a7f41f9d.mp4"
+ style={{width: '100%', height: '100%'}}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/lens-blur.mdx b/packages/docs/docs/effects/lens-blur.mdx
new file mode 100644
index 0000000000..a53f0dcb5a
--- /dev/null
+++ b/packages/docs/docs/effects/lens-blur.mdx
@@ -0,0 +1,143 @@
+---
+image: /generated/articles-docs-effects-lens-blur.png
+slug: /effects/lens-blur
+title: lensBlur()
+sidebar_label: lensBlur()
+crumb: '@remotion/effects'
+---
+
+# lensBlur()<AvailableFrom v="4.0.537" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+Defocuses an image through a circular or polygonal aperture. Bright points spread into bokeh with the selected iris shape.
+
+Apply it to canvas-based components such as [`<Video>`](/docs/media/video), [`<CanvasImage>`](/docs/canvasimage), and [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas). It uses the component's source image without a separate blur map.
+
+## Preview
+
+<Demo type="lens-blur" />
+
+## Controls
+
+<EffectsDemo type="effects-lens-blur" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {lensBlur} from '@remotion/effects/lens-blur';
+import {HtmlInCanvas, Interactive, interpolate, useCurrentFrame} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ const frame = useCurrentFrame();
+ return (
+ <HtmlInCanvas
+ width={1280}
+ height={720}
+ effects={[
+ lensBlur({
+ radius: interpolate(frame, [0, 40], [40, 0], {
+ extrapolateRight: 'clamp',
+ }),
+ irisShape: 'hexagon',
+ samples: 512,
+ }),
+ ]}
+ >
+ <Interactive.Div
+ name="Focus text"
+ style={{
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: 'white',
+ fontFamily: 'Arial, Helvetica, sans-serif',
+ fontSize: 180,
+ fontWeight: 900,
+ }}
+ >
+ FOCUS
+ </Interactive.Div>
+ </HtmlInCanvas>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. All numeric values must be finite.
+
+### `radius?`
+
+Blur radius in pixels. Must be non-negative. Defaults to `10`.
+
+At `0`, the source is unchanged, including when highlight controls are enabled.
+
+### `irisShape?`
+
+Shape of the aperture. One of `'triangle'`, `'square'`, `'pentagon'`, `'hexagon'`, `'heptagon'`, `'octagon'`, `'nonagon'`, `'decagon'`, or `'circle'`. Defaults to `'hexagon'`.
+
+### `irisRoundness?`
+
+Rounds a polygonal iris toward a circle. Ranges from `0` (polygon) to `1` (circle). Defaults to `0`. Has no effect when `irisShape` is `'circle'`.
+
+### `irisRotation?`
+
+Clockwise rotation of the iris in degrees. Defaults to `0`.
+
+### `irisAspectRatio?`
+
+Horizontal stretch of the aperture. Values above `1` produce wider bokeh; values below `1` produce taller bokeh. Must be greater than `0`. Defaults to `1`.
+
+### `highlightGain?`
+
+Additional brightness applied to highlights before averaging them across the aperture. Ranges from `0` to `1`. Defaults to `0`.
+
+At `1`, qualifying highlights contribute five times their original brightness. Alpha is blurred without a brightness boost.
+
+### `highlightThreshold?`
+
+Minimum source luminance that receives `highlightGain`. Ranges from `0` to `1`. Defaults to `1`.
+
+### `highlightSaturation?`
+
+Color saturation of the added highlight brightness. Ranges from `0` (white) to `1` (source color). Defaults to `1`.
+
+### `repeatEdgePixels?`
+
+When `true`, samples outside the source repeat its edge pixels. When `false`, those samples are transparent. Defaults to `false`.
+
+The result stays within the source canvas. Leave padding around content if the blur should extend beyond its edges.
+
+### `samples?`
+
+Number of samples across the aperture. Must be an integer from `16` to `2048`. Defaults to `256`.
+
+Higher values reduce grain around small highlights and large blur radii, and take longer to render. The sample pattern is deterministic.
+
+### `linearLight?`
+
+When `true`, averages colors in linear light, then converts the result back to sRGB. This keeps transitions between bright and dark pixels brighter. Defaults to `false`.
+
+The highlight threshold is evaluated on the source's sRGB luminance in either mode.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`lensBlur()` uses WebGL2. See [Using WebGL and WebGPU during renders](/docs/webgl).
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />
+
+## See also
+
+- [`blur()`](/docs/effects/blur)
+- [`zoomBlur()`](/docs/effects/zoom-blur)
+- [`@remotion/effects`](/docs/effects/api)
+- [Source code](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/lens-blur/index.ts)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 7543678d4f..ee00ebf6f8 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -310,6 +310,7 @@ const sidebars: SidebarsConfig = {
'effects/halftone-linear-gradient',
'effects/hue',
'effects/invert',
+ 'effects/lens-blur',
'effects/levels',
'effects/linear-gradient',
'effects/linear-gradient-tint',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 0d33307b2b..b953191769 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -3645,6 +3645,15 @@ export const articles = [
noAi: false,
slug: 'effects/invert',
},
+ {
+ id: 'effects/lens-blur',
+ title: 'lensBlur()',
+ relativePath: 'docs/effects/lens-blur.mdx',
+ compId: 'articles-docs-effects-lens-blur',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/lens-blur',
+ },
{
id: 'effects/levels',
title: 'levels()',
diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsx
index 71ab3863a9..bd9f34437c 100644
--- a/packages/docs/src/remotion/Root.tsx
+++ b/packages/docs/src/remotion/Root.tsx
@@ -38,6 +38,10 @@ import {EffectsHalftoneLinearGradientPreview} from '../../components/effects/eff
import {EffectsHalftonePreview} from '../../components/effects/effects-halftone-preview';
import {EffectsHuePreview} from '../../components/effects/effects-hue-preview';
import {EffectsInvertPreview} from '../../components/effects/effects-invert-preview';
+import {
+ EffectsLensBlurPreview,
+ LensBlurDemo,
+} from '../../components/effects/effects-lens-blur-preview';
import {EffectsLevelsPreview} from '../../components/effects/effects-levels-preview';
import {EffectsLightLeakPreview} from '../../components/effects/effects-light-leak-preview';
import {
@@ -443,6 +447,33 @@ export const RemotionRoot: React.FC = () => {
feather: 0.18,
}}
/>
+ <Still
+ id="effects-lens-blur-preview"
+ component={EffectsLensBlurPreview}
+ width={1280}
+ height={720}
+ defaultProps={{
+ radius: 16,
+ irisShape: 'hexagon',
+ irisRoundness: 0,
+ irisRotation: 0,
+ irisAspectRatio: 1,
+ highlightGain: 0.5,
+ highlightThreshold: 0.8,
+ highlightSaturation: 1,
+ repeatEdgePixels: true,
+ samples: 512,
+ linearLight: false,
+ }}
+ />
+ <Composition
+ id="lens-blur-demo"
+ component={LensBlurDemo}
+ width={1280}
+ height={720}
+ fps={30}
+ durationInFrames={120}
+ />
<Still
id="effects-turbulent-displace-text-source"
component={TurbulentDisplaceTextSource}
diff --git a/packages/docs/static/generated/articles-docs-effects-lens-blur.png b/packages/docs/static/generated/articles-docs-effects-lens-blur.png
new file mode 100644
index 0000000000..df1e9c7836
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-lens-blur.png differ
diff --git a/packages/docs/static/img/effects-lens-blur-preview.png b/packages/docs/static/img/effects-lens-blur-preview.png
new file mode 100644
index 0000000000..f669d07002
Binary files /dev/null and b/packages/docs/static/img/effects-lens-blur-preview.png differ
diff --git a/packages/effects/THIRD_PARTY_LICENSES.md b/packages/effects/THIRD_PARTY_LICENSES.md
index 8f2e486b7e..16df195742 100644
--- a/packages/effects/THIRD_PARTY_LICENSES.md
+++ b/packages/effects/THIRD_PARTY_LICENSES.md
@@ -2,8 +2,8 @@
## EffectCraft
-The Fractal Noise and Turbulent Displace shaders are adapted from the noise
-and distortion engines in
+The Fractal Noise, Turbulent Displace, and Lens Blur shaders are adapted from
+the noise, distortion, and blur engines in
[EffectCraft](https://github.com/storytold/effectcraft), revision
`8f02f52a44a4b1ea807d8824b92301b96f896a06`. It is used under the MIT license.
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index fd038e4cdc..79d6ed0c1b 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -45,6 +45,7 @@ const effectEntrypoints = [
'src/linear-progressive-pixelate.ts',
'src/light-leak.ts',
'src/light-trail.ts',
+ 'src/lens-blur.ts',
'src/levels.ts',
'src/lut.ts',
'src/mirror.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 9e3be7109e..c5aba55882 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -209,6 +209,11 @@
"module": "./dist/esm/linear-progressive-pixelate.mjs",
"import": "./dist/esm/linear-progressive-pixelate.mjs"
},
+ "./lens-blur": {
+ "types": "./dist/lens-blur.d.ts",
+ "module": "./dist/esm/lens-blur.mjs",
+ "import": "./dist/esm/lens-blur.mjs"
+ },
"./levels": {
"types": "./dist/levels.d.ts",
"module": "./dist/esm/levels.mjs",
@@ -533,6 +538,9 @@
"linear-progressive-pixelate": [
"dist/linear-progressive-pixelate.d.ts"
],
+ "lens-blur": [
+ "dist/lens-blur.d.ts"
+ ],
"levels": [
"dist/levels.d.ts"
],
diff --git a/packages/effects/src/lens-blur.ts b/packages/effects/src/lens-blur.ts
new file mode 100644
index 0000000000..a6f77a5762
--- /dev/null
+++ b/packages/effects/src/lens-blur.ts
@@ -0,0 +1,5 @@
+export {
+ lensBlur,
+ type LensBlurParams,
+ type LensBlurIrisShape,
+} from './lens-blur/index.js';
diff --git a/packages/effects/src/lens-blur/index.ts b/packages/effects/src/lens-blur/index.ts
new file mode 100644
index 0000000000..71196329bb
--- /dev/null
+++ b/packages/effects/src/lens-blur/index.ts
@@ -0,0 +1,445 @@
+import type {InteractivitySchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ validateNonNegative,
+ validateUnitInterval,
+} from '../color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertOptionalBoolean,
+} from '../validate-effect-param.js';
+import {LENS_BLUR_FRAGMENT_SHADER} from './shader.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const DEFAULT_RADIUS = 10 as const;
+const DEFAULT_IRIS_SHAPE = 'hexagon' as const;
+const DEFAULT_IRIS_ROUNDNESS = 0 as const;
+const DEFAULT_IRIS_ROTATION = 0 as const;
+const DEFAULT_IRIS_ASPECT_RATIO = 1 as const;
+const DEFAULT_HIGHLIGHT_GAIN = 0 as const;
+const DEFAULT_HIGHLIGHT_THRESHOLD = 1 as const;
+const DEFAULT_HIGHLIGHT_SATURATION = 1 as const;
+const DEFAULT_REPEAT_EDGE_PIXELS = false as const;
+const DEFAULT_SAMPLES = 256 as const;
+const DEFAULT_LINEAR_LIGHT = false as const;
+const IRIS_SHAPES = [
+ 'triangle',
+ 'square',
+ 'pentagon',
+ 'hexagon',
+ 'heptagon',
+ 'octagon',
+ 'nonagon',
+ 'decagon',
+ 'circle',
+] as const;
+
+const lensBlurSchema = {
+ radius: {
+ type: 'number',
+ default: DEFAULT_RADIUS,
+ description: 'Blur radius in pixels',
+ min: 0,
+ max: 200,
+ step: 1,
+ hiddenFromList: false,
+ },
+ irisShape: {
+ type: 'enum',
+ default: DEFAULT_IRIS_SHAPE,
+ description: 'Iris shape',
+ variants: {
+ triangle: {},
+ square: {},
+ pentagon: {},
+ hexagon: {},
+ heptagon: {},
+ octagon: {},
+ nonagon: {},
+ decagon: {},
+ circle: {},
+ },
+ },
+ irisRoundness: {
+ type: 'number',
+ default: DEFAULT_IRIS_ROUNDNESS,
+ description: 'Roundness of the iris, from 0 (polygon) to 1 (circle)',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ },
+ irisRotation: {
+ type: 'rotation-degrees',
+ default: DEFAULT_IRIS_ROTATION,
+ description: 'Clockwise iris rotation in degrees',
+ step: 1,
+ },
+ irisAspectRatio: {
+ type: 'number',
+ default: DEFAULT_IRIS_ASPECT_RATIO,
+ description: 'Horizontal stretch of the iris',
+ min: 0.01,
+ max: 4,
+ step: 0.01,
+ hiddenFromList: false,
+ },
+ highlightGain: {
+ type: 'number',
+ default: DEFAULT_HIGHLIGHT_GAIN,
+ description: 'Additional brightness of highlights, from 0 to 1',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ },
+ highlightThreshold: {
+ type: 'number',
+ default: DEFAULT_HIGHLIGHT_THRESHOLD,
+ description: 'Minimum luminance for highlight gain, from 0 to 1',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ },
+ highlightSaturation: {
+ type: 'number',
+ default: DEFAULT_HIGHLIGHT_SATURATION,
+ description: 'Saturation of added highlight brightness, from 0 to 1',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ },
+ repeatEdgePixels: {
+ type: 'boolean',
+ default: DEFAULT_REPEAT_EDGE_PIXELS,
+ description:
+ 'Repeat edge pixels outside the source instead of sampling transparency',
+ },
+ samples: {
+ type: 'number',
+ default: DEFAULT_SAMPLES,
+ description: 'Number of aperture samples, from 16 to 2048',
+ min: 16,
+ max: 2048,
+ step: 1,
+ hiddenFromList: false,
+ integer: true,
+ },
+ linearLight: {
+ type: 'boolean',
+ default: DEFAULT_LINEAR_LIGHT,
+ description: 'Average colors in linear light',
+ },
+} as const satisfies InteractivitySchema;
+
+export type LensBlurIrisShape = (typeof IRIS_SHAPES)[number];
+
+export type LensBlurParams = {
+ /** Blur radius in pixels. Defaults to `10`. */
+ readonly radius?: number;
+ /** Iris shape. Defaults to `hexagon`. */
+ readonly irisShape?: LensBlurIrisShape;
+ /** Roundness of the iris, from 0 (polygon) to 1 (circle). Defaults to `0`. */
+ readonly irisRoundness?: number;
+ /** Clockwise iris rotation in degrees. Defaults to `0`. */
+ readonly irisRotation?: number;
+ /** Horizontal stretch of the iris. Must be greater than zero. Defaults to `1`. */
+ readonly irisAspectRatio?: number;
+ /** Additional brightness of highlights, from 0 to 1. Defaults to `0`. */
+ readonly highlightGain?: number;
+ /** Minimum luminance for highlight gain, from 0 to 1. Defaults to `1`. */
+ readonly highlightThreshold?: number;
+ /** Saturation of added highlight brightness, from 0 to 1. Defaults to `1`. */
+ readonly highlightSaturation?: number;
+ /** Repeat edge pixels outside the source instead of sampling transparency. Defaults to `false`. */
+ readonly repeatEdgePixels?: boolean;
+ /** Number of aperture samples, from 16 to 2048. Higher values reduce grain. Defaults to `256`. */
+ readonly samples?: number;
+ /** Average colors in linear light. Defaults to `false`. */
+ readonly linearLight?: boolean;
+};
+
+type LensBlurResolved = Required<LensBlurParams>;
+
+const resolve = (p: LensBlurParams): LensBlurResolved => ({
+ radius: p.radius ?? DEFAULT_RADIUS,
+ irisShape: p.irisShape ?? DEFAULT_IRIS_SHAPE,
+ irisRoundness: p.irisRoundness ?? DEFAULT_IRIS_ROUNDNESS,
+ irisRotation: p.irisRotation ?? DEFAULT_IRIS_ROTATION,
+ irisAspectRatio: p.irisAspectRatio ?? DEFAULT_IRIS_ASPECT_RATIO,
+ highlightGain: p.highlightGain ?? DEFAULT_HIGHLIGHT_GAIN,
+ highlightThreshold: p.highlightThreshold ?? DEFAULT_HIGHLIGHT_THRESHOLD,
+ highlightSaturation: p.highlightSaturation ?? DEFAULT_HIGHLIGHT_SATURATION,
+ repeatEdgePixels: p.repeatEdgePixels ?? DEFAULT_REPEAT_EDGE_PIXELS,
+ samples: p.samples ?? DEFAULT_SAMPLES,
+ linearLight: p.linearLight ?? DEFAULT_LINEAR_LIGHT,
+});
+
+const validateLensBlurParams = (params: LensBlurParams): void => {
+ assertEffectParamsObject(params, 'Lens blur');
+ assertOptionalFiniteNumber(params.radius, 'radius');
+ assertOptionalFiniteNumber(params.irisRoundness, 'irisRoundness');
+ assertOptionalFiniteNumber(params.irisRotation, 'irisRotation');
+ assertOptionalFiniteNumber(params.irisAspectRatio, 'irisAspectRatio');
+ assertOptionalFiniteNumber(params.highlightGain, 'highlightGain');
+ assertOptionalFiniteNumber(params.highlightThreshold, 'highlightThreshold');
+ assertOptionalFiniteNumber(params.highlightSaturation, 'highlightSaturation');
+ assertOptionalBoolean(params.repeatEdgePixels, 'repeatEdgePixels');
+ assertOptionalFiniteNumber(params.samples, 'samples');
+ assertOptionalBoolean(params.linearLight, 'linearLight');
+ if (
+ params.irisShape !== undefined &&
+ !IRIS_SHAPES.includes(params.irisShape)
+ ) {
+ throw new TypeError(
+ 'Invalid irisShape: ' + JSON.stringify(params.irisShape),
+ );
+ }
+
+ const r = resolve(params);
+ validateNonNegative(r.radius, 'radius');
+ validateUnitInterval(r.irisRoundness, 'irisRoundness');
+ validateUnitInterval(r.highlightGain, 'highlightGain');
+ validateUnitInterval(r.highlightThreshold, 'highlightThreshold');
+ validateUnitInterval(r.highlightSaturation, 'highlightSaturation');
+ if (r.irisAspectRatio <= 0)
+ throw new TypeError('"irisAspectRatio" must be greater than zero');
+ if (!Number.isInteger(r.samples) || r.samples < 16 || r.samples > 2048)
+ throw new TypeError('"samples" must be an integer between 16 and 2048');
+};
+
+type LensBlurState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly texture: WebGLTexture;
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uResolution: WebGLUniformLocation | null;
+ readonly uRadius: WebGLUniformLocation | null;
+ readonly uIrisShape: WebGLUniformLocation | null;
+ readonly uIrisRoundness: WebGLUniformLocation | null;
+ readonly uIrisRotation: WebGLUniformLocation | null;
+ readonly uIrisAspectRatio: WebGLUniformLocation | null;
+ readonly uHighlightGain: WebGLUniformLocation | null;
+ readonly uHighlightThreshold: WebGLUniformLocation | null;
+ readonly uHighlightSaturation: WebGLUniformLocation | null;
+ readonly uRepeatEdgePixels: WebGLUniformLocation | null;
+ readonly uSamples: WebGLUniformLocation | null;
+ readonly uLinearLight: WebGLUniformLocation | null;
+};
+
+const VERTEX_SHADER = /* glsl */ `#version 300 es
+in vec2 aPos;
+in vec2 aUv;
+out vec2 vUv;
+
+void main() {
+ vUv = aUv;
+ gl_Position = vec4(aPos, 0.0, 1.0);
+}
+`;
+
+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(`LensBlur 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(`LensBlur program link failed: ${log ?? '(no log)'}`);
+ }
+
+ return program;
+};
+
+const setupLensBlur = (target: HTMLCanvasElement): LensBlurState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('lens blur effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const vs = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, LENS_BLUR_FRAGMENT_SHADER);
+ const program = linkProgram(gl, vs, fs);
+ gl.deleteShader(vs);
+ gl.deleteShader(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);
+
+ 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.bindVertexArray(null);
+
+ 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 {
+ gl,
+ program,
+ vao,
+ vbo,
+ texture,
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uResolution: gl.getUniformLocation(program, 'uResolution'),
+ uRadius: gl.getUniformLocation(program, 'uRadius'),
+ uIrisShape: gl.getUniformLocation(program, 'uIrisShape'),
+ uIrisRoundness: gl.getUniformLocation(program, 'uIrisRoundness'),
+ uIrisRotation: gl.getUniformLocation(program, 'uIrisRotation'),
+ uIrisAspectRatio: gl.getUniformLocation(program, 'uIrisAspectRatio'),
+ uHighlightGain: gl.getUniformLocation(program, 'uHighlightGain'),
+ uHighlightThreshold: gl.getUniformLocation(program, 'uHighlightThreshold'),
+ uHighlightSaturation: gl.getUniformLocation(
+ program,
+ 'uHighlightSaturation',
+ ),
+ uRepeatEdgePixels: gl.getUniformLocation(program, 'uRepeatEdgePixels'),
+ uSamples: gl.getUniformLocation(program, 'uSamples'),
+ uLinearLight: gl.getUniformLocation(program, 'uLinearLight'),
+ };
+};
+
+export const lensBlur = createEffect<LensBlurParams, LensBlurState>({
+ type: 'remotion/lens-blur',
+ label: 'lensBlur()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/lens-blur',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `lens-blur-${JSON.stringify(r)}`;
+ },
+ setup: (target) => setupLensBlur(target),
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ const {gl, program, texture, vao} = state;
+
+ gl.viewport(0, 0, width, height);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ source as TexImageSource,
+ );
+
+ gl.useProgram(program);
+ if (state.uSource) gl.uniform1i(state.uSource, 0);
+ if (state.uResolution) gl.uniform2f(state.uResolution, width, height);
+ if (state.uRadius) gl.uniform1f(state.uRadius, r.radius);
+ if (state.uIrisShape)
+ gl.uniform1i(state.uIrisShape, IRIS_SHAPES.indexOf(r.irisShape) + 3);
+ if (state.uIrisRoundness)
+ gl.uniform1f(state.uIrisRoundness, r.irisRoundness);
+ if (state.uIrisRotation)
+ gl.uniform1f(
+ state.uIrisRotation,
+ ((r.irisRotation % 360) * Math.PI) / 180,
+ );
+ if (state.uIrisAspectRatio)
+ gl.uniform1f(state.uIrisAspectRatio, r.irisAspectRatio);
+ if (state.uHighlightGain)
+ gl.uniform1f(state.uHighlightGain, r.highlightGain);
+ if (state.uHighlightThreshold)
+ gl.uniform1f(state.uHighlightThreshold, r.highlightThreshold);
+ if (state.uHighlightSaturation)
+ gl.uniform1f(state.uHighlightSaturation, r.highlightSaturation);
+ if (state.uRepeatEdgePixels)
+ gl.uniform1i(state.uRepeatEdgePixels, r.repeatEdgePixels ? 1 : 0);
+ if (state.uSamples) gl.uniform1i(state.uSamples, r.samples);
+ if (state.uLinearLight)
+ gl.uniform1i(state.uLinearLight, r.linearLight ? 1 : 0);
+
+ gl.bindVertexArray(vao);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ gl.bindVertexArray(null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.useProgram(null);
+ },
+ cleanup: ({gl, program, vao, vbo, texture}) => {
+ gl.deleteTexture(texture);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: lensBlurSchema,
+ validateParams: validateLensBlurParams,
+});
diff --git a/packages/effects/src/lens-blur/shader.ts b/packages/effects/src/lens-blur/shader.ts
new file mode 100644
index 0000000000..84f9c7a235
--- /dev/null
+++ b/packages/effects/src/lens-blur/shader.ts
@@ -0,0 +1,94 @@
+// Aperture geometry and highlight controls adapted from EffectCraft's
+// blur2.rs (MIT). See ../../THIRD_PARTY_LICENSES.md.
+export const LENS_BLUR_FRAGMENT_SHADER = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform vec2 uResolution;
+uniform float uRadius;
+uniform int uIrisShape;
+uniform float uIrisRoundness;
+uniform float uIrisRotation;
+uniform float uIrisAspectRatio;
+uniform float uHighlightGain;
+uniform float uHighlightThreshold;
+uniform float uHighlightSaturation;
+uniform bool uRepeatEdgePixels;
+uniform int uSamples;
+uniform bool uLinearLight;
+
+const float PI = 3.141592653589793;
+const float GOLDEN_ANGLE = 2.399963229728653;
+
+vec3 toLinear(vec3 color) {
+ return mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color));
+}
+
+vec3 toSrgb(vec3 color) {
+ return mix(color * 12.92, 1.055 * pow(max(color, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), color));
+}
+
+vec4 readSource(vec2 uv) {
+ vec4 sampleColor = texture(uSource, uv);
+ if (sampleColor.a <= 0.0) return vec4(0.0);
+ vec3 color = sampleColor.rgb / sampleColor.a;
+ float luminance = dot(color, vec3(0.2126, 0.7152, 0.0722));
+ if (uLinearLight) color = toLinear(color);
+ if (luminance >= uHighlightThreshold) {
+ float brightest = max(color.r, max(color.g, color.b));
+ vec3 highlight = mix(vec3(brightest), color, uHighlightSaturation);
+ color += highlight * (4.0 * uHighlightGain);
+ }
+
+ float coverage = 1.0;
+ if (!uRepeatEdgePixels) {
+ // The texture clamps to its edge texels. Fade their bilinear footprint
+ // against transparent texels beyond the canvas instead of cutting it off.
+ vec2 pixel = uv * uResolution;
+ vec2 nearEdge = clamp(pixel + 0.5, 0.0, 1.0);
+ vec2 farEdge = clamp(uResolution + 0.5 - pixel, 0.0, 1.0);
+ coverage = nearEdge.x * nearEdge.y * farEdge.x * farEdge.y;
+ }
+ return vec4(color * sampleColor.a, sampleColor.a) * coverage;
+}
+
+void main() {
+ // A zero radius must be an exact identity, including with highlight gain.
+ if (uRadius == 0.0) {
+ fragColor = texture(uSource, vUv);
+ return;
+ }
+
+ vec4 sum = vec4(0.0);
+ float totalWeight = 0.0;
+ for (int i = 0; i < 2048; i++) {
+ if (i >= uSamples) break;
+ float angle = float(i) * GOLDEN_ANGLE;
+ float boundary = 1.0;
+ if (uIrisShape < 11) {
+ float halfSector = PI / float(uIrisShape);
+ float localAngle = mod(angle + PI / 2.0, 2.0 * halfSector) - halfSector;
+ float polygon = cos(halfSector) / cos(localAngle);
+ boundary = mix(polygon, 1.0, uIrisRoundness);
+ }
+ float distance = sqrt((float(i) + 0.5) / float(uSamples)) * boundary;
+ float rotatedAngle = angle + uIrisRotation;
+ vec2 offset = vec2(cos(rotatedAngle) * uIrisAspectRatio, -sin(rotatedAngle)) * distance * uRadius;
+ // Radially mapping a disc onto a polygon changes area by boundary^2.
+ // Weight by that Jacobian to keep the aperture uniformly illuminated.
+ float weight = boundary * boundary;
+ sum += readSource(vUv - offset / uResolution) * weight;
+ totalWeight += weight;
+ }
+
+ vec4 color = sum / totalWeight;
+ if (uLinearLight && color.a > 0.0) {
+ color.rgb = toSrgb(color.rgb / color.a) * color.a;
+ }
+ // Keep the result premultiplied even when highlights exceed display white.
+ fragColor = vec4(clamp(color.rgb, vec3(0.0), vec3(color.a)), color.a);
+}
+`;
diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.ts
index 960f895944..07067a3723 100644
--- a/packages/studio-shared/src/effect-catalog.ts
+++ b/packages/studio-shared/src/effect-catalog.ts
@@ -301,6 +301,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [
},
},
},
+ {
+ id: 'effects-lens-blur',
+ category: 'Blur & Shadow',
+ label: 'lensBlur()',
+ description: 'Camera defocus with shaped bokeh',
+ effect: {
+ name: 'lensBlur',
+ importPath: '@remotion/effects/lens-blur',
+ config: {},
+ },
+ },
{
id: 'effects-linear-progressive-blur',
category: 'Blur & Shadow',