Skip to content

🎥 Make videos programmatically with React

8.5 KB
Raw Blame
import type {InteractivitySchema} 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_BLACK_POINT = 0 as const;
const DEFAULT_WHITE_POINT = 1 as const;
const DEFAULT_GAMMA = 1 as const;
const MIN_GAMMA = 0.01 as const;
const MAX_GAMMA = 10 as const;

const levelsSchema = {
	blackPoint: {
		type: 'number',
		min: 0,
		max: 1,
		step: 0.01,
		default: DEFAULT_BLACK_POINT,
		description: 'Black point',
		hiddenFromList: false,
	},
	whitePoint: {
		type: 'number',
		min: 0,
		max: 1,
		step: 0.01,
		default: DEFAULT_WHITE_POINT,
		description: 'White point',
		hiddenFromList: false,
	},
	gamma: {
		type: 'number',
		min: MIN_GAMMA,
		max: MAX_GAMMA,
		step: 0.01,
		default: DEFAULT_GAMMA,
		description: 'Gamma',
		hiddenFromList: false,
	},
} as const satisfies InteractivitySchema;

export type LevelsParams = {
	/** Input value mapped to black, from `0` to `1`. Defaults to `0`. */
	readonly blackPoint?: number;
	/** Input value mapped to white, from `0` to `1`. Defaults to `1`. */
	readonly whitePoint?: number;
	/** Midtone gamma from `0.01` to `10`. Defaults to `1`. */
	readonly gamma?: number;
};

type LevelsResolved = {
	blackPoint: number;
	whitePoint: number;
	gamma: number;
};

type LevelsState = {
	readonly gl: WebGL2RenderingContext;
	readonly program: WebGLProgram;
	readonly vao: WebGLVertexArrayObject;
	readonly vbo: WebGLBuffer;
	readonly textureSource: WebGLTexture;
	readonly uniforms: {
		readonly uSource: WebGLUniformLocation | null;
		readonly uBlackPoint: WebGLUniformLocation | null;
		readonly uWhitePoint: WebGLUniformLocation | null;
		readonly uGamma: WebGLUniformLocation | null;
	};
};

const resolve = (params: LevelsParams): LevelsResolved => ({
	blackPoint: params.blackPoint ?? DEFAULT_BLACK_POINT,
	whitePoint: params.whitePoint ?? DEFAULT_WHITE_POINT,
	gamma: params.gamma ?? DEFAULT_GAMMA,
});

const validateLevelsParams = (params: LevelsParams): void => {
	assertEffectParamsObject(params, 'Levels');
	assertOptionalFiniteNumber(params.blackPoint, 'blackPoint');
	assertOptionalFiniteNumber(params.whitePoint, 'whitePoint');
	assertOptionalFiniteNumber(params.gamma, 'gamma');

	const {blackPoint, whitePoint, gamma} = resolve(params);
	validateUnitInterval(blackPoint, 'blackPoint');
	validateUnitInterval(whitePoint, 'whitePoint');

	if (blackPoint >= whitePoint) {
		throw new TypeError(
			`"blackPoint" must be less than "whitePoint", but got ${JSON.stringify(blackPoint)} and ${JSON.stringify(whitePoint)}`,
		);
	}

	if (gamma < MIN_GAMMA) {
		throw new TypeError(
			`"gamma" must be >= ${MIN_GAMMA}, but got ${JSON.stringify(gamma)}`,
		);
	}

	if (gamma > MAX_GAMMA) {
		throw new TypeError(
			`"gamma" must be <= ${MAX_GAMMA}, but got ${JSON.stringify(gamma)}`,
		);
	}
};

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 uBlackPoint;
uniform float uWhitePoint;
uniform float uGamma;

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;
	vec3 normalized = clamp(
		(color - vec3(uBlackPoint)) / (uWhitePoint - uBlackPoint),
		0.0,
		1.0
	);
	vec3 corrected = pow(normalized, vec3(1.0 / uGamma));

	fragColor = vec4(corrected * alpha, alpha);
}
`;

const compileShader = (
	gl: WebGL2RenderingContext,
	type: number,
	source: string,
): WebGLShader => {
	const shader = gl.createShader(type);
	if (!shader) {
		throw new Error('Failed to create levels 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(`Levels 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 levels 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(`Levels 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 levels 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 setupLevels = (target: HTMLCanvasElement): LevelsState => {
	const gl = target.getContext('webgl2', {
		premultipliedAlpha: true,
		alpha: true,
		preserveDrawingBuffer: true,
	});
	if (!gl) {
		throw createWebGL2ContextError('levels 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 levels vertex array');
	}

	const vbo = gl.createBuffer();
	if (!vbo) {
		throw new Error('Failed to create levels 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'),
			uBlackPoint: gl.getUniformLocation(program, 'uBlackPoint'),
			uWhitePoint: gl.getUniformLocation(program, 'uWhitePoint'),
			uGamma: gl.getUniformLocation(program, 'uGamma'),
		},
	};
};

export const levels = createEffect<LevelsParams, LevelsState>({
	type: 'remotion/levels',
	label: 'levels()',
	documentationLink: 'https://www.remotion.dev/docs/effects/levels',
	backend: 'webgl2',
	calculateKey: (params) => {
		const {blackPoint, whitePoint, gamma} = resolve(params);
		return `levels-${blackPoint}-${whitePoint}-${gamma}`;
	},
	setup: setupLevels,
	apply: ({source, width, height, params, state, flipSourceY}) => {
		const {blackPoint, whitePoint, gamma} = 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.uBlackPoint) {
			gl.uniform1f(uniforms.uBlackPoint, blackPoint);
		}

		if (uniforms.uWhitePoint) {
			gl.uniform1f(uniforms.uWhitePoint, whitePoint);
		}

		if (uniforms.uGamma) gl.uniform1f(uniforms.uGamma, gamma);
		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: levelsSchema,
	validateParams: validateLevelsParams,
});