Skip to content

🎥 Make videos programmatically with React

`@remotion/effects`: Add combined color correction effect (#10304)

Jonny Burger4305d4a2c857
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.ts
index 2d130648f6..7659f986e6 100644
--- a/packages/docs/components/effects-demos/registry.ts
+++ b/packages/docs/components/effects-demos/registry.ts
@@ -4,6 +4,7 @@ import {brightness} from '@remotion/effects/brightness';
import {burlap} from '@remotion/effects/burlap';
import {checkerboard} from '@remotion/effects/checkerboard';
import {chromaticAberration} from '@remotion/effects/chromatic-aberration';
+import {colorCorrection} from '@remotion/effects/color-correction';
import {colorKey} from '@remotion/effects/color-key';
import {contourLines} from '@remotion/effects/contour-lines';
import {contrast} from '@remotion/effects/contrast';
@@ -72,6 +73,7 @@ import {EffectsBrightnessPreview} from '../effects/effects-brightness-preview';
import {EffectsBurlapPreview} from '../effects/effects-burlap-preview';
import {EffectsCheckerboardPreview} from '../effects/effects-checkerboard-preview';
import {EffectsChromaticAberrationPreview} from '../effects/effects-chromatic-aberration-preview';
+import {EffectsColorCorrectionPreview} from '../effects/effects-color-correction-preview';
import {EffectsColorKeyPreview} from '../effects/effects-color-key-preview';
import {EffectsContourLinesPreview} from '../effects/effects-contour-lines-preview';
import {EffectsContrastPreview} from '../effects/effects-contrast-preview';
@@ -234,6 +236,14 @@ export const effectsDemos: EffectsDemoType[] = [
similarity: 0.45,
},
},
+ {
+ ...defaults,
+ id: 'effects-color-correction',
+ effectName: 'colorCorrection',
+ effectImportPath: '@remotion/effects/color-correction',
+ comp: EffectsColorCorrectionPreview,
+ schema: colorCorrection().definition.schema,
+ },
{
...defaults,
id: 'effects-duotone',
diff --git a/packages/docs/components/effects/effects-color-correction-preview.tsx b/packages/docs/components/effects/effects-color-correction-preview.tsx
new file mode 100644
index 0000000000..66f8234f28
--- /dev/null
+++ b/packages/docs/components/effects/effects-color-correction-preview.tsx
@@ -0,0 +1,21 @@
+import {
+ colorCorrection,
+ type ColorCorrectionParams,
+} from '@remotion/effects/color-correction';
+import React from 'react';
+import {CanvasImage} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const EffectsColorCorrectionPreview: React.FC<
+ Required<ColorCorrectionParams>
+> = (params) => {
+ return (
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ fit="cover"
+ effects={[colorCorrection(params)]}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/color-correction.mdx b/packages/docs/docs/effects/color-correction.mdx
new file mode 100644
index 0000000000..fa5d49f368
--- /dev/null
+++ b/packages/docs/docs/effects/color-correction.mdx
@@ -0,0 +1,120 @@
+---
+image: /generated/articles-docs-effects-color-correction.png
+slug: /effects/color-correction
+title: colorCorrection()
+sidebar_label: colorCorrection()
+crumb: '@remotion/effects'
+---
+
+# colorCorrection()<AvailableFrom v="4.0.509" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+Applies common primary color adjustments in one WebGL pass.
+
+## Preview
+
+<EffectsDemo type="effects-color-correction" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {Video} from '@remotion/media';
+import {colorCorrection} from '@remotion/effects/color-correction';
+
+export const MyComp: React.FC = () => {
+ return (
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ colorCorrection({
+ exposure: 0.25,
+ contrast: 1.1,
+ shadows: 0.2,
+ highlights: -0.15,
+ temperature: 0.1,
+ vibrance: 0.2,
+ }),
+ ]}
+ />
+ );
+};
+```
+
+Calling `colorCorrection()` without arguments leaves the image unchanged.
+
+## Operation order
+
+Adjustments are applied in this order:
+
+1. Exposure
+2. White balance (`temperature` and `tint`)
+3. Tonal regions (`shadows`, `highlights`, `whites`, and `blacks`)
+4. Contrast
+5. Saturation
+6. Vibrance
+
+The effect uses the same color math as the corresponding standalone effects, while avoiding the intermediate canvases required by an effect chain. Alpha is preserved throughout the pass.
+
+## API
+
+### `exposure?`
+
+The exposure adjustment in stops, from `-5` to `5`. Defaults to `0`.
+
+### `contrast?`
+
+The contrast multiplier. `1` leaves contrast unchanged, `0` produces the pivot color, and values above `1` increase contrast. Defaults to `1`.
+
+### `pivot?`
+
+The center of the contrast adjustment, from `0` to `1`. Defaults to `0.5`.
+
+### `shadows?`
+
+The shadow adjustment from `-1` to `1`. Positive values lift dark regions and negative values suppress them. Defaults to `0`.
+
+### `highlights?`
+
+The highlight adjustment from `-1` to `1`. Positive values brighten light regions and negative values recover them. Defaults to `0`.
+
+### `whites?`
+
+The white-region adjustment from `-1` to `1`. It targets a narrower range near white than `highlights`. Defaults to `0`.
+
+### `blacks?`
+
+The black-region adjustment from `-1` to `1`. It targets a narrower range near black than `shadows`. Defaults to `0`.
+
+### `temperature?`
+
+The blue-to-amber temperature adjustment from `-1` to `1`. Negative values cool the image and positive values warm it. Defaults to `0`.
+
+### `tint?`
+
+The green-to-magenta tint adjustment from `-1` to `1`. Negative values add green and positive values add magenta. Defaults to `0`.
+
+### `saturation?`
+
+The saturation multiplier. `1` leaves saturation unchanged, `0` produces grayscale, and values above `1` increase saturation. Defaults to `1`.
+
+### `vibrance?`
+
+The vibrance adjustment from `-1` to `1`. Positive values emphasize muted colors more than already vivid colors. Defaults to `0`.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />
+
+## See also
+
+- [`@remotion/effects`](/docs/effects/api)
+- [`exposure()`](/docs/effects/exposure)
+- [`whiteBalance()`](/docs/effects/white-balance)
+- [`shadowsHighlights()`](/docs/effects/shadows-highlights)
+- [`vibrance()`](/docs/effects/vibrance)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/color-correction.ts)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index c1346034c8..737dbb0910 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -279,6 +279,7 @@ const sidebars: SidebarsConfig = {
'effects/burlap',
'effects/checkerboard',
'effects/chromatic-aberration',
+ 'effects/color-correction',
'effects/color-key',
'effects/contrast',
'effects/contour-lines',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 5e33c2745a..14e85f7355 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1862,6 +1862,15 @@ export const articles = [
noAi: false,
slug: 'effects/chromatic-aberration',
},
+ {
+ id: 'effects/color-correction',
+ title: 'colorCorrection()',
+ relativePath: 'docs/effects/color-correction.mdx',
+ compId: 'articles-docs-effects-color-correction',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/color-correction',
+ },
{
id: 'effects/color-key',
title: 'colorKey()',
diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsx
index 8c4e8d278b..2824669ea8 100644
--- a/packages/docs/src/remotion/Root.tsx
+++ b/packages/docs/src/remotion/Root.tsx
@@ -8,6 +8,7 @@ import {EffectsBrightnessPreview} from '../../components/effects/effects-brightn
import {EffectsBurlapPreview} from '../../components/effects/effects-burlap-preview';
import {EffectsCheckerboardPreview} from '../../components/effects/effects-checkerboard-preview';
import {EffectsChromaticAberrationPreview} from '../../components/effects/effects-chromatic-aberration-preview';
+import {EffectsColorCorrectionPreview} from '../../components/effects/effects-color-correction-preview';
import {EffectsColorKeyPreview} from '../../components/effects/effects-color-key-preview';
import {EffectsContourLinesPreview} from '../../components/effects/effects-contour-lines-preview';
import {EffectsContrastPreview} from '../../components/effects/effects-contrast-preview';
@@ -245,6 +246,25 @@ export const RemotionRoot: React.FC = () => {
offset: 0,
}}
/>
+ <Still
+ id="effects-color-correction-preview"
+ component={EffectsColorCorrectionPreview}
+ width={1280}
+ height={720}
+ defaultProps={{
+ exposure: 0.35,
+ contrast: 1.2,
+ pivot: 0.45,
+ shadows: 0.4,
+ highlights: -0.3,
+ whites: 0.2,
+ blacks: -0.1,
+ temperature: 0.15,
+ tint: 0.05,
+ saturation: 1.1,
+ vibrance: 0.35,
+ }}
+ />
<Still
id="effects-contrast-preview"
component={EffectsContrastPreview}
diff --git a/packages/docs/static/generated/articles-docs-effects-color-correction.png b/packages/docs/static/generated/articles-docs-effects-color-correction.png
new file mode 100644
index 0000000000..40cf97a2bb
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-color-correction.png differ
diff --git a/packages/docs/static/img/effects-color-correction-preview.png b/packages/docs/static/img/effects-color-correction-preview.png
new file mode 100644
index 0000000000..7165bed911
Binary files /dev/null and b/packages/docs/static/img/effects-color-correction-preview.png differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index ce9c55cabc..03876c7e31 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -12,6 +12,7 @@ const effectEntrypoints = [
'src/burlap.ts',
'src/checkerboard.ts',
'src/chromatic-aberration.ts',
+ 'src/color-correction.ts',
'src/color-key.ts',
'src/brightness.ts',
'src/contrast.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 78aa09598c..b3d90eb511 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -69,6 +69,11 @@
"module": "./dist/esm/color-key.mjs",
"import": "./dist/esm/color-key.mjs"
},
+ "./color-correction": {
+ "types": "./dist/color-correction.d.ts",
+ "module": "./dist/esm/color-correction.mjs",
+ "import": "./dist/esm/color-correction.mjs"
+ },
"./brightness": {
"types": "./dist/brightness.d.ts",
"module": "./dist/esm/brightness.mjs",
@@ -399,6 +404,9 @@
"color-key": [
"dist/color-key.d.ts"
],
+ "color-correction": [
+ "dist/color-correction.d.ts"
+ ],
"brightness": [
"dist/brightness.d.ts"
],
diff --git a/packages/effects/src/color-correction-shader-utils.ts b/packages/effects/src/color-correction-shader-utils.ts
new file mode 100644
index 0000000000..082ac20333
--- /dev/null
+++ b/packages/effects/src/color-correction-shader-utils.ts
@@ -0,0 +1,66 @@
+export const COLOR_SPACE_GLSL = /* glsl */ `
+vec3 srgbToLinear(vec3 color) {
+ vec3 lower = color / 12.92;
+ vec3 upper = pow((color + 0.055) / 1.055, vec3(2.4));
+ return mix(lower, upper, step(vec3(0.04045), color));
+}
+
+vec3 linearToSrgb(vec3 color) {
+ vec3 nonNegative = max(color, vec3(0.0));
+ vec3 lower = nonNegative * 12.92;
+ vec3 upper = 1.055 * pow(nonNegative, vec3(1.0 / 2.4)) - 0.055;
+ return mix(lower, upper, step(vec3(0.0031308), nonNegative));
+}
+`;
+
+export const WHITE_BALANCE_GLSL = /* glsl */ `
+vec3 applyWhiteBalanceLinear(vec3 linear, float temperature, float tint) {
+ vec3 temperatureOffset = vec3(0.3, 0.0, -0.3) * temperature;
+ vec3 tintOffset = vec3(0.15, -0.3, 0.15) * tint;
+ vec3 gains = exp2(temperatureOffset + tintOffset);
+ float luminanceGain = dot(gains, vec3(0.2126, 0.7152, 0.0722));
+ return linear * gains / luminanceGain;
+}
+`;
+
+export const SHADOWS_HIGHLIGHTS_GLSL = /* glsl */ `
+float getShadowsHighlightsStops(
+ vec3 color,
+ float shadows,
+ float highlights
+) {
+ float luminance = dot(color, vec3(0.2126, 0.7152, 0.0722));
+ float shadowWeight = 1.0 - smoothstep(0.0, 0.6, luminance);
+ float highlightWeight = smoothstep(0.4, 1.0, luminance);
+ shadowWeight *= shadowWeight;
+ highlightWeight *= highlightWeight;
+ return shadows * shadowWeight + highlights * highlightWeight;
+}
+`;
+
+export const VIBRANCE_GLSL = /* glsl */ `
+vec3 applyVibrance(vec3 color, float amount) {
+ float maximum = max(max(color.r, color.g), color.b);
+ float minimum = min(min(color.r, color.g), color.b);
+ float lightness = (maximum + minimum) * 0.5;
+ float chroma = maximum - minimum;
+ float saturationDenominator = 1.0 - abs(2.0 * lightness - 1.0);
+ float saturation = saturationDenominator <= 0.0
+ ? 0.0
+ : chroma / saturationDenominator;
+
+ if (saturation <= 0.000001) {
+ return color;
+ }
+
+ float targetSaturation = amount >= 0.0
+ ? saturation + amount * (1.0 - saturation)
+ : saturation * (1.0 + amount);
+ return clamp(
+ vec3(lightness) +
+ (color - vec3(lightness)) * (targetSaturation / saturation),
+ 0.0,
+ 1.0
+ );
+}
+`;
diff --git a/packages/effects/src/color-correction.ts b/packages/effects/src/color-correction.ts
new file mode 100644
index 0000000000..579da69c29
--- /dev/null
+++ b/packages/effects/src/color-correction.ts
@@ -0,0 +1,502 @@
+import type {InteractivitySchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ COLOR_SPACE_GLSL,
+ SHADOWS_HIGHLIGHTS_GLSL,
+ VIBRANCE_GLSL,
+ WHITE_BALANCE_GLSL,
+} from './color-correction-shader-utils.js';
+import {
+ assertOptionalFiniteNumber,
+ validateNonNegative,
+ validateSignedUnitInterval,
+ validateUnitInterval,
+} from './color-utils.js';
+import {assertEffectParamsObject} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const DEFAULT_EXPOSURE = 0 as const;
+const DEFAULT_CONTRAST = 1 as const;
+const DEFAULT_PIVOT = 0.5 as const;
+const DEFAULT_SHADOWS = 0 as const;
+const DEFAULT_HIGHLIGHTS = 0 as const;
+const DEFAULT_WHITES = 0 as const;
+const DEFAULT_BLACKS = 0 as const;
+const DEFAULT_TEMPERATURE = 0 as const;
+const DEFAULT_TINT = 0 as const;
+const DEFAULT_SATURATION = 1 as const;
+const DEFAULT_VIBRANCE = 0 as const;
+const MIN_EXPOSURE = -5 as const;
+const MAX_EXPOSURE = 5 as const;
+
+const signedAdjustmentSchema = (description: string) =>
+ ({
+ type: 'number',
+ min: -1,
+ max: 1,
+ step: 0.01,
+ default: 0,
+ description,
+ hiddenFromList: false,
+ }) as const;
+
+const colorCorrectionSchema = {
+ exposure: {
+ type: 'number',
+ min: MIN_EXPOSURE,
+ max: MAX_EXPOSURE,
+ step: 0.1,
+ default: DEFAULT_EXPOSURE,
+ description: 'Exposure',
+ hiddenFromList: false,
+ },
+ contrast: {
+ type: 'number',
+ min: 0,
+ max: 3,
+ step: 0.01,
+ default: DEFAULT_CONTRAST,
+ description: 'Contrast',
+ hiddenFromList: false,
+ },
+ pivot: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_PIVOT,
+ description: 'Contrast pivot',
+ hiddenFromList: false,
+ },
+ shadows: signedAdjustmentSchema('Shadows'),
+ highlights: signedAdjustmentSchema('Highlights'),
+ whites: signedAdjustmentSchema('Whites'),
+ blacks: signedAdjustmentSchema('Blacks'),
+ temperature: signedAdjustmentSchema('Temperature'),
+ tint: signedAdjustmentSchema('Tint'),
+ saturation: {
+ type: 'number',
+ min: 0,
+ max: 3,
+ step: 0.01,
+ default: DEFAULT_SATURATION,
+ description: 'Saturation',
+ hiddenFromList: false,
+ },
+ vibrance: signedAdjustmentSchema('Vibrance'),
+} as const satisfies InteractivitySchema;
+
+export type ColorCorrectionParams = {
+ /** Exposure adjustment in stops, from `-5` to `5`. Defaults to `0`. */
+ readonly exposure?: number;
+ /** Contrast multiplier. Defaults to `1`. */
+ readonly contrast?: number;
+ /** Contrast pivot from `0` to `1`. Defaults to `0.5`. */
+ readonly pivot?: number;
+ /** Shadow adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly shadows?: number;
+ /** Highlight adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly highlights?: number;
+ /** White-region adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly whites?: number;
+ /** Black-region adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly blacks?: number;
+ /** Blue-to-amber temperature adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly temperature?: number;
+ /** Green-to-magenta tint adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly tint?: number;
+ /** Saturation multiplier. Defaults to `1`. */
+ readonly saturation?: number;
+ /** Vibrance adjustment from `-1` to `1`. Defaults to `0`. */
+ readonly vibrance?: number;
+};
+
+type ColorCorrectionResolved = Required<ColorCorrectionParams>;
+
+type ColorCorrectionState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly textureSource: WebGLTexture;
+ readonly uniforms: {
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uExposure: WebGLUniformLocation | null;
+ readonly uContrast: WebGLUniformLocation | null;
+ readonly uPivot: WebGLUniformLocation | null;
+ readonly uShadows: WebGLUniformLocation | null;
+ readonly uHighlights: WebGLUniformLocation | null;
+ readonly uWhites: WebGLUniformLocation | null;
+ readonly uBlacks: WebGLUniformLocation | null;
+ readonly uTemperature: WebGLUniformLocation | null;
+ readonly uTint: WebGLUniformLocation | null;
+ readonly uSaturation: WebGLUniformLocation | null;
+ readonly uVibrance: WebGLUniformLocation | null;
+ };
+};
+
+const resolve = (params: ColorCorrectionParams): ColorCorrectionResolved => ({
+ exposure: params.exposure ?? DEFAULT_EXPOSURE,
+ contrast: params.contrast ?? DEFAULT_CONTRAST,
+ pivot: params.pivot ?? DEFAULT_PIVOT,
+ shadows: params.shadows ?? DEFAULT_SHADOWS,
+ highlights: params.highlights ?? DEFAULT_HIGHLIGHTS,
+ whites: params.whites ?? DEFAULT_WHITES,
+ blacks: params.blacks ?? DEFAULT_BLACKS,
+ temperature: params.temperature ?? DEFAULT_TEMPERATURE,
+ tint: params.tint ?? DEFAULT_TINT,
+ saturation: params.saturation ?? DEFAULT_SATURATION,
+ vibrance: params.vibrance ?? DEFAULT_VIBRANCE,
+});
+
+const validateColorCorrectionParams = (params: ColorCorrectionParams): void => {
+ assertEffectParamsObject(params, 'Color correction');
+ assertOptionalFiniteNumber(params.exposure, 'exposure');
+ assertOptionalFiniteNumber(params.contrast, 'contrast');
+ assertOptionalFiniteNumber(params.pivot, 'pivot');
+ assertOptionalFiniteNumber(params.shadows, 'shadows');
+ assertOptionalFiniteNumber(params.highlights, 'highlights');
+ assertOptionalFiniteNumber(params.whites, 'whites');
+ assertOptionalFiniteNumber(params.blacks, 'blacks');
+ assertOptionalFiniteNumber(params.temperature, 'temperature');
+ assertOptionalFiniteNumber(params.tint, 'tint');
+ assertOptionalFiniteNumber(params.saturation, 'saturation');
+ assertOptionalFiniteNumber(params.vibrance, 'vibrance');
+
+ const resolved = resolve(params);
+ if (resolved.exposure < MIN_EXPOSURE) {
+ throw new TypeError(
+ `"exposure" must be >= ${MIN_EXPOSURE}, but got ${JSON.stringify(resolved.exposure)}`,
+ );
+ }
+
+ if (resolved.exposure > MAX_EXPOSURE) {
+ throw new TypeError(
+ `"exposure" must be <= ${MAX_EXPOSURE}, but got ${JSON.stringify(resolved.exposure)}`,
+ );
+ }
+
+ validateNonNegative(resolved.contrast, 'contrast');
+ validateUnitInterval(resolved.pivot, 'pivot');
+ validateSignedUnitInterval(resolved.shadows, 'shadows');
+ validateSignedUnitInterval(resolved.highlights, 'highlights');
+ validateSignedUnitInterval(resolved.whites, 'whites');
+ validateSignedUnitInterval(resolved.blacks, 'blacks');
+ validateSignedUnitInterval(resolved.temperature, 'temperature');
+ validateSignedUnitInterval(resolved.tint, 'tint');
+ validateNonNegative(resolved.saturation, 'saturation');
+ validateSignedUnitInterval(resolved.vibrance, 'vibrance');
+};
+
+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 uExposure;
+uniform float uContrast;
+uniform float uPivot;
+uniform float uShadows;
+uniform float uHighlights;
+uniform float uWhites;
+uniform float uBlacks;
+uniform float uTemperature;
+uniform float uTint;
+uniform float uSaturation;
+uniform float uVibrance;
+
+${COLOR_SPACE_GLSL}
+${WHITE_BALANCE_GLSL}
+${SHADOWS_HIGHLIGHTS_GLSL}
+${VIBRANCE_GLSL}
+
+vec3 applyEndpointTones(vec3 color, float blacks, float whites) {
+ float luminance = dot(color, vec3(0.2126, 0.7152, 0.0722));
+ float blackWeight = 1.0 - smoothstep(0.0, 0.35, luminance);
+ float whiteWeight = smoothstep(0.65, 1.0, luminance);
+ blackWeight *= blackWeight;
+ whiteWeight *= whiteWeight;
+
+ // Moving tones toward their named endpoint uses the full adjustment.
+ // Moving them away is damped to avoid flattening the image too aggressively.
+ if (blacks >= 0.0) {
+ color += (vec3(1.0) - color) * blacks * blackWeight * 0.2;
+ } else {
+ color *= 1.0 + blacks * blackWeight;
+ }
+
+ if (whites >= 0.0) {
+ color += (vec3(1.0) - color) * whites * whiteWeight;
+ } else {
+ color *= 1.0 + whites * whiteWeight * 0.2;
+ }
+
+ return clamp(color, 0.0, 1.0);
+}
+
+void main() {
+ vec4 sourceColor = texture(uSource, vUv);
+ float alpha = sourceColor.a;
+
+ if (alpha <= 0.0) {
+ fragColor = vec4(0.0);
+ return;
+ }
+
+ if (
+ uExposure == 0.0 &&
+ uContrast == 1.0 &&
+ uPivot == 0.5 &&
+ uShadows == 0.0 &&
+ uHighlights == 0.0 &&
+ uWhites == 0.0 &&
+ uBlacks == 0.0 &&
+ uTemperature == 0.0 &&
+ uTint == 0.0 &&
+ uSaturation == 1.0 &&
+ uVibrance == 0.0
+ ) {
+ fragColor = sourceColor;
+ return;
+ }
+
+ vec3 color = sourceColor.rgb / alpha;
+ vec3 linear = srgbToLinear(color) * exp2(uExposure);
+ linear = applyWhiteBalanceLinear(linear, uTemperature, uTint);
+ color = linearToSrgb(linear);
+
+ float tonalStops = getShadowsHighlightsStops(
+ color,
+ uShadows,
+ uHighlights
+ );
+ linear = srgbToLinear(color) * exp2(tonalStops);
+ color = linearToSrgb(linear);
+ color = applyEndpointTones(color, uBlacks, uWhites);
+ color = clamp((color - vec3(uPivot)) * uContrast + vec3(uPivot), 0.0, 1.0);
+
+ float luminance = dot(color, vec3(0.213, 0.715, 0.072));
+ color = clamp(
+ vec3(luminance) + (color - vec3(luminance)) * uSaturation,
+ 0.0,
+ 1.0
+ );
+ color = applyVibrance(color, uVibrance);
+
+ fragColor = vec4(color * alpha, alpha);
+}
+`;
+
+const compileShader = (
+ gl: WebGL2RenderingContext,
+ type: number,
+ source: string,
+): WebGLShader => {
+ const shader = gl.createShader(type);
+ if (!shader) {
+ throw new Error('Failed to create color correction 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(
+ `Color correction shader compile failed: ${log ?? '(no log)'}`,
+ );
+ }
+
+ return shader;
+};
+
+const createProgram = (gl: WebGL2RenderingContext): WebGLProgram => {
+ const vertexShader = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
+ const fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER);
+ const program = gl.createProgram();
+ if (!program) {
+ throw new Error('Failed to create color correction shader program');
+ }
+
+ gl.attachShader(program, vertexShader);
+ gl.attachShader(program, fragmentShader);
+ gl.linkProgram(program);
+ gl.deleteShader(vertexShader);
+ gl.deleteShader(fragmentShader);
+
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+ const log = gl.getProgramInfoLog(program);
+ gl.deleteProgram(program);
+ throw new Error(
+ `Color correction shader link failed: ${log ?? '(no log)'}`,
+ );
+ }
+
+ return program;
+};
+
+const createTexture = (gl: WebGL2RenderingContext): WebGLTexture => {
+ const texture = gl.createTexture();
+ if (!texture) {
+ throw new Error('Failed to create color correction 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 setupColorCorrection = (
+ target: HTMLCanvasElement,
+): ColorCorrectionState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('color correction effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const program = createProgram(gl);
+ const vao = gl.createVertexArray();
+ if (!vao) {
+ throw new Error('Failed to create color correction vertex array');
+ }
+
+ const vbo = gl.createBuffer();
+ if (!vbo) {
+ throw new Error('Failed to create color correction vertex buffer');
+ }
+
+ gl.bindVertexArray(vao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ new Float32Array([-1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1]),
+ 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);
+
+ return {
+ gl,
+ program,
+ vao,
+ vbo,
+ textureSource: createTexture(gl),
+ uniforms: {
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uExposure: gl.getUniformLocation(program, 'uExposure'),
+ uContrast: gl.getUniformLocation(program, 'uContrast'),
+ uPivot: gl.getUniformLocation(program, 'uPivot'),
+ uShadows: gl.getUniformLocation(program, 'uShadows'),
+ uHighlights: gl.getUniformLocation(program, 'uHighlights'),
+ uWhites: gl.getUniformLocation(program, 'uWhites'),
+ uBlacks: gl.getUniformLocation(program, 'uBlacks'),
+ uTemperature: gl.getUniformLocation(program, 'uTemperature'),
+ uTint: gl.getUniformLocation(program, 'uTint'),
+ uSaturation: gl.getUniformLocation(program, 'uSaturation'),
+ uVibrance: gl.getUniformLocation(program, 'uVibrance'),
+ },
+ };
+};
+
+export const colorCorrection = createEffect<
+ ColorCorrectionParams,
+ ColorCorrectionState
+>({
+ type: 'remotion/color-correction',
+ label: 'colorCorrection()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/color-correction',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `color-correction-${r.exposure}-${r.contrast}-${r.pivot}-${r.shadows}-${r.highlights}-${r.whites}-${r.blacks}-${r.temperature}-${r.tint}-${r.saturation}-${r.vibrance}`;
+ },
+ setup: setupColorCorrection,
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ 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.uExposure) gl.uniform1f(uniforms.uExposure, r.exposure);
+ if (uniforms.uContrast) gl.uniform1f(uniforms.uContrast, r.contrast);
+ if (uniforms.uPivot) gl.uniform1f(uniforms.uPivot, r.pivot);
+ if (uniforms.uShadows) gl.uniform1f(uniforms.uShadows, r.shadows);
+ if (uniforms.uHighlights) {
+ gl.uniform1f(uniforms.uHighlights, r.highlights);
+ }
+
+ if (uniforms.uWhites) gl.uniform1f(uniforms.uWhites, r.whites);
+ if (uniforms.uBlacks) gl.uniform1f(uniforms.uBlacks, r.blacks);
+ if (uniforms.uTemperature) {
+ gl.uniform1f(uniforms.uTemperature, r.temperature);
+ }
+
+ if (uniforms.uTint) gl.uniform1f(uniforms.uTint, r.tint);
+ if (uniforms.uSaturation) {
+ gl.uniform1f(uniforms.uSaturation, r.saturation);
+ }
+
+ if (uniforms.uVibrance) gl.uniform1f(uniforms.uVibrance, r.vibrance);
+
+ 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: colorCorrectionSchema,
+ validateParams: validateColorCorrectionParams,
+});
diff --git a/packages/effects/src/exposure.ts b/packages/effects/src/exposure.ts
index 9a897e4295..de4fab833b 100644
--- a/packages/effects/src/exposure.ts
+++ b/packages/effects/src/exposure.ts
@@ -1,5 +1,6 @@
import type {InteractivitySchema} from 'remotion';
import {Internals} from 'remotion';
+import {COLOR_SPACE_GLSL} from './color-correction-shader-utils.js';
import {assertOptionalFiniteNumber} from './color-utils.js';
import {assertEffectParamsObject} from './validate-effect-param.js';
@@ -84,18 +85,7 @@ out vec4 fragColor;
uniform sampler2D uSource;
uniform float uStops;
-vec3 srgbToLinear(vec3 color) {
- vec3 lower = color / 12.92;
- vec3 upper = pow((color + 0.055) / 1.055, vec3(2.4));
- return mix(lower, upper, step(vec3(0.04045), color));
-}
-
-vec3 linearToSrgb(vec3 color) {
- vec3 nonNegative = max(color, vec3(0.0));
- vec3 lower = nonNegative * 12.92;
- vec3 upper = 1.055 * pow(nonNegative, vec3(1.0 / 2.4)) - 0.055;
- return mix(lower, upper, step(vec3(0.0031308), nonNegative));
-}
+${COLOR_SPACE_GLSL}
void main() {
vec4 sourceColor = texture(uSource, vUv);
diff --git a/packages/effects/src/shadows-highlights.ts b/packages/effects/src/shadows-highlights.ts
index 4ee49f165d..b07aebb4f3 100644
--- a/packages/effects/src/shadows-highlights.ts
+++ b/packages/effects/src/shadows-highlights.ts
@@ -1,5 +1,9 @@
import type {InteractivitySchema} from 'remotion';
import {Internals} from 'remotion';
+import {
+ COLOR_SPACE_GLSL,
+ SHADOWS_HIGHLIGHTS_GLSL,
+} from './color-correction-shader-utils.js';
import {
assertOptionalFiniteNumber,
validateSignedUnitInterval,
@@ -97,18 +101,8 @@ uniform sampler2D uSource;
uniform float uShadows;
uniform float uHighlights;
-vec3 srgbToLinear(vec3 color) {
- vec3 lower = color / 12.92;
- vec3 upper = pow((color + 0.055) / 1.055, vec3(2.4));
- return mix(lower, upper, step(vec3(0.04045), color));
-}
-
-vec3 linearToSrgb(vec3 color) {
- vec3 nonNegative = max(color, vec3(0.0));
- vec3 lower = nonNegative * 12.92;
- vec3 upper = 1.055 * pow(nonNegative, vec3(1.0 / 2.4)) - 0.055;
- return mix(lower, upper, step(vec3(0.0031308), nonNegative));
-}
+${COLOR_SPACE_GLSL}
+${SHADOWS_HIGHLIGHTS_GLSL}
void main() {
vec4 sourceColor = texture(uSource, vUv);
@@ -120,13 +114,7 @@ void main() {
}
vec3 color = sourceColor.rgb / alpha;
- float luminance = dot(color, vec3(0.2126, 0.7152, 0.0722));
- float shadowWeight = 1.0 - smoothstep(0.0, 0.6, luminance);
- float highlightWeight = smoothstep(0.4, 1.0, luminance);
- shadowWeight *= shadowWeight;
- highlightWeight *= highlightWeight;
-
- float stops = uShadows * shadowWeight + uHighlights * highlightWeight;
+ float stops = getShadowsHighlightsStops(color, uShadows, uHighlights);
vec3 linear = srgbToLinear(color);
vec3 adjusted = linear * exp2(stops);
vec3 corrected = linearToSrgb(adjusted);
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index 867fc1e9a6..ed763410ea 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -5,6 +5,10 @@ import {brightness} from '../brightness.js';
import {burlap} from '../burlap.js';
import {checkerboard} from '../checkerboard.js';
import {chromaticAberration} from '../chromatic-aberration/index.js';
+import {
+ colorCorrection,
+ type ColorCorrectionParams,
+} from '../color-correction.js';
import {colorKey} from '../color-key.js';
import {contourLines} from '../contour-lines.js';
import {contrast} from '../contrast.js';
@@ -110,6 +114,9 @@ test('@remotion/effects expose documentation links', () => {
expect(colorKey().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/color-key',
);
+ expect(colorCorrection().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/color-correction',
+ );
expect(brightness().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/brightness',
);
@@ -312,6 +319,7 @@ test('@remotion/effects expose API names as Studio labels', () => {
expect(blur({radius: 1}).definition.label).toBe('blur()');
expect(chromaticAberration().definition.label).toBe('chromaticAberration()');
expect(colorKey().definition.label).toBe('colorKey()');
+ expect(colorCorrection().definition.label).toBe('colorCorrection()');
expect(brightness().definition.label).toBe('brightness()');
expect(burlap().definition.label).toBe('burlap()');
expect(checkerboard().definition.label).toBe('checkerboard()');
@@ -1136,6 +1144,70 @@ test('shadowsHighlights() parameters produce distinct effect keys', () => {
).toBe(3);
});
+test('colorCorrection() accepts neutral defaults', () => {
+ expect(() => colorCorrection()).not.toThrow();
+});
+
+test('colorCorrection() validates exposure, contrast, pivot, and saturation', () => {
+ expect(() => colorCorrection({exposure: Number.NaN})).toThrow(
+ '"exposure" must be a finite number',
+ );
+ expect(() => colorCorrection({exposure: -5.1})).toThrow(
+ '"exposure" must be >= -5',
+ );
+ expect(() => colorCorrection({exposure: 5.1})).toThrow(
+ '"exposure" must be <= 5',
+ );
+ expect(() => colorCorrection({contrast: -0.1})).toThrow(
+ '"contrast" must be >= 0',
+ );
+ expect(() => colorCorrection({pivot: 1.1})).toThrow('"pivot" must be <= 1');
+ expect(() => colorCorrection({saturation: -0.1})).toThrow(
+ '"saturation" must be >= 0',
+ );
+});
+
+test('colorCorrection() validates signed adjustments', () => {
+ const names = [
+ 'shadows',
+ 'highlights',
+ 'whites',
+ 'blacks',
+ 'temperature',
+ 'tint',
+ 'vibrance',
+ ] as const satisfies readonly (keyof ColorCorrectionParams)[];
+
+ for (const name of names) {
+ expect(() => colorCorrection({[name]: -1.1})).toThrow(
+ `"${name}" must be >= -1`,
+ );
+ expect(() => colorCorrection({[name]: 1.1})).toThrow(
+ `"${name}" must be <= 1`,
+ );
+ }
+});
+
+test('colorCorrection() parameters produce distinct effect keys', () => {
+ const effects = [
+ colorCorrection(),
+ colorCorrection({exposure: 1}),
+ colorCorrection({contrast: 1.2}),
+ colorCorrection({pivot: 0.4}),
+ colorCorrection({shadows: 0.2}),
+ colorCorrection({highlights: -0.2}),
+ colorCorrection({whites: 0.2}),
+ colorCorrection({blacks: -0.2}),
+ colorCorrection({temperature: 0.2}),
+ colorCorrection({tint: -0.2}),
+ colorCorrection({saturation: 1.2}),
+ colorCorrection({vibrance: 0.2}),
+ ];
+ expect(new Set(effects.map((effect) => effect.effectKey)).size).toBe(
+ effects.length,
+ );
+});
+
test('contrast() accepts default params', () => {
expect(() => contrast()).not.toThrow();
});
diff --git a/packages/effects/src/vibrance.ts b/packages/effects/src/vibrance.ts
index 0416aa5041..cfa2d94392 100644
--- a/packages/effects/src/vibrance.ts
+++ b/packages/effects/src/vibrance.ts
@@ -1,5 +1,6 @@
import type {InteractivitySchema} from 'remotion';
import {Internals} from 'remotion';
+import {VIBRANCE_GLSL} from './color-correction-shader-utils.js';
import {
assertOptionalFiniteNumber,
validateSignedUnitInterval,
@@ -75,6 +76,8 @@ out vec4 fragColor;
uniform sampler2D uSource;
uniform float uAmount;
+${VIBRANCE_GLSL}
+
void main() {
vec4 sourceColor = texture(uSource, vUv);
float alpha = sourceColor.a;
@@ -85,27 +88,9 @@ void main() {
}
vec3 color = sourceColor.rgb / alpha;
- float maximum = max(max(color.r, color.g), color.b);
- float minimum = min(min(color.r, color.g), color.b);
- float lightness = (maximum + minimum) * 0.5;
- float chroma = maximum - minimum;
- float saturationDenominator = 1.0 - abs(2.0 * lightness - 1.0);
- float saturation = saturationDenominator <= 0.0
- ? 0.0
- : chroma / saturationDenominator;
-
- if (saturation <= 0.000001) {
- fragColor = sourceColor;
- return;
- }
-
- float targetSaturation = uAmount >= 0.0
- ? saturation + uAmount * (1.0 - saturation)
- : saturation * (1.0 + uAmount);
- vec3 adjusted = vec3(lightness) +
- (color - vec3(lightness)) * (targetSaturation / saturation);
+ vec3 adjusted = applyVibrance(color, uAmount);
- fragColor = vec4(clamp(adjusted, 0.0, 1.0) * alpha, alpha);
+ fragColor = vec4(adjusted * alpha, alpha);
}
`;
diff --git a/packages/effects/src/visual-test/effects-visual.test.ts b/packages/effects/src/visual-test/effects-visual.test.ts
index 276798919f..ae20bf6fae 100644
--- a/packages/effects/src/visual-test/effects-visual.test.ts
+++ b/packages/effects/src/visual-test/effects-visual.test.ts
@@ -1,10 +1,13 @@
import {expect, test} from 'vitest';
import {blur} from '../blur.js';
+import {colorCorrection} from '../color-correction.js';
+import {contrast} from '../contrast.js';
import {evolve} from '../evolve.js';
import {exposure} from '../exposure.js';
import {levels} from '../levels.js';
import {noise} from '../noise.js';
import {pixelDissolve} from '../pixel-dissolve.js';
+import {saturation} from '../saturation.js';
import {shadowsHighlights} from '../shadows-highlights.js';
import {vibrance} from '../vibrance.js';
import {vignette} from '../vignette.js';
@@ -262,6 +265,188 @@ test('shadowsHighlights() targets dark and bright tones smoothly', async () => {
expect(pixels[11]).toBe(128);
});
+test('colorCorrection() is neutral by default and matches standalone adjustments', async () => {
+ const source = document.createElement('canvas');
+ source.width = 3;
+ source.height = 1;
+ const sourceContext = source.getContext('2d');
+ if (!sourceContext) {
+ throw new Error('Could not get source context');
+ }
+
+ const sourcePixels = new Uint8ClampedArray([
+ 64, 96, 128, 255, 128, 128, 128, 255, 192, 128, 64, 255,
+ ]);
+ sourceContext.putImageData(new ImageData(sourcePixels, 3, 1), 0, 0);
+
+ const neutralCanvas = await renderEffectChainToCanvas({
+ source,
+ width: 3,
+ height: 1,
+ effects: descriptorsToMemoizedEffects([colorCorrection()]),
+ });
+ const neutralContext = neutralCanvas.getContext('2d');
+ if (!neutralContext) {
+ throw new Error('Could not get neutral output context');
+ }
+
+ expect([...neutralContext.getImageData(0, 0, 3, 1).data]).toEqual([
+ ...sourcePixels,
+ ]);
+
+ const comparisons = [
+ {
+ combined: colorCorrection({exposure: 0.75}),
+ standalone: exposure({stops: 0.75}),
+ },
+ {
+ combined: colorCorrection({temperature: 0.6, tint: -0.3}),
+ standalone: whiteBalance({temperature: 0.6, tint: -0.3}),
+ },
+ {
+ combined: colorCorrection({shadows: 0.7, highlights: -0.4}),
+ standalone: shadowsHighlights({shadows: 0.7, highlights: -0.4}),
+ },
+ {
+ combined: colorCorrection({contrast: 1.4, pivot: 128 / 255}),
+ standalone: contrast({amount: 1.4}),
+ },
+ {
+ combined: colorCorrection({saturation: 0.4}),
+ standalone: saturation({amount: 0.4}),
+ },
+ {
+ combined: colorCorrection({vibrance: 0.5}),
+ standalone: vibrance({amount: 0.5}),
+ },
+ ];
+
+ for (const {combined, standalone} of comparisons) {
+ const combinedCanvas = await renderEffectChainToCanvas({
+ source,
+ width: 3,
+ height: 1,
+ effects: descriptorsToMemoizedEffects([combined]),
+ });
+ const standaloneCanvas = await renderEffectChainToCanvas({
+ source,
+ width: 3,
+ height: 1,
+ effects: descriptorsToMemoizedEffects([standalone]),
+ });
+ const combinedContext = combinedCanvas.getContext('2d');
+ const standaloneContext = standaloneCanvas.getContext('2d');
+ if (!combinedContext || !standaloneContext) {
+ throw new Error('Could not get comparison output context');
+ }
+
+ const combinedPixels = combinedContext.getImageData(0, 0, 3, 1).data;
+ const standalonePixels = standaloneContext.getImageData(0, 0, 3, 1).data;
+ for (let index = 0; index < combinedPixels.length; index++) {
+ expect(
+ Math.abs(combinedPixels[index] - standalonePixels[index]),
+ ).toBeLessThanOrEqual(2);
+ }
+ }
+});
+
+test('colorCorrection() applies endpoint and combined adjustments in one pass', async () => {
+ const source = document.createElement('canvas');
+ source.width = 3;
+ source.height = 1;
+ const sourceContext = source.getContext('2d');
+ if (!sourceContext) {
+ throw new Error('Could not get source context');
+ }
+
+ sourceContext.putImageData(
+ new ImageData(
+ new Uint8ClampedArray([
+ 32, 32, 32, 128, 128, 96, 64, 128, 224, 224, 224, 128,
+ ]),
+ 3,
+ 1,
+ ),
+ 0,
+ 0,
+ );
+
+ const endpointCanvas = await renderEffectChainToCanvas({
+ source,
+ width: 3,
+ height: 1,
+ effects: descriptorsToMemoizedEffects([
+ colorCorrection({blacks: 1, whites: -1}),
+ ]),
+ });
+ const endpointContext = endpointCanvas.getContext('2d');
+ if (!endpointContext) {
+ throw new Error('Could not get endpoint output context');
+ }
+
+ const endpointPixels = endpointContext.getImageData(0, 0, 3, 1).data;
+ expect(endpointPixels[0]).toBeGreaterThan(32);
+ expect(endpointPixels[8]).toBeLessThan(224);
+
+ const towardEndpointCanvas = await renderEffectChainToCanvas({
+ source,
+ width: 3,
+ height: 1,
+ effects: descriptorsToMemoizedEffects([
+ colorCorrection({blacks: -1, whites: 1}),
+ ]),
+ });
+ const towardEndpointContext = towardEndpointCanvas.getContext('2d');
+ if (!towardEndpointContext) {
+ throw new Error('Could not get toward-endpoint output context');
+ }
+
+ const towardEndpointPixels = towardEndpointContext.getImageData(
+ 0,
+ 0,
+ 3,
+ 1,
+ ).data;
+ expect(towardEndpointPixels[0]).toBeLessThan(32);
+ expect(towardEndpointPixels[8]).toBeGreaterThan(224);
+ expect(towardEndpointPixels[3]).toBe(128);
+ expect(towardEndpointPixels[7]).toBe(128);
+ expect(towardEndpointPixels[11]).toBe(128);
+
+ const combinedCanvas = await renderEffectChainToCanvas({
+ source,
+ width: 3,
+ height: 1,
+ effects: descriptorsToMemoizedEffects([
+ colorCorrection({
+ exposure: 0.25,
+ contrast: 1.15,
+ pivot: 0.45,
+ shadows: 0.3,
+ highlights: -0.2,
+ whites: 0.25,
+ blacks: 0.15,
+ temperature: 0.2,
+ tint: -0.1,
+ saturation: 0.9,
+ vibrance: 0.25,
+ }),
+ ]),
+ });
+ const combinedContext = combinedCanvas.getContext('2d');
+ if (!combinedContext) {
+ throw new Error('Could not get combined output context');
+ }
+
+ const combinedPixels = combinedContext.getImageData(0, 0, 3, 1).data;
+ expect([...combinedPixels]).not.toEqual([
+ 32, 32, 32, 128, 128, 96, 64, 128, 224, 224, 224, 128,
+ ]);
+ expect(combinedPixels[3]).toBe(128);
+ expect(combinedPixels[7]).toBe(128);
+ expect(combinedPixels[11]).toBe(128);
+});
+
test('vignette() color mode works on transparent sources', async () => {
const width = 40;
const height = 40;
diff --git a/packages/effects/src/white-balance.ts b/packages/effects/src/white-balance.ts
index 86ed179a05..ae89e1ba06 100644
--- a/packages/effects/src/white-balance.ts
+++ b/packages/effects/src/white-balance.ts
@@ -1,5 +1,9 @@
import type {InteractivitySchema} from 'remotion';
import {Internals} from 'remotion';
+import {
+ COLOR_SPACE_GLSL,
+ WHITE_BALANCE_GLSL,
+} from './color-correction-shader-utils.js';
import {
assertOptionalFiniteNumber,
validateSignedUnitInterval,
@@ -93,18 +97,8 @@ uniform sampler2D uSource;
uniform float uTemperature;
uniform float uTint;
-vec3 srgbToLinear(vec3 color) {
- vec3 lower = color / 12.92;
- vec3 upper = pow((color + 0.055) / 1.055, vec3(2.4));
- return mix(lower, upper, step(vec3(0.04045), color));
-}
-
-vec3 linearToSrgb(vec3 color) {
- vec3 nonNegative = max(color, vec3(0.0));
- vec3 lower = nonNegative * 12.92;
- vec3 upper = 1.055 * pow(nonNegative, vec3(1.0 / 2.4)) - 0.055;
- return mix(lower, upper, step(vec3(0.0031308), nonNegative));
-}
+${COLOR_SPACE_GLSL}
+${WHITE_BALANCE_GLSL}
void main() {
vec4 sourceColor = texture(uSource, vUv);
@@ -117,11 +111,7 @@ void main() {
vec3 unpremultiplied = sourceColor.rgb / alpha;
vec3 linear = srgbToLinear(unpremultiplied);
- vec3 temperatureOffset = vec3(0.3, 0.0, -0.3) * uTemperature;
- vec3 tintOffset = vec3(0.15, -0.3, 0.15) * uTint;
- vec3 gains = exp2(temperatureOffset + tintOffset);
- float luminanceGain = dot(gains, vec3(0.2126, 0.7152, 0.0722));
- vec3 balanced = linear * gains / luminanceGain;
+ vec3 balanced = applyWhiteBalanceLinear(linear, uTemperature, uTint);
vec3 corrected = linearToSrgb(balanced);
fragColor = vec4(corrected * alpha, alpha);
diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.ts
index bcf786d930..d719470617 100644
--- a/packages/studio-shared/src/effect-catalog.ts
+++ b/packages/studio-shared/src/effect-catalog.ts
@@ -83,6 +83,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [
config: {},
},
},
+ {
+ id: 'effects-color-correction',
+ category: 'Color',
+ label: 'colorCorrection()',
+ description: 'Combined primary color adjustments',
+ effect: {
+ name: 'colorCorrection',
+ importPath: '@remotion/effects/color-correction',
+ config: {},
+ },
+ },
{
id: 'effects-color-key',
category: 'Color',
diff --git a/packages/studio/src/test/effect-catalog.test.ts b/packages/studio/src/test/effect-catalog.test.ts
index 374b2bb6e1..ad955170be 100644
--- a/packages/studio/src/test/effect-catalog.test.ts
+++ b/packages/studio/src/test/effect-catalog.test.ts
@@ -15,6 +15,9 @@ test('effect catalog exposes documentation links for picker context menu', () =>
expect(links.get('brightness()')).toBe(
'https://www.remotion.dev/docs/effects/brightness',
);
+ expect(links.get('colorCorrection()')).toBe(
+ 'https://www.remotion.dev/docs/effects/color-correction',
+ );
expect(links.get('xyTranslate()')).toBe(
'https://www.remotion.dev/docs/effects/xy-translate',
);
diff --git a/packages/studio/src/test/effect-picker-search.test.ts b/packages/studio/src/test/effect-picker-search.test.ts
index 9399346394..8329ada752 100644
--- a/packages/studio/src/test/effect-picker-search.test.ts
+++ b/packages/studio/src/test/effect-picker-search.test.ts
@@ -39,7 +39,7 @@ test('effect picker search preserves table-of-contents order for empty queries',
items: EFFECT_CATALOG,
query: '',
})
- .slice(0, 3)
+ .slice(0, 4)
.map((item) => item.label),
- ).toEqual(['brightness()', 'contrast()', 'colorKey()']);
+ ).toEqual(['brightness()', 'contrast()', 'colorCorrection()', 'colorKey()']);
});