🎥 Make videos programmatically with React
`@remotion/effects`: Add vibrance effect (#10296)
Jonny Burgerc6947c1a9524
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.tsindex b15af3cbd1..aae70fe325 100644--- a/packages/docs/components/effects-demos/registry.ts+++ b/packages/docs/components/effects-demos/registry.ts@@ -56,6 +56,7 @@ import {tint} from '@remotion/effects/tint';import {uvTranslate, xyTranslate} from '@remotion/effects/translate';import {tvSignalOff} from '@remotion/effects/tv-signal-off';import {venetianBlinds} from '@remotion/effects/venetian-blinds';+import {vibrance} from '@remotion/effects/vibrance';import {vignette} from '@remotion/effects/vignette';import {wave} from '@remotion/effects/wave';import {waves} from '@remotion/effects/waves';@@ -146,6 +147,7 @@ import {} from '../effects/effects-translate-preview';import {EffectsTvSignalOffPreview} from '../effects/effects-tv-signal-off-preview';import {EffectsVenetianBlindsPreview} from '../effects/effects-venetian-blinds-preview';+import {EffectsVibrancePreview} from '../effects/effects-vibrance-preview';import {EffectsVignettePreview} from '../effects/effects-vignette-preview';import {EffectsWavePreview} from '../effects/effects-wave-preview';import {EffectsWavesPreview} from '../effects/effects-waves-preview';@@ -260,6 +262,14 @@ export const effectsDemos: EffectsDemoType[] = [comp: EffectsWhiteBalancePreview,schema: whiteBalance().definition.schema,},+ {+ ...defaults,+ id: 'effects-vibrance',+ effectName: 'vibrance',+ effectImportPath: '@remotion/effects/vibrance',+ comp: EffectsVibrancePreview,+ schema: vibrance().definition.schema,+ },{...defaults,id: 'effects-venetian-blinds',diff --git a/packages/docs/components/effects/effects-vibrance-preview.tsx b/packages/docs/components/effects/effects-vibrance-preview.tsxnew file mode 100644index 0000000000..82ca102667--- /dev/null+++ b/packages/docs/components/effects/effects-vibrance-preview.tsx@@ -0,0 +1,18 @@+import {vibrance} from '@remotion/effects/vibrance';+import React from 'react';+import {CanvasImage} from 'remotion';+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';++export const EffectsVibrancePreview: React.FC<{+ readonly amount: number;+}> = ({amount}) => {+ return (+ <CanvasImage+ src={EFFECTS_PREVIEW_IMAGE_SRC}+ width={1280}+ height={720}+ fit="cover"+ effects={[vibrance({amount})]}+ />+ );+};diff --git a/packages/docs/docs/effects/vibrance.mdx b/packages/docs/docs/effects/vibrance.mdxnew file mode 100644index 0000000000..5ce62fbd81--- /dev/null+++ b/packages/docs/docs/effects/vibrance.mdx@@ -0,0 +1,58 @@+---+image: /generated/articles-docs-effects-vibrance.png+slug: /effects/vibrance+title: vibrance()+sidebar_label: vibrance()+crumb: '@remotion/effects'+---++# vibrance()<AvailableFrom v="4.0.508" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Adjusts muted colors more strongly than colors that are already saturated.++## Preview++<EffectsDemo type="effects-vibrance" />++## Example++```tsx twoslash title="MyComp.tsx"+import {Video} from '@remotion/media';+import {vibrance} from '@remotion/effects/vibrance';++export const MyComp: React.FC = () => {+ return (+ <Video+ src="https://remotion.media/video.mp4"+ effects={[vibrance({amount: 0.4})]}+ />+ );+};+```++## API++You can call `vibrance()` without arguments or pass an object with the following properties.++### `amount?`++The vibrance adjustment from `-1` to `1`. Positive values increase HSL saturation, with a larger adjustment for colors that have more saturation available. Negative values reduce saturation, and `-1` produces grayscale. Defaults to `0`.++The calculation uses unpremultiplied sRGB values and preserves HSL lightness. Grayscale pixels remain unchanged because they have no hue.++### `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)+- [`saturation()`](/docs/effects/saturation)+- [`whiteBalance()`](/docs/effects/white-balance)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/vibrance.ts)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 40a93406f7..9bb1b176c4 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -331,6 +331,7 @@ const sidebars: SidebarsConfig = {'effects/tv-signal-off','effects/uv-translate','effects/venetian-blinds',+ 'effects/vibrance','effects/vignette','effects/wave','effects/waves',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex df31351653..9f2764deab 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2339,6 +2339,15 @@ export const articles = [noAi: false,slug: 'effects/venetian-blinds',},+ {+ id: 'effects/vibrance',+ title: 'vibrance()',+ relativePath: 'docs/effects/vibrance.mdx',+ compId: 'articles-docs-effects-vibrance',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/vibrance',+ },{id: 'effects/vignette',title: 'vignette()',diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex 37274122b8..09eb409c48 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -93,6 +93,7 @@ import {} from '../../components/effects/effects-translate-preview';import {EffectsTvSignalOffPreview} from '../../components/effects/effects-tv-signal-off-preview';import {EffectsVenetianBlindsPreview} from '../../components/effects/effects-venetian-blinds-preview';+import {EffectsVibrancePreview} from '../../components/effects/effects-vibrance-preview';import {EffectsVignettePreview} from '../../components/effects/effects-vignette-preview';import {EffectsWavePreview} from '../../components/effects/effects-wave-preview';import {EffectsWavesPreview} from '../../components/effects/effects-waves-preview';@@ -297,6 +298,13 @@ export const RemotionRoot: React.FC = () => {height={720}defaultProps={{temperature: 0.8, tint: 0.2}}/>+ <Still+ id="effects-vibrance-preview"+ component={EffectsVibrancePreview}+ width={1280}+ height={720}+ defaultProps={{amount: 0.8}}+ /><Stillid="effects-venetian-blinds-preview"component={EffectsVenetianBlindsPreview}diff --git a/packages/docs/static/generated/articles-docs-effects-vibrance.png b/packages/docs/static/generated/articles-docs-effects-vibrance.pngnew file mode 100644index 0000000000..b1b8bde659Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-vibrance.png differdiff --git a/packages/docs/static/img/effects-vibrance-preview.png b/packages/docs/static/img/effects-vibrance-preview.pngnew file mode 100644index 0000000000..57c7dea60bBinary files /dev/null and b/packages/docs/static/img/effects-vibrance-preview.png differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 1c825569da..8ed41cce64 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -65,6 +65,7 @@ const effectEntrypoints = ['src/translate.ts','src/tv-signal-off.ts','src/venetian-blinds.ts',+ 'src/vibrance.ts','src/vignette.ts','src/wave.ts','src/waves.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex 2697676127..98e70370ef 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -324,6 +324,11 @@"module": "./dist/esm/venetian-blinds.mjs","import": "./dist/esm/venetian-blinds.mjs"},+ "./vibrance": {+ "types": "./dist/vibrance.d.ts",+ "module": "./dist/esm/vibrance.mjs",+ "import": "./dist/esm/vibrance.mjs"+ },"./vignette": {"types": "./dist/vignette.d.ts","module": "./dist/esm/vignette.mjs",@@ -537,6 +542,9 @@"venetian-blinds": ["dist/venetian-blinds.d.ts"],+ "vibrance": [+ "dist/vibrance.d.ts"+ ],"vignette": ["dist/vignette.d.ts"],diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex 3039f50988..129748201b 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -65,6 +65,7 @@ import {uvTranslate, xyTranslate} from '../translate.js';import {tvSignalOff} from '../tv-signal-off.js';import {publicUvToShaderUv} from '../uv-coordinate.js';import {venetianBlinds} from '../venetian-blinds.js';+import {vibrance} from '../vibrance.js';import {vignette} from '../vignette.js';import {wave} from '../wave/index.js';import {waves} from '../waves.js';@@ -266,6 +267,9 @@ test('@remotion/effects expose documentation links', () => {expect(venetianBlinds().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/venetian-blinds',);+ expect(vibrance().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/vibrance',+ );expect(uvTranslate().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/uv-translate',);@@ -361,6 +365,7 @@ test('@remotion/effects expose API names as Studio labels', () => {expect(tint({color: '#fff'}).definition.label).toBe('tint()');expect(tvSignalOff().definition.label).toBe('tvSignalOff()');expect(venetianBlinds().definition.label).toBe('venetianBlinds()');+ expect(vibrance().definition.label).toBe('vibrance()');expect(uvTranslate().definition.label).toBe('uvTranslate()');expect(vignette().definition.label).toBe('vignette()');expect(xyTranslate().definition.label).toBe('xyTranslate()');@@ -1014,6 +1019,30 @@ test('whiteBalance() parameters produce distinct effect keys', () => {).toBe(3);});+test('vibrance() accepts default params', () => {+ expect(() => vibrance()).not.toThrow();+});++test('vibrance() rejects non-finite amount', () => {+ expect(() => vibrance({amount: Number.NaN})).toThrow(+ '"amount" must be a finite number',+ );+});++test('vibrance() rejects amount outside the signed unit interval', () => {+ expect(() => vibrance({amount: -1.1})).toThrow('"amount" must be >= -1');+ expect(() => vibrance({amount: 1.1})).toThrow('"amount" must be <= 1');+});++test('vibrance() amount produces distinct effect keys', () => {+ const muted = vibrance({amount: -0.5});+ const neutral = vibrance();+ const vivid = vibrance({amount: 0.5});+ expect(+ new Set([muted.effectKey, neutral.effectKey, vivid.effectKey]).size,+ ).toBe(3);+});+test('contrast() accepts default params', () => {expect(() => contrast()).not.toThrow();});diff --git a/packages/effects/src/vibrance.ts b/packages/effects/src/vibrance.tsnew file mode 100644index 0000000000..0416aa5041--- /dev/null+++ b/packages/effects/src/vibrance.ts@@ -0,0 +1,271 @@+import type {InteractivitySchema} from 'remotion';+import {Internals} from 'remotion';+import {+ assertOptionalFiniteNumber,+ validateSignedUnitInterval,+} from './color-utils.js';+import {assertEffectParamsObject} from './validate-effect-param.js';++const {createEffect, createWebGL2ContextError} = Internals;++const DEFAULT_AMOUNT = 0 as const;++const vibranceSchema = {+ amount: {+ type: 'number',+ min: -1,+ max: 1,+ step: 0.01,+ default: DEFAULT_AMOUNT,+ description: 'Amount',+ hiddenFromList: false,+ },+} as const satisfies InteractivitySchema;++export type VibranceParams = {+ /** Vibrance adjustment from `-1` to `1`. Defaults to `0`. */+ readonly amount?: number;+};++type VibranceResolved = {+ amount: number;+};++type VibranceState = {+ readonly gl: WebGL2RenderingContext;+ readonly program: WebGLProgram;+ readonly vao: WebGLVertexArrayObject;+ readonly vbo: WebGLBuffer;+ readonly textureSource: WebGLTexture;+ readonly uniforms: {+ readonly uSource: WebGLUniformLocation | null;+ readonly uAmount: WebGLUniformLocation | null;+ };+};++const resolve = (params: VibranceParams): VibranceResolved => ({+ amount: params.amount ?? DEFAULT_AMOUNT,+});++const validateVibranceParams = (params: VibranceParams): void => {+ assertEffectParamsObject(params, 'Vibrance');+ assertOptionalFiniteNumber(params.amount, 'amount');++ const {amount} = resolve(params);+ validateSignedUnitInterval(amount, 'amount');+};++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 sourceColor = texture(uSource, vUv);+ float alpha = sourceColor.a;++ if (alpha <= 0.0) {+ fragColor = vec4(0.0);+ return;+ }++ 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);++ fragColor = vec4(clamp(adjusted, 0.0, 1.0) * alpha, alpha);+}+`;++const compileShader = (+ gl: WebGL2RenderingContext,+ type: number,+ source: string,+): WebGLShader => {+ const shader = gl.createShader(type);+ if (!shader) {+ throw new Error('Failed to create vibrance 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(`Vibrance 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 vibrance 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(`Vibrance 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 vibrance 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 setupVibrance = (target: HTMLCanvasElement): VibranceState => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('vibrance 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 vibrance vertex array');+ }++ const vbo = gl.createBuffer();+ if (!vbo) {+ throw new Error('Failed to create vibrance 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'),+ uAmount: gl.getUniformLocation(program, 'uAmount'),+ },+ };+};++export const vibrance = createEffect<VibranceParams, VibranceState>({+ type: 'remotion/vibrance',+ label: 'vibrance()',+ documentationLink: 'https://www.remotion.dev/docs/effects/vibrance',+ backend: 'webgl2',+ calculateKey: (params) => {+ const {amount} = resolve(params);+ return `vibrance-${amount}`;+ },+ setup: setupVibrance,+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const {amount} = 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.uAmount) gl.uniform1f(uniforms.uAmount, amount);+ 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: vibranceSchema,+ validateParams: validateVibranceParams,+});diff --git a/packages/effects/src/visual-test/effects-visual.test.ts b/packages/effects/src/visual-test/effects-visual.test.tsindex 057409691c..6eab8ae776 100644--- a/packages/effects/src/visual-test/effects-visual.test.ts+++ b/packages/effects/src/visual-test/effects-visual.test.ts@@ -4,6 +4,7 @@ import {evolve} from '../evolve.js';import {exposure} from '../exposure.js';import {noise} from '../noise.js';import {pixelDissolve} from '../pixel-dissolve.js';+import {vibrance} from '../vibrance.js';import {vignette} from '../vignette.js';import {whiteBalance} from '../white-balance.js';import {@@ -124,6 +125,53 @@ test('whiteBalance() applies temperature and tint while preserving alpha', asyncexpect(magentaPixel[3]).toBe(128);});+test('vibrance() boosts muted colors more than vivid colors', 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([+ 153, 102, 102, 128, 204, 51, 51, 128, 128, 128, 128, 128,+ ]),+ 3,+ 1,+ ),+ 0,+ 0,+ );++ const canvas = await renderEffectChainToCanvas({+ source,+ width: 3,+ height: 1,+ effects: descriptorsToMemoizedEffects([vibrance({amount: 0.5})]),+ });+ const context = canvas.getContext('2d');+ if (!context) {+ throw new Error('Could not get output context');+ }++ const pixels = context.getImageData(0, 0, 3, 1).data;+ const mutedRedChange = pixels[0] - 153;+ const vividRedChange = pixels[4] - 204;+ expect(mutedRedChange).toBeGreaterThanOrEqual(45);+ expect(vividRedChange).toBeGreaterThanOrEqual(20);+ expect(mutedRedChange).toBeGreaterThan(vividRedChange);+ expect(pixels[8]).toBeGreaterThanOrEqual(127);+ expect(pixels[8]).toBeLessThanOrEqual(129);+ expect(pixels[9]).toBe(pixels[8]);+ expect(pixels[10]).toBe(pixels[8]);+ expect(pixels[3]).toBe(128);+ expect(pixels[7]).toBe(128);+ expect(pixels[11]).toBe(128);+});+test('vignette() color mode works on transparent sources', async () => {const width = 40;const height = 40;diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.tsindex 2db3102852..370bce265f 100644--- a/packages/studio-shared/src/effect-catalog.ts+++ b/packages/studio-shared/src/effect-catalog.ts@@ -186,6 +186,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [config: {},},},+ {+ id: 'effects-vibrance',+ category: 'Color',+ label: 'vibrance()',+ description: 'Selective saturation adjustment',+ effect: {+ name: 'vibrance',+ importPath: '@remotion/effects/vibrance',+ config: {},+ },+ },{id: 'effects-linear-gradient',category: 'Color',