🎥 Make videos programmatically with React
`@remotion/effects`: Add noise effect
Igor Samokhovetsc949a0dafea2
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsxindex 016e115511..55dbc50d53 100644--- a/packages/docs/components/demos/index.tsx+++ b/packages/docs/components/demos/index.tsx@@ -31,6 +31,7 @@ import {effectsInvertDemo,effectsLightLeakDemo,effectsMirrorDemo,+ effectsNoiseDemo,effectsSaturationDemo,effectsScaleDemo,effectsShineDemo,@@ -105,6 +106,7 @@ const demos: DemoType[] = [effectsTintDemo,effectsShineDemo,effectsMirrorDemo,+ effectsNoiseDemo,effectsScaleDemo,effectsXyTranslateDemo,effectsUvTranslateDemo,diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.tsindex e7aefa995a..be85b22f3f 100644--- a/packages/docs/components/demos/types.ts+++ b/packages/docs/components/demos/types.ts@@ -13,6 +13,7 @@ import {EffectsHuePreview} from '../effects/effects-hue-preview';import {EffectsInvertPreview} from '../effects/effects-invert-preview';import {EffectsLightLeakPreview} from '../effects/effects-light-leak-preview';import {EffectsMirrorPreview} from '../effects/effects-mirror-preview';+import {EffectsNoisePreview} from '../effects/effects-noise-preview';import {EffectsSaturationPreview} from '../effects/effects-saturation-preview';import {EffectsScalePreview} from '../effects/effects-scale-preview';import {EffectsShinePreview} from '../effects/effects-shine-preview';@@ -1919,6 +1920,44 @@ export const effectsBarrelDistortionDemo: DemoType = {],};+export const effectsNoiseDemo: DemoType = {+ comp: EffectsNoisePreview,+ compHeight: 720,+ compWidth: 1280,+ durationInFrames: 1,+ fps: 30,+ id: 'effects-noise',+ autoPlay: false,+ controls: false,+ logLevel: 'info',+ options: [+ {+ name: 'amount',+ type: 'numeric',+ min: 0,+ max: 1,+ step: 0.01,+ default: 0.25,+ optional: 'no',+ },+ {+ name: 'seed',+ type: 'numeric',+ min: 0,+ max: 100,+ step: 1,+ default: 0,+ optional: 'no',+ },+ {+ name: 'premultiply',+ type: 'boolean',+ default: false,+ optional: 'no',+ },+ ],+};+export const effectsVignetteDemo: DemoType = {comp: EffectsVignettePreview,compHeight: 720,diff --git a/packages/docs/components/effects/effects-noise-preview.tsx b/packages/docs/components/effects/effects-noise-preview.tsxnew file mode 100644index 0000000000..48bf6844f9--- /dev/null+++ b/packages/docs/components/effects/effects-noise-preview.tsx@@ -0,0 +1,20 @@+import {noise} from '@remotion/effects/noise';+import React from 'react';+import {CanvasImage} from 'remotion';+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';++export const EffectsNoisePreview: React.FC<{+ readonly amount: number;+ readonly seed: number;+ readonly premultiply: boolean;+}> = ({amount, seed, premultiply}) => {+ return (+ <CanvasImage+ src={EFFECTS_PREVIEW_IMAGE_SRC}+ width={1280}+ height={720}+ fit="cover"+ effects={[noise({amount, seed, premultiply})]}+ />+ );+};diff --git a/packages/docs/docs/effects/noise.mdx b/packages/docs/docs/effects/noise.mdxnew file mode 100644index 0000000000..cedf4fb93c--- /dev/null+++ b/packages/docs/docs/effects/noise.mdx@@ -0,0 +1,81 @@+---+image: /generated/articles-docs-effects-noise.png+slug: /effects/noise+title: noise()+sidebar_label: noise()+crumb: '@remotion/effects'+---++# noise()<AvailableFrom v="4.0.469" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Adds centered procedural noise to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).++The effect preserves the source alpha mask. Transparent regions stay transparent.++## Preview++<Demo type="effects-noise" />++## Example++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill} from 'remotion';+import {Video} from '@remotion/media';+import {noise} from '@remotion/effects/noise';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Video+ src="https://remotion.media/video.mp4"+ effects={[+ noise({+ amount: 0.25,+ seed: 7,+ premultiply: false,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties. You can also call `noise()` without arguments.++### `amount?`++Strength from `0` to `1`. Defaults to `0.15`.++Use `0` to leave the layer unchanged.++### `seed?`++Seed for the random noise pattern. Defaults to `0`.++Change it to get a different static noise pattern. The noise is visible without animating the seed. To animate the noise, pass a value derived from [`useCurrentFrame()`](/docs/use-current-frame).++### `premultiply?`++Whether the centered noise is multiplied with the input colors before being added. Defaults to `false`.++Set to `true` for a subtler noise that follows the source brightness more closely.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`noise()` 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)+- [`vignette()`](/docs/effects/vignette)+- [`glow()`](/docs/effects/glow)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/noise.ts)diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsxindex c52dc26b15..46591c1788 100644--- a/packages/docs/docs/effects/table-of-contents.tsx+++ b/packages/docs/docs/effects/table-of-contents.tsx@@ -172,6 +172,13 @@ const categories: {name: 'halftoneLinearGradient()',description: 'Linear dot size gradient',},+ {+ link: '/docs/effects/noise',+ preview: '/img/effects-noise-preview.jpg',+ alt: 'noise effect preview',+ name: 'noise()',+ description: 'Procedural grain effect',+ },{link: '/docs/starburst/starburst-effect',preview: '/img/effects-starburst-preview.jpg',diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex deb96480d7..72925c19d4 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -281,6 +281,7 @@ const sidebars: SidebarsConfig = {'effects/hue','effects/invert','effects/mirror',+ 'effects/noise','effects/saturation','effects/scale','effects/shine',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex b70054e8a0..8ab38043f2 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1844,6 +1844,15 @@ export const articles = [noAi: false,slug: 'effects/mirror',},+ {+ id: 'effects/noise',+ title: 'noise()',+ relativePath: 'docs/effects/noise.mdx',+ compId: 'articles-docs-effects-noise',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/noise',+ },{id: 'effects/saturation',title: 'saturation()',diff --git a/packages/docs/static/generated/articles-docs-effects-noise.png b/packages/docs/static/generated/articles-docs-effects-noise.pngnew file mode 100644index 0000000000..8934f0c834Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-noise.png differdiff --git a/packages/docs/static/img/effects-noise-preview.jpg b/packages/docs/static/img/effects-noise-preview.jpgnew file mode 100644index 0000000000..083ad10834Binary files /dev/null and b/packages/docs/static/img/effects-noise-preview.jpg differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 563c42ba31..498333106b 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -20,6 +20,7 @@ const effectEntrypoints = ['src/hue.ts','src/invert.ts','src/mirror.ts',+ 'src/noise.ts','src/saturation.ts','src/scale.ts','src/shine.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex b26e244f79..e16cc4a5d9 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -97,6 +97,11 @@"module": "./dist/esm/mirror.mjs","import": "./dist/esm/mirror.mjs"},+ "./noise": {+ "types": "./dist/noise.d.ts",+ "module": "./dist/esm/noise.mjs",+ "import": "./dist/esm/noise.mjs"+ },"./saturation": {"types": "./dist/saturation.d.ts","module": "./dist/esm/saturation.mjs",@@ -175,6 +180,9 @@"mirror": ["dist/mirror.d.ts"],+ "noise": [+ "dist/noise.d.ts"+ ],"saturation": ["dist/saturation.d.ts"],diff --git a/packages/effects/src/noise.ts b/packages/effects/src/noise.tsnew file mode 100644index 0000000000..7e2b6300c0--- /dev/null+++ b/packages/effects/src/noise.ts@@ -0,0 +1,307 @@+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 = 0.15 as const;+const DEFAULT_SEED = 0 as const;+const DEFAULT_PREMULTIPLY = false as const;++const noiseSchema = {+ amount: {+ type: 'number',+ min: 0,+ max: 1,+ step: 0.01,+ default: DEFAULT_AMOUNT,+ description: 'Amount',+ },+ seed: {+ type: 'number',+ step: 1,+ default: DEFAULT_SEED,+ description: 'Seed',+ },+ premultiply: {+ type: 'boolean',+ default: DEFAULT_PREMULTIPLY,+ description: 'Premultiply',+ },+} as const satisfies SequenceSchema;++export type NoiseParams = {+ /** Strength of the noise from `0` to `1`. Defaults to `0.15`. */+ readonly amount?: number;+ /** Seed for the random noise pattern. Defaults to `0`. */+ readonly seed?: number;+ /** Multiply the noise with the input colors before blending. Defaults to `false`. */+ readonly premultiply?: boolean;+};++type NoiseResolved = {+ amount: number;+ seed: number;+ premultiply: boolean;+};++type NoiseState = {+ readonly gl: WebGL2RenderingContext;+ readonly program: WebGLProgram;+ readonly vao: WebGLVertexArrayObject;+ readonly vbo: WebGLBuffer;+ readonly texture: WebGLTexture;+ readonly uSource: WebGLUniformLocation | null;+ readonly uResolution: WebGLUniformLocation | null;+ readonly uAmount: WebGLUniformLocation | null;+ readonly uSeed: WebGLUniformLocation | null;+ readonly uPremultiply: WebGLUniformLocation | null;+};++const resolve = (p: NoiseParams): NoiseResolved => ({+ amount: p.amount ?? DEFAULT_AMOUNT,+ seed: p.seed ?? DEFAULT_SEED,+ premultiply: p.premultiply ?? DEFAULT_PREMULTIPLY,+});++const assertOptionalBoolean = (value: unknown, name: string): void => {+ if (value === undefined) {+ return;+ }++ if (typeof value !== 'boolean') {+ throw new TypeError(+ `"${name}" must be a boolean, but got ${JSON.stringify(value)}`,+ );+ }+};++const validateNoiseParams = (params: NoiseParams): void => {+ assertEffectParamsObject(params, 'Noise');+ assertOptionalFiniteNumber(params.amount, 'amount');+ assertOptionalFiniteNumber(params.seed, 'seed');+ assertOptionalBoolean(params.premultiply, 'premultiply');++ const r = resolve(params);+ validateUnitInterval(r.amount, 'amount');+};++const NOISE_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 NOISE_FS = /* glsl */ `#version 300 es+precision highp float;++in vec2 vUv;+out vec4 fragColor;++uniform sampler2D uSource;+uniform vec2 uResolution;+uniform float uAmount;+uniform float uSeed;+uniform bool uPremultiply;++float random(vec2 co) {+ vec3 p3 = fract(vec3(co.xyx) * 0.1031 + uSeed * 0.0973);+ p3 += dot(p3, p3.yzx + 33.33);+ return fract((p3.x + p3.y) * p3.z);+}++void main() {+ vec4 texColor = texture(uSource, vUv);+ float alpha = texColor.a;++ if (alpha <= 0.001) {+ fragColor = vec4(0.0);+ return;+ }++ float noise = random(gl_FragCoord.xy) - 0.5;+ vec3 rgb = texColor.rgb / alpha;+ vec3 noiseLayer = uPremultiply ? rgb * noise : vec3(noise);+ rgb = clamp(rgb + noiseLayer * uAmount, 0.0, 1.0);+ fragColor = vec4(rgb * 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(`Noise 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(`Noise program link failed: ${log ?? '(no log)'}`);+ }++ return program;+};++const setupNoise = (target: HTMLCanvasElement): NoiseState => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('noise effect');+ }++ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);++ const vs = compileShader(gl, gl.VERTEX_SHADER, NOISE_VS);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, NOISE_FS);+ const program = linkProgram(gl, vs, fs);+ gl.deleteShader(vs);+ gl.deleteShader(fs);++ const vao = gl.createVertexArray();+ if (!vao) {+ throw new Error('Failed to create WebGL vertex array');+ }++ gl.bindVertexArray(vao);++ const data = new Float32Array([+ -1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1,+ ]);++ const vbo = gl.createBuffer();+ if (!vbo) {+ throw new Error('Failed to create WebGL buffer');+ }++ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);+ gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);++ const aPos = gl.getAttribLocation(program, 'aPos');+ const aUv = gl.getAttribLocation(program, 'aUv');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(aUv);+ gl.vertexAttribPointer(aUv, 2, gl.FLOAT, false, 16, 8);++ gl.bindVertexArray(null);++ const texture = gl.createTexture();+ if (!texture) {+ throw new Error('Failed to create WebGL texture');+ }++ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.bindTexture(gl.TEXTURE_2D, null);++ return {+ gl,+ program,+ vao,+ vbo,+ texture,+ uSource: gl.getUniformLocation(program, 'uSource'),+ uResolution: gl.getUniformLocation(program, 'uResolution'),+ uAmount: gl.getUniformLocation(program, 'uAmount'),+ uSeed: gl.getUniformLocation(program, 'uSeed'),+ uPremultiply: gl.getUniformLocation(program, 'uPremultiply'),+ };+};++export const noise = createEffect<NoiseParams, NoiseState>({+ type: 'remotion/noise',+ label: 'noise()',+ documentationLink: 'https://www.remotion.dev/docs/effects/noise',+ backend: 'webgl2',+ calculateKey: (params) => {+ const r = resolve(params);+ return `noise-${r.amount}-${r.seed}-${r.premultiply ? 1 : 0}`;+ },+ setup: (target) => setupNoise(target),+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const r = resolve(params);+ const {gl, program, texture, vao} = state;++ gl.viewport(0, 0, width, height);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ source as TexImageSource,+ );++ gl.useProgram(program);+ if (state.uSource) gl.uniform1i(state.uSource, 0);+ if (state.uResolution) gl.uniform2f(state.uResolution, width, height);+ if (state.uAmount) gl.uniform1f(state.uAmount, r.amount);+ if (state.uSeed) gl.uniform1f(state.uSeed, r.seed);+ if (state.uPremultiply)+ gl.uniform1i(state.uPremultiply, r.premultiply ? 1 : 0);++ gl.bindVertexArray(vao);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ gl.bindVertexArray(null);+ gl.bindTexture(gl.TEXTURE_2D, null);+ gl.useProgram(null);+ },+ cleanup: ({gl, program, vao, vbo, texture}) => {+ gl.deleteTexture(texture);+ gl.deleteBuffer(vbo);+ gl.deleteProgram(program);+ gl.deleteVertexArray(vao);+ },+ schema: noiseSchema,+ validateParams: validateNoiseParams,+});diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex 6afb7cfafd..9aa07745e2 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -12,6 +12,7 @@ import {halftone} from '../halftone.js';import {hue} from '../hue.js';import {invert} from '../invert.js';import {mirror} from '../mirror.js';+import {noise} from '../noise.js';import {saturation} from '../saturation.js';import {scale} from '../scale.js';import {shine} from '../shine.js';@@ -60,6 +61,9 @@ test('@remotion/effects expose documentation links', () => {expect(mirror().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/mirror',);+ expect(noise().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/noise',+ );expect(saturation().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/saturation',);@@ -101,6 +105,7 @@ test('@remotion/effects expose API names as Studio labels', () => {expect(hue().definition.label).toBe('hue()');expect(invert().definition.label).toBe('invert()');expect(mirror().definition.label).toBe('mirror()');+ expect(noise().definition.label).toBe('noise()');expect(saturation().definition.label).toBe('saturation()');expect(scale({scale: 1}).definition.label).toBe('scale()');expect(shine().definition.label).toBe('shine()');@@ -777,6 +782,52 @@ test('mirror() parameters produce distinct effect keys', () => {).toBe(4);});+test('noise() accepts default params', () => {+ expect(() => noise()).not.toThrow();+});++test('noise() rejects non-finite amount', () => {+ expect(() => noise({amount: Number.NaN})).toThrow(+ '"amount" must be a finite number',+ );+});++test('noise() rejects amount below range', () => {+ expect(() => noise({amount: -0.1})).toThrow('"amount" must be >= 0');+});++test('noise() rejects amount above range', () => {+ expect(() => noise({amount: 1.1})).toThrow('"amount" must be <= 1');+});++test('noise() rejects non-finite seed', () => {+ expect(() => noise({seed: Number.NaN})).toThrow(+ '"seed" must be a finite number',+ );+});++test('noise() rejects non-boolean premultiply', () => {+ expect(() => noise({premultiply: 'yes' as unknown as boolean})).toThrow(+ '"premultiply" must be a boolean',+ );+});++test('noise() parameters produce distinct effect keys', () => {+ const subtle = noise({amount: 0.1});+ const strong = noise({amount: 0.3});+ const seeded = noise({amount: 0.3, seed: 1});+ const premultiplied = noise({amount: 0.3, premultiply: true});++ expect(+ new Set([+ subtle.effectKey,+ strong.effectKey,+ seeded.effectKey,+ premultiplied.effectKey,+ ]).size,+ ).toBe(4);+});+test('saturation() accepts default params', () => {expect(() => saturation()).not.toThrow();});