Skip to content

🎥 Make videos programmatically with React

11.3 KB
Raw Blame
import {continueRender, delayRender} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {resolveFontSubsetKeys} from './resolve-font-subsets';

const loadedFontsByDocument = new WeakMap<
	Document,
	Record<string, Promise<void> | undefined>
>();

const getLoadedFontsForDocument = (targetDocument: Document) => {
	const cached = loadedFontsByDocument.get(targetDocument);
	if (cached) {
		return cached;
	}

	const loadedFonts: Record<string, Promise<void> | undefined> = {};
	loadedFontsByDocument.set(targetDocument, loadedFonts);
	return loadedFonts;
};

export type FontInfo = {
	fontFamily: string;
	importName: string;
	version: string;
	url: string;
	unicodeRanges: Record<string, string>;
	fonts: Record<string, Record<string, Record<string, string>>>;
	subsets: string[];
	variable?: {
		axes: Record<string, {min: number; max: number}>;
		fontFaces: {
			style: string;
			weight: string;
			stretch: string | null;
			subset: string;
			unicodeRange: string;
			src: string;
		}[];
		url: string;
	};
};

interface WithResolvers<T> {
	promise: Promise<T>;
	resolve: (value: T | PromiseLike<T>) => void;
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	reject: (reason?: any) => void;
}

export const withResolvers = function <T>() {
	let resolve: WithResolvers<T>['resolve'];
	let reject: WithResolvers<T>['reject'];
	const promise = new Promise<T>((res, rej) => {
		resolve = res;
		reject = rej;
	});
	return {promise, resolve: resolve!, reject: reject!};
};

const loadFontFaceOrTimeoutAfter20Seconds = (fontFace: FontFace) => {
	const timeout = withResolvers();

	const int = setTimeout(() => {
		timeout.reject(new Error('Timed out loading Google Font'));
	}, 18_000);

	return Promise.race([
		fontFace.load().then(() => {
			clearTimeout(int);
		}),
		timeout.promise,
	]);
};

type FontLoadOptions = {
	document?: Document;
	ignoreTooManyRequestsWarning?: boolean;
};

type V4Options = FontLoadOptions & {
	weights?: string[];
	subsets?: string[];
};

// weights and subsets are required in v5
type V5Options = FontLoadOptions & {
	weights: string[];
	subsets: string[];
};

/**
 * @description Load a Google Font for use in Remotion.
 * @param meta
 * @param {string} style The font style we want to load. While each font has a different set of styles, common options are: normal, italic etc.
 * @param {Array} options
 * @returns An object with the following properties: fontFamily, unicodeRanges, fonts
 * @see [Documentation](https://www.remotion.dev/docs/google-fonts/load-font)
 */
export const loadFonts = (
	meta: FontInfo,
	style?: string,
	options?: typeof NoReactInternals.ENABLE_V5_BREAKING_CHANGES extends true
		? V5Options
		: V4Options,
): {
	fontFamily: FontInfo['fontFamily'];
	fonts: FontInfo['fonts'];
	unicodeRanges: FontInfo['unicodeRanges'];
	waitUntilDone: () => Promise<undefined>;
} => {
	const weightsAndSubsetsAreSpecified =
		Array.isArray(options?.weights) &&
		Array.isArray(options?.subsets) &&
		options.weights.length > 0 &&
		options.subsets.length > 0;

	if (
		NoReactInternals.ENABLE_V5_BREAKING_CHANGES &&
		!weightsAndSubsetsAreSpecified
	) {
		throw new Error(
			'Loading Google Fonts without specifying weights and subsets is not supported in Remotion v5. Please specify the weights and subsets you need.',
		);
	}

	const promises: Promise<void>[] = [];
	const styles = style ? [style] : Object.keys(meta.fonts);

	let fontsLoaded = 0;
	let previousAdded: Promise<void> = Promise.resolve();

	for (const style of styles) {
		// Don't load fonts on server
		if (typeof FontFace === 'undefined') {
			continue;
		}

		if (!meta.fonts[style]) {
			throw new Error(
				`The font ${meta.fontFamily} does not have a style ${style}`,
			);
		}
		const targetDocument = options?.document ?? document;
		const loadedFonts = getLoadedFontsForDocument(targetDocument);
		const weights = options?.weights ?? Object.keys(meta.fonts[style]);
		for (const weight of weights) {
			if (!meta.fonts[style][weight]) {
				throw new Error(
					`The font ${meta.fontFamily} does not  have a weight ${weight} in style ${style}`,
				);
			}
			const requestedSubsets: string[] =
				options?.subsets ?? Object.keys(meta.fonts[style][weight]);
			const availableSubsetKeys = Object.keys(meta.fonts[style][weight]);
			const subsets = [
				...new Set(
					requestedSubsets.flatMap((requestedSubset) =>
						resolveFontSubsetKeys({
							availableSubsetKeys,
							metaSubsets: meta.subsets,
							requestedSubset,
						}),
					),
				),
			];
			for (const subset of subsets) {
				//  Get font url from meta
				let font = meta.fonts[style]?.[weight]?.[subset];

				//  Check is font available in meta
				if (!font) {
					throw new Error(
						`weight: ${weight} subset: ${subset} is not available for '${meta.fontFamily}'`,
					);
				}

				//  Check is font already loaded
				let fontKey = `${meta.fontFamily}-${style}-${weight}-${subset}`;
				const previousPromise = loadedFonts[fontKey];
				if (previousPromise) {
					promises.push(previousPromise);
					continue;
				}

				const baseLabel = `Fetching ${meta.fontFamily} font ${JSON.stringify({
					style,
					weight,
					subset,
				})}`;

				const label = weightsAndSubsetsAreSpecified
					? baseLabel
					: `${baseLabel}. This might be caused by loading too many font variations. Read more: https://www.remotion.dev/docs/troubleshooting/font-loading-errors#render-timeout-when-loading-google-fonts`;

				const handle = delayRender(label, {timeoutInMilliseconds: 60000});
				fontsLoaded++;

				const registerFont = (fontData: ArrayBuffer) => {
					NoReactInternals.registerFontFace({
						ascentOverride: null,
						descentOverride: null,
						display: null,
						featureSettings: null,
						fontFamily: meta.fontFamily,
						fontData,
						fontUrl: font,
						format: 'woff2',
						lineGapOverride: null,
						style,
						weight,
						stretch: null,
						unicodeRange: meta.unicodeRanges[subset] ?? null,
						variant: null,
					});
				};

				let attempts = 2;

				const tryToLoad = (): Promise<{
					fontFace: FontFace;
					fontData: ArrayBuffer;
				}> => {
					return NoReactInternals.fetchFontData(font)
						.then((fontData) => {
							const fontFace = new FontFace(meta.fontFamily, fontData, {
								weight,
								style,
								unicodeRange: meta.unicodeRanges[subset],
							});

							return loadFontFaceOrTimeoutAfter20Seconds(fontFace).then(() => ({
								fontFace,
								fontData,
							}));
						})
						.catch((err) => {
							if (attempts === 0) {
								loadedFonts[fontKey] = undefined;
								throw err;
							}

							attempts--;
							return tryToLoad();
						});
				};

				const promise = Promise.all([tryToLoad(), previousAdded]).then(
					([{fontFace, fontData}]) => {
						targetDocument.fonts.add(fontFace);
						registerFont(fontData);
						continueRender(handle);
					},
				);
				previousAdded = promise.catch(() => undefined);
				loadedFonts[fontKey] = promise;
				promises.push(promise);
			}
		}

		if (fontsLoaded > 20 && !options?.ignoreTooManyRequestsWarning) {
			console.warn(
				`Made ${fontsLoaded} network requests to load fonts for ${meta.fontFamily}. Consider loading fewer weights and subsets by passing options to loadFont(). Disable this warning by passing "ignoreTooManyRequestsWarning: true" to "options".`,
			);
		}
	}

	return {
		fontFamily: meta.fontFamily,
		fonts: meta.fonts,
		unicodeRanges: meta.unicodeRanges,
		waitUntilDone: () => Promise.all<void>(promises).then(() => undefined),
	};
};

export const loadVariableFonts = (
	meta: FontInfo,
	style: string,
	options: FontLoadOptions & {subsets: string[]},
): {
	fontFamily: FontInfo['fontFamily'];
	axes: Record<string, {min: number; max: number}>;
	waitUntilDone: () => Promise<undefined>;
} => {
	if (!meta.variable) {
		throw new Error(`${meta.fontFamily} is not available as a variable font`);
	}

	if (options.subsets.length === 0) {
		throw new Error('Pass at least one subset to loadVariableFont()');
	}

	const fontFacesForStyle = meta.variable.fontFaces.filter(
		(fontFace) => fontFace.style === style,
	);
	if (fontFacesForStyle.length === 0) {
		throw new Error(
			`The variable font ${meta.fontFamily} does not have a style ${style}`,
		);
	}

	const availableSubsetKeys = fontFacesForStyle.map(
		(fontFace) => fontFace.subset,
	);
	const subsets = [
		...new Set(
			options.subsets.flatMap((requestedSubset) =>
				resolveFontSubsetKeys({
					availableSubsetKeys,
					metaSubsets: meta.subsets,
					requestedSubset,
				}),
			),
		),
	];
	const promises: Promise<void>[] = [];
	let previousAdded: Promise<void> = Promise.resolve();

	for (const subset of subsets) {
		if (typeof FontFace === 'undefined') {
			continue;
		}

		const font = fontFacesForStyle.find(
			(fontFace) => fontFace.subset === subset,
		);
		if (!font) {
			throw new Error(
				`subset: ${subset} is not available for the variable font '${meta.fontFamily}'`,
			);
		}

		const fontKey = [
			meta.fontFamily,
			'variable',
			font.style,
			font.weight,
			font.stretch,
			font.subset,
			font.src,
		].join('-');
		const targetDocument = options.document ?? document;
		const loadedFonts = getLoadedFontsForDocument(targetDocument);
		const previousPromise = loadedFonts[fontKey];
		if (previousPromise) {
			promises.push(previousPromise);
			continue;
		}

		const handle = delayRender(
			`Fetching variable ${meta.fontFamily} font ${JSON.stringify({
				style,
				subset,
			})}`,
			{timeoutInMilliseconds: 60000},
		);
		const descriptors: FontFaceDescriptors = {
			style: font.style,
			weight: font.weight,
			unicodeRange: font.unicodeRange,
		};
		if (font.stretch) {
			descriptors.stretch = font.stretch;
		}

		const registerFont = (fontData: ArrayBuffer) => {
			NoReactInternals.registerFontFace({
				ascentOverride: null,
				descentOverride: null,
				display: null,
				featureSettings: null,
				fontFamily: meta.fontFamily,
				fontData,
				fontUrl: font.src,
				format: 'woff2',
				lineGapOverride: null,
				style: font.style,
				weight: font.weight,
				stretch: font.stretch,
				unicodeRange: font.unicodeRange,
				variant: null,
			});
		};
		let attempts = 2;

		const tryToLoad = (): Promise<{
			fontFace: FontFace;
			fontData: ArrayBuffer;
		}> => {
			return NoReactInternals.fetchFontData(font.src)
				.then((fontData) => {
					const fontFace = new FontFace(meta.fontFamily, fontData, descriptors);

					return loadFontFaceOrTimeoutAfter20Seconds(fontFace).then(() => ({
						fontFace,
						fontData,
					}));
				})
				.catch((err) => {
					if (attempts === 0) {
						loadedFonts[fontKey] = undefined;
						throw err;
					}

					attempts--;
					return tryToLoad();
				});
		};

		const promise = Promise.all([tryToLoad(), previousAdded]).then(
			([{fontFace, fontData}]) => {
				targetDocument.fonts.add(fontFace);
				registerFont(fontData);
				continueRender(handle);
			},
		);
		previousAdded = promise.catch(() => undefined);
		loadedFonts[fontKey] = promise;
		promises.push(promise);
	}

	if (subsets.length > 20 && !options.ignoreTooManyRequestsWarning) {
		console.warn(
			`Made ${subsets.length} network requests to load the variable font ${meta.fontFamily}. Consider loading fewer subsets. Disable this warning by passing "ignoreTooManyRequestsWarning: true" to "options".`,
		);
	}

	return {
		fontFamily: meta.fontFamily,
		axes: meta.variable.axes,
		waitUntilDone: () => Promise.all<void>(promises).then(() => undefined),
	};
};