Skip to content

🎥 Make videos programmatically with React

7.0 KB
Raw Blame
import type {CanvasCaptureData} from '@remotion/studio-shared';
import * as recast from 'recast';

type FramedMouseMovement = CanvasCaptureData['mouseMovements'][number] & {
	readonly frame: number;
};

const customCursorRegex = /^\s*url\(/;

const collapseMouseMovementsByFrame = ({
	data,
	keyframeFps,
}: {
	readonly data: CanvasCaptureData;
	readonly keyframeFps: number;
}) => {
	const movements: FramedMouseMovement[] = [];

	for (const movement of data.mouseMovements) {
		if (movement.canvasX === null || movement.canvasY === null) {
			continue;
		}

		const framedMovement = {
			...movement,
			frame: Math.ceil(movement.timeInSeconds * keyframeFps),
		};
		const previous = movements.at(-1);
		if (previous?.frame === framedMovement.frame) {
			movements[movements.length - 1] = framedMovement;
		} else {
			movements.push(framedMovement);
		}
	}

	return movements;
};

const getCursorName = (cursor: string) => {
	if (customCursorRegex.test(cursor)) {
		return 'custom';
	}

	return cursor.split(',').at(-1)?.trim().toLowerCase() || 'default';
};

const serialize = (value: unknown): string => {
	if (typeof value === 'string') {
		return recast.prettyPrint(recast.types.builders.stringLiteral(value), {
			quote: 'single',
		}).code;
	}

	return JSON.stringify(value);
};

const serializeArray = (values: (string | number)[], indentation: number) => {
	const items = values.map(serialize);
	const inline = `[${items.join(', ')}]`;
	if (indentation * 2 + inline.length + 1 <= 80) {
		return inline;
	}

	const lines: string[] = [];
	const numeric = values.every((value) => typeof value === 'number');
	for (const item of items) {
		const previous = lines.at(-1);
		if (
			numeric &&
			previous &&
			(indentation + 1) * 2 + previous.length + item.length + 2 <= 80
		) {
			lines[lines.length - 1] = `${previous} ${item},`;
		} else {
			lines.push(`${item},`);
		}
	}

	return [
		'[',
		...lines.map((line) => `${'\t'.repeat(indentation + 1)}${line}`),
		`${'\t'.repeat(indentation)}]`,
	].join('\n');
};

export const generateCanvasCaptureComposition = ({
	componentName,
	data,
	durationInFrames,
	keyframeFps,
	videoFileName,
	videoHeight,
	videoWidth,
}: {
	readonly componentName: string;
	readonly data: CanvasCaptureData;
	readonly durationInFrames: number;
	readonly keyframeFps: number;
	readonly videoFileName: string;
	readonly videoHeight: number;
	readonly videoWidth: number;
}) => {
	const movements = collapseMouseMovementsByFrame({data, keyframeFps});
	if (movements.length === 0) {
		throw new Error('The Canvas Capture does not contain cursor movements');
	}

	const cursorKeyframes = movements.reduce<
		Array<{readonly frame: number; readonly value: string}>
	>((keyframes, movement) => {
		const value = getCursorName(movement.cursor);
		if (keyframes.at(-1)?.value !== value) {
			keyframes.push({frame: movement.frame, value});
		}

		return keyframes;
	}, []);

	const positionKeyframes: Array<{
		readonly frame: number;
		readonly value: string;
	}> = [];
	for (const movement of movements) {
		const previous = positionKeyframes.at(-1);
		if (previous !== undefined && movement.frame - previous.frame > 1) {
			positionKeyframes.push({
				frame: movement.frame - 1,
				value: previous.value,
			});
		}

		positionKeyframes.push({
			frame: movement.frame,
			value: `${movement.canvasX}px ${movement.canvasY}px`,
		});
	}

	const scaleKeyframes = [
		{frame: 0, value: data.captureMetadata.density},
		...data.pointerClicks.map((click) => ({
			frame: Math.ceil(click.timeInSeconds * keyframeFps),
			value:
				click.type === 'pointer-down'
					? data.captureMetadata.density * 0.9
					: data.captureMetadata.density,
		})),
	].reduce<Array<{readonly frame: number; readonly value: number}>>(
		(keyframes, keyframe) => {
			if (keyframes.at(-1)?.frame === keyframe.frame) {
				keyframes[keyframes.length - 1] = keyframe;
			} else if (keyframes.at(-1)?.value !== keyframe.value) {
				keyframes.push(keyframe);
			}

			return keyframes;
		},
		[],
	);

	const customCursorKeyframes = movements.reduce<
		Array<{readonly frame: number; readonly value: string}>
	>((keyframes, movement) => {
		if (!customCursorRegex.test(movement.cursor)) {
			return keyframes;
		}

		if (keyframes.at(-1)?.value !== movement.cursor) {
			keyframes.push({frame: movement.frame, value: movement.cursor});
		}

		return keyframes;
	}, []);
	const cursorProp =
		cursorKeyframes.length === 1
			? `cursor={${serialize(cursorKeyframes[0].value)}}`
			: `cursor={interpolate(
					frame,
					${serializeArray(
						cursorKeyframes.map((keyframe) => keyframe.frame),
						5,
					)},
					${serializeArray(
						cursorKeyframes.map((keyframe) => keyframe.value),
						5,
					)},
					{
						easing: Easing.step1,
						extrapolateLeft: 'clamp',
						extrapolateRight: 'clamp',
					},
				)}`;
	// Keep the cursor shape as a direct interpolation so timeline moves retime it
	// together with the cursor's position and scale.
	const customCursorProp =
		customCursorKeyframes.length === 0
			? ''
			: customCursorKeyframes.length === 1
				? `\t\t\t\tcustomCursor={${serialize(customCursorKeyframes[0].value)}}\n`
				: `\t\t\t\tcustomCursor={interpolate(
					frame,
					${serializeArray(
						customCursorKeyframes.map((keyframe) => keyframe.frame),
						5,
					)},
					${serializeArray(
						customCursorKeyframes.map((keyframe) => keyframe.value),
						5,
					)},
					{
						easing: Easing.step1,
						extrapolateLeft: 'clamp',
						extrapolateRight: 'clamp',
					},
				)}
`;
	const scale =
		scaleKeyframes.length === 1
			? serialize(scaleKeyframes[0].value)
			: `interpolate(
						frame,
						${serializeArray(
							scaleKeyframes.map((keyframe) => keyframe.frame),
							6,
						)},
						${serializeArray(
							scaleKeyframes.map((keyframe) => keyframe.value),
							6,
						)},
						{
							easing: Easing.step1,
							extrapolateLeft: 'clamp',
							extrapolateRight: 'clamp',
						},
					)`;
	const translate =
		positionKeyframes.length === 1
			? serialize(positionKeyframes[0].value)
			: `interpolate(
						frame,
						${serializeArray(
							positionKeyframes.map((keyframe) => keyframe.frame),
							6,
						)},
						${serializeArray(
							positionKeyframes.map((keyframe) => keyframe.value),
							6,
						)},
						{
							extrapolateLeft: 'clamp',
							extrapolateRight: 'clamp',
						},
					)`;

	return `import {MacOSCursor} from '@remotion/mac-cursors';
import {Video} from '@remotion/media';
import {
	AbsoluteFill,
	Easing,
	interpolate,
	staticFile,
	useCurrentFrame,
} from 'remotion';

export const ${componentName} = () => {
	const frame = useCurrentFrame();

	return (
		<AbsoluteFill
			name="Canvas Capture"
			durationInFrames={${durationInFrames}}
			style={{
				width: ${videoWidth},
				height: ${videoHeight},
			}}
		>
			<Video
				src={staticFile(${serialize(videoFileName)})}
				durationInFrames={${durationInFrames}}
				style={{
					position: 'absolute',
				}}
			/>
			<MacOSCursor
				${cursorProp}
${customCursorProp}				style={{
					position: 'absolute',
					left: 0,
					top: 0,
					scale: ${scale},
					translate: ${translate},
				}}
			/>
		</AbsoluteFill>
	);
};
`;
};