Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/effects`: `duotone()` effect (#7683)

Jonny Burger4ebb86d21cfd
diff --git a/.agents/skills/add-effect/SKILL.md b/.agents/skills/add-effect/SKILL.md
new file mode 100644
index 0000000000..d1a04e959f
--- /dev/null
+++ b/.agents/skills/add-effect/SKILL.md
@@ -0,0 +1,359 @@
+---
+name: add-effect
+description: Add a new effect to @remotion/effects, including implementation, package exports, docs, demos, preview images, tests, formatting, and builds.
+---
+
+# Add a new `@remotion/effects` effect
+
+Use this skill when adding a new effect to `@remotion/effects`.
+
+## 1. Pick the effect shape
+
+- Prefer the WebGL2 backend for new effects. Use 2D only when WebGL cannot express the effect.
+- Use a single file at `packages/effects/src/<effect-name>.ts` for simple effects.
+- Use a folder at `packages/effects/src/<effect-name>/` plus a top-level re-export file when the effect needs multiple shaders, runtime helpers, or multiple files.
+- Follow naming already used by the package:
+ - File/subpath: kebab-case (`chromatic-aberration`)
+ - Function: camelCase (`chromaticAberration`)
+ - Type: PascalCase params (`ChromaticAberrationParams`)
+ - Effect type string: `remotion/<kebab-case-name>`
+
+## 2. Implement the effect
+
+In the effect file:
+
+- Import `SequenceSchema` and `Internals` from `remotion`.
+- Use `const {createEffect, createWebGL2ContextError} = Internals;`.
+- Define defaults as `const` values.
+- Define a schema with `satisfies SequenceSchema`; these fields appear in Studio visual editing.
+- Export the params type.
+- Resolve defaults in a `resolve()` helper.
+- Validate params using helpers from:
+ - `packages/effects/src/validate-effect-param.ts`
+ - `packages/effects/src/color-utils.ts`
+- Throw `createWebGL2ContextError('<effect name> effect')` if WebGL2 cannot be acquired.
+- Set `documentationLink` to `https://www.remotion.dev/docs/effects/<slug>`.
+- Include every resolved parameter in `calculateKey()`.
+
+For WebGL2 effects, use this general structure:
+
+```ts
+import type {SequenceSchema} from 'remotion';
+import {Internals} from 'remotion';
+import {assertOptionalFiniteNumber, validateUnitInterval} from './color-utils.js';
+import {assertEffectParamsObject} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const DEFAULT_AMOUNT = 1 as const;
+
+const myEffectSchema = {
+ amount: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_AMOUNT,
+ description: 'Amount',
+ },
+} as const satisfies SequenceSchema;
+
+export type MyEffectParams = {
+ readonly amount?: number;
+};
+
+type MyEffectResolved = {
+ amount: number;
+};
+
+const resolve = (p: MyEffectParams): MyEffectResolved => ({
+ amount: p.amount ?? DEFAULT_AMOUNT,
+});
+
+const validateMyEffectParams = (params: MyEffectParams): void => {
+ assertEffectParamsObject(params, 'My effect');
+ assertOptionalFiniteNumber(params.amount, 'amount');
+ validateUnitInterval(params.amount ?? DEFAULT_AMOUNT, 'amount');
+};
+
+type MyEffectState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly texture: WebGLTexture;
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uAmount: 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 FRAGMENT_SHADER = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform float uAmount;
+
+void main() {
+ vec4 color = texture(uSource, vUv);
+ fragColor = vec4(color.rgb * uAmount, color.a);
+}
+`;
+
+// Follow existing helpers in halftone.ts or a runtime file for shader
+// compilation, program linking, fullscreen-quad setup, and texture setup.
+
+export const myEffect = createEffect<MyEffectParams, MyEffectState>({
+ type: 'remotion/my-effect',
+ label: 'My Effect',
+ documentationLink: 'https://www.remotion.dev/docs/effects/my-effect',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `my-effect-${r.amount}`;
+ },
+ setup: (target) => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('my effect effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ return createMyEffectState(gl, VERTEX_SHADER, FRAGMENT_SHADER);
+ },
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+
+ state.gl.viewport(0, 0, width, height);
+ state.gl.bindFramebuffer(state.gl.FRAMEBUFFER, null);
+ state.gl.activeTexture(state.gl.TEXTURE0);
+ state.gl.bindTexture(state.gl.TEXTURE_2D, state.texture);
+ state.gl.pixelStorei(state.gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);
+ state.gl.texImage2D(
+ state.gl.TEXTURE_2D,
+ 0,
+ state.gl.RGBA,
+ state.gl.RGBA,
+ state.gl.UNSIGNED_BYTE,
+ source as TexImageSource,
+ );
+
+ state.gl.useProgram(state.program);
+ if (state.uSource) state.gl.uniform1i(state.uSource, 0);
+ if (state.uAmount) state.gl.uniform1f(state.uAmount, r.amount);
+ state.gl.bindVertexArray(state.vao);
+ state.gl.drawArrays(state.gl.TRIANGLE_STRIP, 0, 4);
+ },
+ cleanup: ({gl, program, vao, vbo, texture}) => {
+ gl.deleteTexture(texture);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: myEffectSchema,
+ validateParams: validateMyEffectParams,
+});
+```
+
+Look at existing WebGL2 effects such as `halftone.ts`,
+`blur/blur-runtime.ts`, `chromatic-aberration/chromatic-aberration-runtime.ts`,
+and `wave/wave-runtime.ts` before adding new helpers. In the template above,
+`createMyEffectState()` stands for the shader compilation, program linking,
+fullscreen-quad, texture, and uniform-location setup used by those files.
+
+## 3. Register package entry points
+
+Update:
+
+- `packages/effects/bundle.ts` β€” add the new `src/<effect-name>.ts` entrypoint.
+- `packages/effects/package.json`:
+ - Add `exports["./<effect-name>"]`.
+ - Add the `typesVersions` entry.
+
+If using a folder implementation, add a top-level file that re-exports from the folder:
+
+```ts
+export {myEffect, type MyEffectParams} from './my-effect/index.js';
+```
+
+## 4. Add tests
+
+Update `packages/effects/src/test/effect-params.test.ts`:
+
+- Import the new effect.
+- Add it to the documentation link test.
+- Test default params when all fields are optional.
+- Test required params if any are required.
+- Test invalid values and exact error substrings.
+- Test that meaningful params produce distinct `effectKey` values.
+
+Run:
+
+```bash
+cd packages/effects
+bun test src/test
+bunx turbo make --filter="@remotion/effects"
+```
+
+## 5. Add docs
+
+Create `packages/docs/docs/effects/<effect-name>.mdx`.
+
+Follow existing effect pages:
+
+- Frontmatter: `slug`, `title`, `sidebar_label`, `crumb: '@remotion/effects'`.
+- Add `image:` only after running `bun render-cards.ts`.
+- H1: `# effectName()<AvailableFrom v="..." />`.
+- Include `_Part of the [@remotion/effects](/docs/effects/api) package._`.
+- Add a short description.
+- Add `<Demo type="effects-<effect-name>" />`.
+- Add a twoslash example with `title="MyComp.tsx"`.
+- Document each option as its own `###` heading, using `?` for optional parameters.
+- Add a `disabled?` section.
+- Add a See also section.
+
+Update:
+
+- `packages/docs/sidebars.ts` β€” add `'effects/<effect-name>'`.
+- `packages/docs/docs/effects/table-of-contents.tsx` β€” add a card in the right category.
+- `packages/docs/src/data/articles.ts` by running the card generator, not by hand.
+
+Use the `writing-docs` skill for documentation wording.
+
+## 6. Add the interactive docs demo
+
+Create `packages/docs/components/effects/effects-<effect-name>-preview.tsx`.
+
+Use the same preview source as other effects:
+
+```tsx
+import {myEffect} from '@remotion/effects/my-effect';
+import React from 'react';
+import {CanvasImage} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const EffectsMyEffectPreview: React.FC<{
+ readonly amount: number;
+}> = ({amount}) => {
+ return (
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ effects={[myEffect({amount})]}
+ />
+ );
+};
+```
+
+Register the demo:
+
+- `packages/docs/components/demos/types.ts`
+ - Import the preview component.
+ - Export `effectsMyEffectDemo`.
+ - Use `id: 'effects-<effect-name>'`.
+ - Add controls matching the effect schema.
+- `packages/docs/components/demos/index.tsx`
+ - Import and add the demo to the `demos` array.
+
+Use the `docs-demo` skill for demo details.
+
+## 7. Render the table-of-contents preview image
+
+The TOC card should use a rendered image from the same preview component, not a hand-written SVG.
+
+Create a temporary Remotion entry point for the still render and delete it before committing:
+
+```tsx
+import React from 'react';
+import {Composition, registerRoot} from 'remotion';
+import {EffectsMyEffectPreview} from '../../components/effects/effects-my-effect-preview';
+
+const Root: React.FC = () => {
+ return (
+ <Composition
+ id="effects-my-effect-preview"
+ component={EffectsMyEffectPreview}
+ width={1080}
+ height={720}
+ fps={30}
+ durationInFrames={1}
+ defaultProps={{
+ amount: 1,
+ }}
+ />
+ );
+};
+
+registerRoot(Root);
+```
+
+Then render from `packages/docs`:
+
+```bash
+npx --no-install --package @remotion/cli remotion still src/remotion/effects-preview-entry.tsx effects-my-effect-preview static/img/effects-my-effect-preview.jpg --overwrite --image-format=jpeg
+```
+
+Add the rendered image to `packages/docs/static/img/`, reference it from `table-of-contents.tsx`, and delete the temporary entry point before committing.
+
+## 8. Generate docs card
+
+Run:
+
+```bash
+cd packages/docs
+bun render-cards.ts
+```
+
+Commit the generated `packages/docs/static/generated/articles-docs-effects-<effect-name>.png` and the new `image:` frontmatter line.
+
+If `render-cards.ts` opportunistically generates unrelated missing cards, remove those unrelated files unless they belong to the current change.
+
+## 9. Format, build, and verify
+
+Run:
+
+```bash
+cd packages/effects
+bunx oxfmt src --write
+cd ../..
+bun run build
+bun run formatting
+```
+
+If the change touches docs source, `bun run formatting` covers `packages/docs/src`. For MDX-only edits, do not run formatters on docs pages.
+
+Before committing, check:
+
+```bash
+git diff --check
+git status --short
+```
+
+## Common pitfalls
+
+- Do not forget `package.json` `exports` and `typesVersions`; subpath imports like `@remotion/effects/my-effect` depend on them.
+- Do not forget `bundle.ts`; otherwise the ESM subpath will not be built.
+- Do not leave temporary render entry points in `packages/docs/src/remotion`.
+- Do not use a hand-written SVG for the effect TOC preview.
+- Preserve alpha unless the effect intentionally changes it.
+- For pixel math, be aware canvases store premultiplied alpha.
+- WebGL color math often needs to unpremultiply the sampled RGB before luminance
+ or threshold calculations, then premultiply the output RGB again.
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index d2bc5f6a95..b25e0c7f50 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -22,6 +22,7 @@ import {
effectsBrightnessDemo,
effectsChromaticAberrationDemo,
effectsContrastDemo,
+ effectsDuotoneDemo,
effectsGrayscaleDemo,
effectsHalftoneDemo,
effectsHueDemo,
@@ -89,6 +90,7 @@ const demos: DemoType[] = [
noiseDemo,
effectsBrightnessDemo,
effectsContrastDemo,
+ effectsDuotoneDemo,
effectsGrayscaleDemo,
effectsHueDemo,
effectsInvertDemo,
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 2d89378bf4..db739dd5bd 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -4,6 +4,7 @@ import {EffectsBlurPreview} from '../effects/effects-blur-preview';
import {EffectsBrightnessPreview} from '../effects/effects-brightness-preview';
import {EffectsChromaticAberrationPreview} from '../effects/effects-chromatic-aberration-preview';
import {EffectsContrastPreview} from '../effects/effects-contrast-preview';
+import {EffectsDuotonePreview} from '../effects/effects-duotone-preview';
import {EffectsGrayscalePreview} from '../effects/effects-grayscale-preview';
import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';
import {EffectsHuePreview} from '../effects/effects-hue-preview';
@@ -1499,6 +1500,41 @@ export const effectsGrayscaleDemo: DemoType = {
],
};
+export const effectsDuotoneDemo: DemoType = {
+ comp: EffectsDuotonePreview,
+ compHeight: 720,
+ compWidth: 1280,
+ durationInFrames: 1,
+ fps: 30,
+ id: 'effects-duotone',
+ autoPlay: false,
+ controls: false,
+ logLevel: 'info',
+ options: [
+ {
+ name: 'darkColor',
+ type: 'color',
+ default: 'black',
+ optional: 'no',
+ },
+ {
+ name: 'lightColor',
+ type: 'color',
+ default: 'white',
+ optional: 'no',
+ },
+ {
+ name: 'threshold',
+ type: 'numeric',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: 0.18,
+ optional: 'no',
+ },
+ ],
+};
+
export const effectsHueDemo: DemoType = {
comp: EffectsHuePreview,
compHeight: 720,
diff --git a/packages/docs/components/effects/effects-duotone-preview.tsx b/packages/docs/components/effects/effects-duotone-preview.tsx
new file mode 100644
index 0000000000..e83f1355bc
--- /dev/null
+++ b/packages/docs/components/effects/effects-duotone-preview.tsx
@@ -0,0 +1,19 @@
+import {duotone} from '@remotion/effects/duotone';
+import React from 'react';
+import {CanvasImage} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const EffectsDuotonePreview: React.FC<{
+ readonly darkColor: string;
+ readonly lightColor: string;
+ readonly threshold: number;
+}> = ({darkColor, lightColor, threshold}) => {
+ return (
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ effects={[duotone({darkColor, lightColor, threshold})]}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/duotone.mdx b/packages/docs/docs/effects/duotone.mdx
new file mode 100644
index 0000000000..aa176b1c82
--- /dev/null
+++ b/packages/docs/docs/effects/duotone.mdx
@@ -0,0 +1,77 @@
+---
+image: /generated/articles-docs-effects-duotone.png
+slug: /effects/duotone
+title: duotone()
+sidebar_label: duotone()
+crumb: '@remotion/effects'
+---
+
+# duotone()<AvailableFrom v="4.0.468" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+A duotone effect that maps every non-transparent pixel to one of two colors based on its luminance. It can be applied to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).
+
+The source alpha channel is preserved, so transparent and semi-transparent regions keep their original transparency.
+
+## Preview
+
+<Demo type="effects-duotone" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill} from 'remotion';
+import {Video} from '@remotion/media';
+import {duotone} from '@remotion/effects/duotone';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ duotone({
+ darkColor: 'black',
+ lightColor: 'white',
+ threshold: 0.18,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. You can also call `duotone()` without arguments.
+
+### `darkColor?`
+
+Color used for pixels below the luminance threshold. Accepts any CSS color string. Defaults to `'#000000'`.
+
+### `lightColor?`
+
+Color used for pixels at or above the luminance threshold. Accepts any CSS color string. Defaults to `'#ffffff'`.
+
+### `threshold?`
+
+Luminance threshold from `0` to `1`. Defaults to `0.5`.
+
+Lower values assign more pixels to `lightColor`; higher values assign more pixels to `darkColor`.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`duotone()` 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)
+- [`grayscale()`](/docs/effects/grayscale)
+- [`tint()`](/docs/effects/tint)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/duotone.ts)
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index f22870966a..e542ec8197 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -31,6 +31,13 @@ const categories: {
name: 'contrast()',
description: 'Contrast adjustment effect',
},
+ {
+ link: '/docs/effects/duotone',
+ preview: '/img/effects-duotone-preview.jpg',
+ alt: 'duotone effect preview',
+ name: 'duotone()',
+ description: 'Two-color threshold effect',
+ },
{
link: '/docs/effects/grayscale',
preview: '/img/effects-grayscale-preview.jpg',
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index ef58a70ff8..4d8307f08b 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -273,6 +273,7 @@ const sidebars: SidebarsConfig = {
'effects/brightness',
'effects/chromatic-aberration',
'effects/contrast',
+ 'effects/duotone',
'effects/grayscale',
'effects/halftone',
'effects/hue',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 41992cdba1..f584e1ad70 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1763,6 +1763,15 @@ export const articles = [
noAi: false,
slug: 'effects/contrast',
},
+ {
+ id: 'effects/duotone',
+ title: 'duotone()',
+ relativePath: 'docs/effects/duotone.mdx',
+ compId: 'articles-docs-effects-duotone',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/duotone',
+ },
{
id: 'effects/grayscale',
title: 'grayscale()',
diff --git a/packages/docs/static/generated/articles-docs-effects-duotone.png b/packages/docs/static/generated/articles-docs-effects-duotone.png
new file mode 100644
index 0000000000..0b10242cb2
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-duotone.png differ
diff --git a/packages/docs/static/img/effects-duotone-preview.jpg b/packages/docs/static/img/effects-duotone-preview.jpg
new file mode 100644
index 0000000000..4fa45213fd
Binary files /dev/null and b/packages/docs/static/img/effects-duotone-preview.jpg differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index e8f3f1ecca..f0d84f006c 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -12,6 +12,7 @@ const effectEntrypoints = [
'src/chromatic-aberration.ts',
'src/brightness.ts',
'src/contrast.ts',
+ 'src/duotone.ts',
'src/grayscale.ts',
'src/halftone.ts',
'src/hue.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 4aec2bb078..f26d5c9360 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -57,6 +57,11 @@
"module": "./dist/esm/contrast.mjs",
"import": "./dist/esm/contrast.mjs"
},
+ "./duotone": {
+ "types": "./dist/duotone.d.ts",
+ "module": "./dist/esm/duotone.mjs",
+ "import": "./dist/esm/duotone.mjs"
+ },
"./halftone": {
"types": "./dist/halftone.d.ts",
"module": "./dist/esm/halftone.mjs",
@@ -126,6 +131,9 @@
"contrast": [
"dist/contrast.d.ts"
],
+ "duotone": [
+ "dist/duotone.d.ts"
+ ],
"halftone": [
"dist/halftone.d.ts"
],
diff --git a/packages/effects/src/color-utils.ts b/packages/effects/src/color-utils.ts
index b6a258448e..f285561375 100644
--- a/packages/effects/src/color-utils.ts
+++ b/packages/effects/src/color-utils.ts
@@ -91,3 +91,16 @@ export const validateSignedUnitInterval = (
export const clampColorChannel = (value: number): number => {
return Math.max(0, Math.min(255, value));
};
+
+export type ParsedColorRgba = readonly [number, number, number, number];
+
+export const parseColorRgba = (
+ ctx: CanvasRenderingContext2D,
+ color: string,
+): ParsedColorRgba => {
+ ctx.clearRect(0, 0, 1, 1);
+ ctx.fillStyle = color;
+ ctx.fillRect(0, 0, 1, 1);
+ const {data} = ctx.getImageData(0, 0, 1, 1);
+ return [data[0], data[1], data[2], data[3]];
+};
diff --git a/packages/effects/src/duotone.ts b/packages/effects/src/duotone.ts
new file mode 100644
index 0000000000..5ce48e226a
--- /dev/null
+++ b/packages/effects/src/duotone.ts
@@ -0,0 +1,362 @@
+import type {SequenceSchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ parseColorRgba,
+ type ParsedColorRgba,
+ validateUnitInterval,
+} from './color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertOptionalColor,
+} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const DEFAULT_DARK_COLOR = '#000000' as const;
+const DEFAULT_LIGHT_COLOR = '#ffffff' as const;
+const DEFAULT_LUMINANCE_THRESHOLD = 0.5 as const;
+
+export const duotoneSchema = {
+ darkColor: {
+ type: 'color',
+ default: DEFAULT_DARK_COLOR,
+ description: 'Dark color',
+ },
+ lightColor: {
+ type: 'color',
+ default: DEFAULT_LIGHT_COLOR,
+ description: 'Light color',
+ },
+ threshold: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_LUMINANCE_THRESHOLD,
+ description: 'Luminance threshold',
+ },
+} as const satisfies SequenceSchema;
+
+export type DuotoneParams = {
+ /** Color used for pixels below the luminance threshold. Defaults to black. */
+ readonly darkColor?: string;
+ /** Color used for pixels at or above the luminance threshold. Defaults to white. */
+ readonly lightColor?: string;
+ /** Luminance threshold from `0` to `1`. Defaults to `0.5`. */
+ readonly threshold?: number;
+};
+
+type DuotoneResolved = {
+ darkColor: string;
+ lightColor: string;
+ threshold: number;
+};
+
+type DuotoneState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly textureSource: WebGLTexture;
+ readonly uniforms: {
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uDarkColor: WebGLUniformLocation | null;
+ readonly uLightColor: WebGLUniformLocation | null;
+ readonly uThreshold: WebGLUniformLocation | null;
+ };
+ readonly colorCtx: CanvasRenderingContext2D;
+ cachedDarkColor: string;
+ cachedDarkColorRgba: ParsedColorRgba;
+ cachedLightColor: string;
+ cachedLightColorRgba: ParsedColorRgba;
+};
+
+const resolve = (p: DuotoneParams): DuotoneResolved => ({
+ darkColor: p.darkColor ?? DEFAULT_DARK_COLOR,
+ lightColor: p.lightColor ?? DEFAULT_LIGHT_COLOR,
+ threshold: p.threshold ?? DEFAULT_LUMINANCE_THRESHOLD,
+});
+
+const validateDuotoneParams = (params: DuotoneParams): void => {
+ assertEffectParamsObject(params, 'Duotone');
+ assertOptionalColor(params.darkColor, 'darkColor');
+ assertOptionalColor(params.lightColor, 'lightColor');
+ assertOptionalFiniteNumber(params.threshold, 'threshold');
+
+ const {threshold} = resolve(params);
+ validateUnitInterval(threshold, 'threshold');
+};
+
+const DUOTONE_VS = /* 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 DUOTONE_FS = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform vec3 uDarkColor;
+uniform vec3 uLightColor;
+uniform float uThreshold;
+
+void main() {
+ vec4 texColor = texture(uSource, vUv);
+ float alpha = texColor.a;
+
+ if (alpha <= 0.001) {
+ fragColor = vec4(0.0);
+ return;
+ }
+
+ vec3 rgb = texColor.rgb / alpha;
+ float luminance = dot(rgb, vec3(0.299, 0.587, 0.114));
+ vec3 duotoneColor = luminance < uThreshold ? uDarkColor : uLightColor;
+
+ fragColor = vec4(duotoneColor * alpha, alpha);
+}
+`;
+
+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(`Duotone 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(`Duotone 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;
+};
+
+const setupDuotone = (target: HTMLCanvasElement): DuotoneState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('duotone effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const program = createProgram(gl, DUOTONE_VS, DUOTONE_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 textureSource = createRgbaTexture(gl);
+
+ const colorCanvas = document.createElement('canvas');
+ colorCanvas.width = 1;
+ colorCanvas.height = 1;
+ const colorCtx = colorCanvas.getContext('2d', {willReadFrequently: true});
+ if (!colorCtx) {
+ throw new Error('Failed to acquire 2D context for color parsing');
+ }
+
+ return {
+ gl,
+ program,
+ vao,
+ vbo,
+ textureSource,
+ uniforms: {
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uDarkColor: gl.getUniformLocation(program, 'uDarkColor'),
+ uLightColor: gl.getUniformLocation(program, 'uLightColor'),
+ uThreshold: gl.getUniformLocation(program, 'uThreshold'),
+ },
+ colorCtx,
+ cachedDarkColor: '',
+ cachedDarkColorRgba: [0, 0, 0, 255],
+ cachedLightColor: '',
+ cachedLightColorRgba: [255, 255, 255, 255],
+ };
+};
+
+const normalizedRgb = (
+ color: ParsedColorRgba,
+): readonly [number, number, number] => {
+ return [color[0] / 255, color[1] / 255, color[2] / 255];
+};
+
+const getParsedColors = (
+ state: DuotoneState,
+ resolved: DuotoneResolved,
+): {
+ dark: ParsedColorRgba;
+ light: ParsedColorRgba;
+} => {
+ if (state.cachedDarkColor !== resolved.darkColor) {
+ state.cachedDarkColor = resolved.darkColor;
+ state.cachedDarkColorRgba = parseColorRgba(
+ state.colorCtx,
+ resolved.darkColor,
+ );
+ }
+
+ if (state.cachedLightColor !== resolved.lightColor) {
+ state.cachedLightColor = resolved.lightColor;
+ state.cachedLightColorRgba = parseColorRgba(
+ state.colorCtx,
+ resolved.lightColor,
+ );
+ }
+
+ return {
+ dark: state.cachedDarkColorRgba,
+ light: state.cachedLightColorRgba,
+ };
+};
+
+export const duotone = createEffect<DuotoneParams, DuotoneState>({
+ type: 'remotion/duotone',
+ label: 'Duotone',
+ documentationLink: 'https://www.remotion.dev/docs/effects/duotone',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `duotone-${r.darkColor}-${r.lightColor}-${r.threshold}`;
+ },
+ setup: (target) => setupDuotone(target),
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ const {dark, light} = getParsedColors(state, r);
+ const [dr, dg, db] = normalizedRgb(dark);
+ const [lr, lg, lb] = normalizedRgb(light);
+ const {gl, program, textureSource, uniforms, 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, textureSource);
+ 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 (uniforms.uSource) gl.uniform1i(uniforms.uSource, 0);
+ if (uniforms.uDarkColor) gl.uniform3f(uniforms.uDarkColor, dr, dg, db);
+ if (uniforms.uLightColor) gl.uniform3f(uniforms.uLightColor, lr, lg, lb);
+ if (uniforms.uThreshold) gl.uniform1f(uniforms.uThreshold, r.threshold);
+
+ 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, textureSource}) => {
+ gl.deleteTexture(textureSource);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: duotoneSchema,
+ validateParams: validateDuotoneParams,
+});
diff --git a/packages/effects/src/halftone.ts b/packages/effects/src/halftone.ts
index fc7ff68b39..dbb0e4a048 100644
--- a/packages/effects/src/halftone.ts
+++ b/packages/effects/src/halftone.ts
@@ -1,7 +1,14 @@
import type {SequenceSchema} from 'remotion';
import {Internals} from 'remotion';
-import {assertOptionalFiniteNumber} from './color-utils.js';
-import {assertEffectParamsObject} from './validate-effect-param.js';
+import {
+ assertOptionalFiniteNumber,
+ parseColorRgba,
+ type ParsedColorRgba,
+} from './color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertOptionalColor,
+} from './validate-effect-param.js';
const {createEffect, createWebGL2ContextError} = Internals;
const HALFTONE_SHAPES = ['circle', 'square', 'line'] as const;
@@ -163,18 +170,6 @@ const assertOptionalBoolean = (value: unknown, name: string): void => {
}
};
-const assertOptionalColor = (value: unknown, name: string): void => {
- if (value === undefined) {
- return;
- }
-
- if (typeof value !== 'string' || value.length === 0) {
- throw new TypeError(
- `"${name}" must be a non-empty string, but got ${JSON.stringify(value)}`,
- );
- }
-};
-
const resolve = (p: HalftoneParams): HalftoneResolved => ({
shape: p.shape ?? 'circle',
dotSize: p.dotSize ?? 20,
@@ -333,7 +328,7 @@ type HalftoneState = {
uUseSourceColor: WebGLUniformLocation | null;
colorCtx: CanvasRenderingContext2D;
cachedColorStr: string;
- cachedColorRgba: [number, number, number, number];
+ cachedColorRgba: ParsedColorRgba;
};
const SHAPE_INDEX: Record<HalftoneShape, number> = {
@@ -385,17 +380,6 @@ const linkProgram = (
return program;
};
-const parseColorRgba = (
- ctx: CanvasRenderingContext2D,
- color: string,
-): [number, number, number, number] => {
- ctx.clearRect(0, 0, 1, 1);
- ctx.fillStyle = color;
- ctx.fillRect(0, 0, 1, 1);
- const {data} = ctx.getImageData(0, 0, 1, 1);
- return [data[0] / 255, data[1] / 255, data[2] / 255, data[3] / 255];
-};
-
// Halftone effect (WebGL2). Converts luminance into a grid of dots, squares,
// or lines. Each fragment determines its nearest grid cell and whether it falls
// inside a dot, so edge dots are never culled. `dotSpacing` sets the grid pitch
@@ -495,7 +479,7 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
uUseSourceColor: gl.getUniformLocation(program, 'uUseSourceColor'),
colorCtx,
cachedColorStr: '',
- cachedColorRgba: [0, 0, 0, 1] as [number, number, number, number],
+ cachedColorRgba: [0, 0, 0, 255],
};
},
apply: ({source, width, height, params, state, flipSourceY}) => {
@@ -508,6 +492,7 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
}
const [cr, cg, cb, ca] = state.cachedColorRgba;
+ const caNormalized = ca / 255;
const filter = r.sampling === 'nearest' ? gl.NEAREST : gl.LINEAR;
@@ -539,7 +524,14 @@ export const halftone = createEffect<HalftoneParams, HalftoneState>({
if (state.uRotation)
gl.uniform1f(state.uRotation, (r.rotation * Math.PI) / 180);
if (state.uOffset) gl.uniform2f(state.uOffset, r.offsetX, r.offsetY);
- if (state.uColor) gl.uniform4f(state.uColor, cr * ca, cg * ca, cb * ca, ca);
+ if (state.uColor)
+ gl.uniform4f(
+ state.uColor,
+ (cr / 255) * caNormalized,
+ (cg / 255) * caNormalized,
+ (cb / 255) * caNormalized,
+ caNormalized,
+ );
if (state.uShape) gl.uniform1i(state.uShape, SHAPE_INDEX[r.shape]);
if (state.uShadeOutside)
gl.uniform1i(state.uShadeOutside, r.invert ? 1 : 0);
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index 3e19b46d5d..e368aca68d 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -4,6 +4,7 @@ import {blur} from '../blur/index.js';
import {brightness} from '../brightness.js';
import {chromaticAberration} from '../chromatic-aberration/index.js';
import {contrast} from '../contrast.js';
+import {duotone} from '../duotone.js';
import {grayscale} from '../grayscale.js';
import {halftone} from '../halftone.js';
import {hue} from '../hue.js';
@@ -31,6 +32,9 @@ test('@remotion/effects expose documentation links', () => {
expect(contrast().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/contrast',
);
+ expect(duotone().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/duotone',
+ );
expect(grayscale().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/grayscale',
);
@@ -299,6 +303,63 @@ test('contrast() amount produces distinct effect keys', () => {
).toBe(3);
});
+test('duotone() accepts default params', () => {
+ expect(() => duotone()).not.toThrow();
+});
+
+test('duotone() accepts valid params', () => {
+ expect(() =>
+ duotone({
+ darkColor: '#111111',
+ lightColor: '#eeeeee',
+ threshold: 0.4,
+ }),
+ ).not.toThrow();
+});
+
+test('duotone() rejects empty darkColor strings', () => {
+ expect(() => duotone({darkColor: ''})).toThrow(
+ '"darkColor" must be a non-empty string, but got ""',
+ );
+});
+
+test('duotone() rejects empty lightColor strings', () => {
+ expect(() => duotone({lightColor: ''})).toThrow(
+ '"lightColor" must be a non-empty string, but got ""',
+ );
+});
+
+test('duotone() rejects non-finite threshold', () => {
+ expect(() => duotone({threshold: Number.NaN})).toThrow(
+ '"threshold" must be a finite number',
+ );
+});
+
+test('duotone() rejects threshold below range', () => {
+ expect(() => duotone({threshold: -0.1})).toThrow('"threshold" must be >= 0');
+});
+
+test('duotone() rejects threshold above range', () => {
+ expect(() => duotone({threshold: 1.1})).toThrow('"threshold" must be <= 1');
+});
+
+test('duotone() parameters produce distinct effect keys', () => {
+ const defaultDuotone = duotone();
+ const shiftedThreshold = duotone({threshold: 0.25});
+ const customColors = duotone({
+ darkColor: '#123456',
+ lightColor: '#abcdef',
+ });
+
+ expect(
+ new Set([
+ defaultDuotone.effectKey,
+ shiftedThreshold.effectKey,
+ customColors.effectKey,
+ ]).size,
+ ).toBe(3);
+});
+
test('halftone() accepts default params', () => {
expect(() => halftone()).not.toThrow();
});
diff --git a/packages/effects/src/validate-effect-param.ts b/packages/effects/src/validate-effect-param.ts
index ef21742908..209ba50672 100644
--- a/packages/effects/src/validate-effect-param.ts
+++ b/packages/effects/src/validate-effect-param.ts
@@ -27,3 +27,11 @@ export const assertRequiredColor = (value: unknown, name: string): void => {
);
}
};
+
+export const assertOptionalColor = (value: unknown, name: string): void => {
+ if (value === undefined) {
+ return;
+ }
+
+ assertRequiredColor(value, name);
+};
diff --git a/packages/example/src/HtmlInCanvas/effects-duotone-preview.tsx b/packages/example/src/HtmlInCanvas/effects-duotone-preview.tsx
new file mode 100644
index 0000000000..620214c965
--- /dev/null
+++ b/packages/example/src/HtmlInCanvas/effects-duotone-preview.tsx
@@ -0,0 +1,24 @@
+import {duotone} from '@remotion/effects/duotone';
+import React from 'react';
+import {HtmlInCanvas, useVideoConfig} from 'remotion';
+import {EffectsPreviewImage} from './effects-preview-image';
+
+export const EffectsDuotonePreview: React.FC = () => {
+ const {width, height} = useVideoConfig();
+
+ return (
+ <HtmlInCanvas
+ width={width}
+ height={height}
+ effects={[
+ duotone({
+ darkColor: 'black',
+ lightColor: 'white',
+ threshold: 0.18,
+ }),
+ ]}
+ >
+ <EffectsPreviewImage />
+ </HtmlInCanvas>
+ );
+};
diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsx
index c7561a2ba8..a89a0eb304 100644
--- a/packages/example/src/HtmlInCanvas/index.tsx
+++ b/packages/example/src/HtmlInCanvas/index.tsx
@@ -27,6 +27,7 @@ export {HtmlInCanvasDocsDemo2DBlur} from './docs-demo-2d-blur';
export {EffectsBlurPreview} from './effects-blur-preview';
export {EffectsBrightnessPreview} from './effects-brightness-preview';
export {EffectsContrastPreview} from './effects-contrast-preview';
+export {EffectsDuotonePreview} from './effects-duotone-preview';
export {EffectsGrayscalePreview} from './effects-grayscale-preview';
export {EffectsHalftonePreview} from './effects-halftone-preview';
export {EffectsHuePreview} from './effects-hue-preview';
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index bb11039291..cd80584566 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -59,6 +59,7 @@ import {
EffectsBlurPreview,
EffectsBrightnessPreview,
EffectsContrastPreview,
+ EffectsDuotonePreview,
EffectsGrayscalePreview,
EffectsHalftonePreview,
EffectsHuePreview,
@@ -1112,6 +1113,14 @@ export const Index: React.FC = () => {
width={1080}
durationInFrames={1}
/>
+ <Composition
+ id="html-in-canvas-effects-duotone-preview"
+ component={EffectsDuotonePreview}
+ fps={30}
+ height={720}
+ width={1080}
+ durationInFrames={1}
+ />
<Composition
id="html-in-canvas-effects-blur-preview"
component={EffectsBlurPreview}