Skip to content

🎥 Make videos programmatically with React

8.9 KB
Raw Blame
import type {StorageClass} from '@aws-sdk/client-s3';
import type {
	AudioCodec,
	ChromiumOptions,
	ColorSpace,
	LogLevel,
	PixelFormat,
	SingleFrameRange,
	ToOptions,
	VideoImageFormat,
	X264Preset,
} from '@remotion/renderer';
import type {BrowserSafeApis} from '@remotion/renderer/client';
import type {_InternalTypes} from 'remotion';
import {NoReactInternals, type DownloadBehavior} from 'remotion/no-react';
import {VERSION} from 'remotion/version';
import {
	compressInputProps,
	getNeedsToUpload,
	serializeOrThrow,
} from './compress-props';
import type {GetRenderProgressInput} from './get-render-progress';
import {getSizeInBytes} from './get-size-in-bytes';
import type {ServerlessRenderOutput} from './image-sequence';
import type {AwsRegion} from './regions';
import type {RenderStillOnLambdaNonNullInput} from './render-still-on-lambda';
import {getRendererFunctionTransport} from './renderer-transport';
import {
	ServerlessRoutines,
	type DeleteAfter,
	type OutNameInput,
	type OutNameInputWithKey,
	type Privacy,
	type ServerlessCodec,
	type ServerlessPayloads,
	type ServerlessStartPayload,
	type ServerlessStatusPayload,
	type WebhookOption,
} from './shared-constants';
import type {RequestHandler} from './types';
import {validateDownloadBehavior} from './validate-download-behavior';
import {validateLambdaCodec} from './validate-lambda-codec';
import {validateServeUrl} from './validate-serveurl';
import {validateWebhook} from './validate-webhook';

export type InnerRenderMediaOnLambdaInput = {
	enableCancellation: boolean;
	region: AwsRegion;
	functionName: string;
	serveUrl: string;
	composition: string;
	inputProps: Record<string, unknown>;
	codec: ServerlessCodec | null;
	output: ServerlessRenderOutput;
	imageFormat: VideoImageFormat;
	crf: number | undefined;
	envVariables: Record<string, string>;
	pixelFormat: PixelFormat | undefined;
	proResProfile: _InternalTypes['ProResProfile'] | undefined;
	x264Preset: X264Preset | null;
	gopSize: number | null;
	privacy: Privacy;
	jpegQuality: number;
	maxRetries: number;
	framesPerLambda: number | null;
	concurrency: number | null;
	logLevel: LogLevel;
	frameRange: SingleFrameRange | null;
	outName: OutNameInput | null;
	separateAudioTo: OutNameInputWithKey | null;
	timeoutInMilliseconds: number;
	chromiumOptions: ChromiumOptions;
	scale: number;
	everyNthFrame: number;
	numberOfGifLoops: number | null;
	concurrencyPerLambda: number;
	downloadBehavior: DownloadBehavior;
	muted: boolean;
	overwrite: boolean | undefined;
	audioBitrate: string | null;
	videoBitrate: string | null;
	encodingMaxRate: string | null;
	encodingBufferSize: string | null;
	webhook: WebhookOption | null;
	forceWidth: number | null;
	forceHeight: number | null;
	forceFps: number | null;
	forceDurationInFrames: number | null;
	rendererFunctionName: string | null;
	forceBucketName: string | null;
	audioCodec: AudioCodec | null;
	colorSpace: ColorSpace | null;
	deleteAfter: DeleteAfter | null;
	indent: boolean;
	forcePathStyle: boolean;
	metadata: Record<string, string> | null;
	storageClass: StorageClass | null;
	requestHandler: RequestHandler | null;
	isProduction: boolean | null;
} & ToOptions<
	Omit<typeof BrowserSafeApis.optionsMap.renderMediaOnLambda, 'apiKey'>
>;

export const makeLambdaRenderMediaPayload = async ({
	enableCancellation,
	rendererFunctionName,
	frameRange,
	framesPerLambda,
	concurrency,
	forceBucketName: bucketName,
	codec,
	output,
	composition,
	serveUrl,
	imageFormat,
	inputProps,
	region,
	crf,
	envVariables,
	pixelFormat,
	proResProfile,
	x264Preset,
	gopSize,
	disableSharedMemoryCapture,
	maxRetries,
	privacy,
	logLevel,
	outName,
	separateAudioTo,
	timeoutInMilliseconds,
	chromiumOptions,
	scale,
	everyNthFrame,
	numberOfGifLoops,
	audioBitrate,
	concurrencyPerLambda,
	audioCodec,
	forceHeight,
	forceWidth,
	forceFps,
	forceDurationInFrames,
	webhook,
	videoBitrate,
	encodingMaxRate,
	encodingBufferSize,
	downloadBehavior,
	muted,
	overwrite,
	jpegQuality,
	offthreadVideoCacheSizeInBytes,
	mediaCacheSizeInBytes,
	deleteAfter,
	colorSpace,
	preferLossless,
	forcePathStyle,
	metadata,
	licenseKey,
	offthreadVideoThreads,
	storageClass,
	requestHandler,
	isProduction,
	sampleRate,
}: InnerRenderMediaOnLambdaInput): Promise<ServerlessStartPayload> => {
	const actualCodec = codec === null ? null : validateLambdaCodec(codec);

	if ((output.type === 'sequence') !== (actualCodec === null)) {
		throw new Error(
			'Image sequence renders must omit the codec. Media renders require a codec.',
		);
	}

	validateServeUrl(serveUrl);
	validateDownloadBehavior(downloadBehavior);
	validateWebhook(webhook);

	const stringifiedInputProps = serializeOrThrow(
		inputProps ?? {},
		'input-props',
	);

	const serialized = await compressInputProps({
		stringifiedInputProps,
		region,
		needsToUpload: getNeedsToUpload({
			type: 'video-or-audio',
			sizes: [
				getSizeInBytes(stringifiedInputProps),
				getSizeInBytes(JSON.stringify(envVariables)),
			],
		}),
		userSpecifiedBucketName: bucketName ?? null,
		propsType: 'input-props',
		forcePathStyle: forcePathStyle ?? false,
		skipPutAcl: privacy === 'no-acl',
		requestHandler: requestHandler ?? null,
		logLevel,
	});
	return {
		enableCancellation,
		rendererFunctionName,
		framesPerLambda,
		concurrency,
		composition,
		serveUrl,
		inputProps: serialized,
		codec: actualCodec,
		output,
		imageFormat,
		crf: crf ?? null,
		envVariables,
		pixelFormat: pixelFormat ?? null,
		proResProfile: proResProfile ?? null,
		x264Preset,
		gopSize,
		disableSharedMemoryCapture,
		jpegQuality,
		maxRetries,
		privacy,
		logLevel,
		frameRange,
		outName,
		separateAudioTo,
		timeoutInMilliseconds,
		chromiumOptions,
		scale,
		everyNthFrame,
		numberOfGifLoops,
		concurrencyPerLambda,
		downloadBehavior,
		muted,
		version: VERSION,
		overwrite: overwrite ?? NoReactInternals.ENABLE_V5_BREAKING_CHANGES,
		audioBitrate: audioBitrate ?? null,
		videoBitrate: videoBitrate ?? null,
		encodingBufferSize: encodingBufferSize ?? null,
		encodingMaxRate: encodingMaxRate ?? null,
		webhook: webhook ?? null,
		forceHeight: forceHeight ?? null,
		forceWidth: forceWidth ?? null,
		forceFps: forceFps ?? null,
		forceDurationInFrames: forceDurationInFrames ?? null,
		bucketName: bucketName ?? null,
		audioCodec: audioCodec ?? null,
		type: ServerlessRoutines.start,
		offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytes ?? null,
		deleteAfter: deleteAfter ?? null,
		colorSpace: colorSpace ?? null,
		preferLossless: preferLossless ?? false,
		forcePathStyle: forcePathStyle ?? false,
		metadata: metadata ?? null,
		licenseKey: licenseKey ?? null,
		offthreadVideoThreads: offthreadVideoThreads ?? null,
		mediaCacheSizeInBytes: mediaCacheSizeInBytes ?? null,
		storageClass: storageClass ?? null,
		isProduction,
		sampleRate,
	};
};

export const getRenderProgressPayload = ({
	bucketName,
	renderId,
	s3OutputProvider,
	logLevel,
	forcePathStyle,
}: GetRenderProgressInput): ServerlessStatusPayload => {
	return {
		type: ServerlessRoutines.status,
		bucketName,
		renderId,
		version: VERSION,
		s3OutputProvider: s3OutputProvider ?? null,
		logLevel: logLevel ?? 'info',
		forcePathStyle: forcePathStyle ?? false,
	};
};

export const makeLambdaRenderStillPayload = async ({
	serveUrl,
	inputProps,
	imageFormat,
	envVariables,
	jpegQuality,
	region,
	maxRetries,
	composition,
	privacy,
	frame,
	logLevel,
	outName,
	timeoutInMilliseconds,
	chromiumOptions,
	scale,
	downloadBehavior,
	forceHeight,
	forceWidth,
	forceFps,
	forceDurationInFrames,
	forceBucketName,
	offthreadVideoCacheSizeInBytes,
	deleteAfter,
	forcePathStyle,
	licenseKey,
	storageClass,
	requestHandler,
	offthreadVideoThreads,
	mediaCacheSizeInBytes,
	isProduction,
}: RenderStillOnLambdaNonNullInput): Promise<
	ServerlessPayloads[ServerlessRoutines.still]
> => {
	const stringifiedInputProps = serializeOrThrow(inputProps, 'input-props');

	const serializedInputProps = await compressInputProps({
		stringifiedInputProps,
		region,
		needsToUpload: getNeedsToUpload({
			type: 'still',
			sizes: [
				getSizeInBytes(stringifiedInputProps),
				getSizeInBytes(JSON.stringify(envVariables)),
			],
		}),
		userSpecifiedBucketName: forceBucketName ?? null,
		propsType: 'input-props',
		forcePathStyle,
		skipPutAcl: privacy === 'no-acl',
		requestHandler,
		logLevel,
	});

	return {
		composition,
		serveUrl,
		inputProps: serializedInputProps,
		imageFormat,
		envVariables,
		jpegQuality,
		maxRetries,
		frame,
		privacy,
		attempt: 1,
		logLevel,
		outName,
		timeoutInMilliseconds,
		chromiumOptions,
		scale,
		downloadBehavior,
		version: VERSION,
		forceHeight,
		forceWidth,
		forceFps,
		forceDurationInFrames,
		bucketName: forceBucketName,
		offthreadVideoCacheSizeInBytes,
		deleteAfter,
		type: ServerlessRoutines.still,
		streamed: getRendererFunctionTransport(region) === 'response-streaming',
		forcePathStyle,
		licenseKey: licenseKey ?? null,
		offthreadVideoThreads: offthreadVideoThreads ?? null,
		mediaCacheSizeInBytes: mediaCacheSizeInBytes ?? null,
		storageClass: storageClass ?? null,
		isProduction,
	};
};