Skip to content

🎥 Make videos programmatically with React

Improve SVG font embedding

Jonny Burgerf2442abe041e
diff --git a/packages/core/src/font-face-registry.ts b/packages/core/src/font-face-registry.ts
index 32da53cf11..d264622d4e 100644
--- a/packages/core/src/font-face-registry.ts
+++ b/packages/core/src/font-face-registry.ts
@@ -1,26 +1,65 @@
export type RegisteredFontFace = {
+ ascentOverride: string | null;
+ descentOverride: string | null;
+ display: 'auto' | 'block' | 'fallback' | 'optional' | 'swap' | null;
+ featureSettings: string | null;
fontFamily: string;
+ fontData: ArrayBuffer;
fontUrl: string;
format: 'woff2' | 'woff' | 'opentype' | 'truetype';
+ lineGapOverride: string | null;
style: string | null;
weight: string | null;
stretch: string | null;
unicodeRange: string | null;
+ variant: string | null;
};
const registeredFontFaces: RegisteredFontFace[] = [];
+const fontDataByUrl = new Map<string, Promise<ArrayBuffer>>();
+
+export const fetchFontData = (fontUrl: string): Promise<ArrayBuffer> => {
+ const cached = fontDataByUrl.get(fontUrl);
+ if (cached) {
+ return cached;
+ }
+
+ const promise = fetch(fontUrl)
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(
+ `Failed to load font ${JSON.stringify(fontUrl)}: ${response.status} ${response.statusText}`,
+ );
+ }
+
+ return response.arrayBuffer();
+ })
+ .catch((error) => {
+ fontDataByUrl.delete(fontUrl);
+ throw error;
+ });
+
+ fontDataByUrl.set(fontUrl, promise);
+ return promise;
+};
export const registerFontFace = (fontFace: RegisteredFontFace) => {
if (
registeredFontFaces.some(
(registered) =>
+ registered.ascentOverride === fontFace.ascentOverride &&
+ registered.descentOverride === fontFace.descentOverride &&
+ registered.display === fontFace.display &&
+ registered.featureSettings === fontFace.featureSettings &&
registered.fontFamily === fontFace.fontFamily &&
registered.fontUrl === fontFace.fontUrl &&
registered.format === fontFace.format &&
+ registered.lineGapOverride === fontFace.lineGapOverride &&
registered.style === fontFace.style &&
registered.weight === fontFace.weight &&
registered.stretch === fontFace.stretch &&
- registered.unicodeRange === fontFace.unicodeRange,
+ registered.unicodeRange === fontFace.unicodeRange &&
+ registered.variant === fontFace.variant,
)
) {
return;
diff --git a/packages/core/src/no-react.ts b/packages/core/src/no-react.ts
index 3aa3ce249d..a26d75870f 100644
--- a/packages/core/src/no-react.ts
+++ b/packages/core/src/no-react.ts
@@ -27,7 +27,11 @@ import {
DELAY_RENDER_RETRY_TOKEN,
} from './delay-render-constants';
import {findPropsToDelete} from './find-props-to-delete';
-import {getRegisteredFontFaces, registerFontFace} from './font-face-registry';
+import {
+ fetchFontData,
+ getRegisteredFontFaces,
+ registerFontFace,
+} from './font-face-registry';
import {
deserializeJSONWithSpecialTypes,
serializeJSONWithSpecialTypes,
@@ -81,4 +85,5 @@ export const NoReactInternals = {
serializeScaleValue,
getRegisteredFontFaces,
registerFontFace,
+ fetchFontData,
};
diff --git a/packages/core/src/test/font-face-registry.test.ts b/packages/core/src/test/font-face-registry.test.ts
new file mode 100644
index 0000000000..646c6b4b02
--- /dev/null
+++ b/packages/core/src/test/font-face-registry.test.ts
@@ -0,0 +1,24 @@
+import {afterEach, expect, mock, test} from 'bun:test';
+import {fetchFontData} from '../font-face-registry';
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+test('fetches font data once for concurrent consumers', async () => {
+ const fetchMock = mock(() =>
+ Promise.resolve(new Response(new Uint8Array([1, 2, 3, 4]))),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ const [first, second] = await Promise.all([
+ fetchFontData('https://example.com/font-cache-test.woff2'),
+ fetchFontData('https://example.com/font-cache-test.woff2'),
+ ]);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(first).toBe(second);
+ expect(Array.from(new Uint8Array(first))).toEqual([1, 2, 3, 4]);
+});
diff --git a/packages/docs/docs/client-side-rendering/limitations.mdx b/packages/docs/docs/client-side-rendering/limitations.mdx
index c280e68168..0a76c13024 100644
--- a/packages/docs/docs/client-side-rendering/limitations.mdx
+++ b/packages/docs/docs/client-side-rendering/limitations.mdx
@@ -74,6 +74,16 @@ The `text-decoration` property is <a style={{color: 'green'}}>supported</a> for
The `text-shadow` property is <a style={{color: 'green'}}>supported</a>.
The `-webkit-text-stroke`, `-webkit-text-stroke-color`, `-webkit-text-stroke-width`, `paint-order` properties are <a style={{color: 'green'}}>supported</a>.
+### Web fonts inside SVG
+
+Fonts loaded through [`@remotion/fonts`](/docs/fonts-api) or [`@remotion/google-fonts`](/docs/google-fonts) are embedded automatically when they are used by `<text>`, `<tspan>`, or `<textPath>` inside an `<svg>` from <AvailableFrom v="4.0.525" inline />.
+
+The font selection must be part of the SVG markup, for example through an inline `style`, a `font-family` attribute, or a `<style>` element inside the SVG. A CSS class whose rules are defined outside the SVG is not preserved when the SVG is converted into an image.
+
+Fonts loaded through CSS `@font-face`, a Google Fonts CSS import, or the browser's `FontFace` API are not embedded. Text inside `<foreignObject>` is not detected as SVG text and does not receive embedded fonts.
+
+In Safari, SVG text may intermittently use a fallback font because WebKit can report the SVG image as loaded before its embedded font is ready. Use Chrome or Firefox when reliable SVG web font rendering is required.
+
## Shadows
Basic `box-shadow` are <a style={{color: 'green'}}>supported</a>.
diff --git a/packages/docs/docs/fonts.mdx b/packages/docs/docs/fonts.mdx
index 7e3590d580..21c5917baf 100644
--- a/packages/docs/docs/fonts.mdx
+++ b/packages/docs/docs/fonts.mdx
@@ -81,6 +81,14 @@ const fontFamily = "Inter";
<div style={{ fontFamily: fontFamily }}>Some text</div>;
```
+## Web fonts in SVG with `@remotion/web-renderer`
+
+From <AvailableFrom v="4.0.525" inline />, [`@remotion/web-renderer`](/docs/web-renderer) automatically embeds fonts loaded through [`@remotion/fonts`](/docs/fonts-api) and [`@remotion/google-fonts`](/docs/google-fonts) when they are used by SVG `<text>`, `<tspan>`, or `<textPath>` elements.
+
+Set `fontFamily` through an inline style, a `font-family` attribute, or a `<style>` element inside the SVG. A CSS class whose rules are defined outside the SVG is not preserved when the SVG is converted into an image.
+
+Fonts loaded through CSS or the browser's `FontFace` API are not embedded into SVG images. Regular HTML text can still use those fonts. See [client-side rendering limitations](/docs/client-side-rendering/limitations#web-fonts-inside-svg) for browser-specific limitations.
+
## Local fonts (manually)
You may load fonts by using the web-native [`FontFace`](https://developer.mozilla.org/en-US/docs/Web/API/FontFace) API.
diff --git a/packages/fonts/src/load-font.ts b/packages/fonts/src/load-font.ts
index 44092e8f01..1bd7e7dec1 100644
--- a/packages/fonts/src/load-font.ts
+++ b/packages/fonts/src/load-font.ts
@@ -53,7 +53,8 @@ export const loadFont = async (options: LoadFontOptions): Promise<void> => {
);
try {
const fontFormat = format ?? getFontFormat(url);
- const font = new FontFace(family, `url('${url}') format('${fontFormat}')`, {
+ const fontData = await NoReactInternals.fetchFontData(url);
+ const font = new FontFace(family, fontData, {
ascentOverride,
descentOverride,
display,
@@ -70,13 +71,20 @@ export const loadFont = async (options: LoadFontOptions): Promise<void> => {
await font.load();
document.fonts.add(font);
NoReactInternals.registerFontFace({
+ ascentOverride: ascentOverride ?? null,
+ descentOverride: descentOverride ?? null,
+ display: display ?? null,
+ featureSettings: featureSettings ?? null,
fontFamily: family,
+ fontData,
fontUrl: url,
format: fontFormat,
+ lineGapOverride: lineGapOverride ?? null,
style: style ?? null,
weight: weight ?? null,
stretch: stretch ?? null,
unicodeRange: unicodeRange ?? null,
+ variant: variant ?? null,
});
continueRender(waitForFont);
} catch (err) {
diff --git a/packages/google-fonts/src/base.ts b/packages/google-fonts/src/base.ts
index 58f813977e..f6e365479e 100644
--- a/packages/google-fonts/src/base.ts
+++ b/packages/google-fonts/src/base.ts
@@ -178,62 +178,56 @@ export const loadFonts = (
const handle = delayRender(label, {timeoutInMilliseconds: 60000});
fontsLoaded++;
- // Create font-face
- const fontFace = new FontFace(
- meta.fontFamily,
- `url(${font}) format('woff2')`,
- {
- weight: weight,
- style: style,
- unicodeRange: meta.unicodeRanges[subset],
- },
- );
- const registerFont = () => {
+ 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 = () => {
- // Load font-face
- if (fontFace.status === 'loaded') {
- registerFont();
- continueRender(handle);
- return;
- }
-
- const promise = loadFontFaceOrTimeoutAfter20Seconds(fontFace)
- .then(() => {
- (options?.document ?? document).fonts.add(fontFace);
- registerFont();
- continueRender(handle);
+ const tryToLoad = (): Promise<void> => {
+ return NoReactInternals.fetchFontData(font)
+ .then((fontData) => {
+ const fontFace = new FontFace(meta.fontFamily, fontData, {
+ weight,
+ style,
+ unicodeRange: meta.unicodeRanges[subset],
+ });
+
+ return loadFontFaceOrTimeoutAfter20Seconds(fontFace).then(() => {
+ (options?.document ?? document).fonts.add(fontFace);
+ registerFont(fontData);
+ continueRender(handle);
+ });
})
.catch((err) => {
- // Mark font as not loaded
- loadedFonts[fontKey] = undefined;
if (attempts === 0) {
+ loadedFonts[fontKey] = undefined;
throw err;
- } else {
- attempts--;
- tryToLoad();
}
- });
-
- // Mark font as loaded
- loadedFonts[fontKey] = promise;
- promises.push(promise);
+ attempts--;
+ return tryToLoad();
+ });
};
- tryToLoad();
+ const promise = tryToLoad();
+ loadedFonts[fontKey] = promise;
+ promises.push(promise);
}
}
@@ -339,52 +333,51 @@ export const loadVariableFonts = (
descriptors.stretch = font.stretch;
}
- const fontFace = new FontFace(
- meta.fontFamily,
- `url(${font.src}) format('woff2')`,
- descriptors,
- );
- const registerFont = () => {
+ 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 = () => {
- if (fontFace.status === 'loaded') {
- registerFont();
- continueRender(handle);
- return;
- }
+ const tryToLoad = (): Promise<void> => {
+ return NoReactInternals.fetchFontData(font.src)
+ .then((fontData) => {
+ const fontFace = new FontFace(meta.fontFamily, fontData, descriptors);
- const promise = loadFontFaceOrTimeoutAfter20Seconds(fontFace)
- .then(() => {
- (options.document ?? document).fonts.add(fontFace);
- registerFont();
- continueRender(handle);
+ return loadFontFaceOrTimeoutAfter20Seconds(fontFace).then(() => {
+ (options.document ?? document).fonts.add(fontFace);
+ registerFont(fontData);
+ continueRender(handle);
+ });
})
.catch((err) => {
- loadedFonts[fontKey] = undefined;
if (attempts === 0) {
+ loadedFonts[fontKey] = undefined;
throw err;
}
attempts--;
- tryToLoad();
+ return tryToLoad();
});
-
- loadedFonts[fontKey] = promise;
- promises.push(promise);
};
- tryToLoad();
+ const promise = tryToLoad();
+ loadedFonts[fontKey] = promise;
+ promises.push(promise);
}
if (subsets.length > 20 && !options.ignoreTooManyRequestsWarning) {
diff --git a/packages/google-fonts/test/variable-font.test.ts b/packages/google-fonts/test/variable-font.test.ts
index 1e2f87e718..32a84a6565 100644
--- a/packages/google-fonts/test/variable-font.test.ts
+++ b/packages/google-fonts/test/variable-font.test.ts
@@ -9,6 +9,7 @@ mock.module('remotion', () => ({
mock.module('remotion/no-react', () => ({
NoReactInternals: {
ENABLE_V5_BREAKING_CHANGES: false,
+ fetchFontData: () => Promise.resolve(new ArrayBuffer(4)),
registerFontFace: (fontFace: unknown) => {
registeredFontFaces.push(fontFace);
},
@@ -27,7 +28,7 @@ test('loads variable font faces from a generated module and font info', async ()
constructor(
_fontFamily: string,
- _source: string,
+ _source: string | BufferSource,
fontDescriptors?: FontFaceDescriptors,
) {
if (fontDescriptors) {
diff --git a/packages/web-renderer/src/drawing/embed-registered-fonts-in-svg.ts b/packages/web-renderer/src/drawing/embed-registered-fonts-in-svg.ts
index f32eb32f6d..e43059c2f2 100644
--- a/packages/web-renderer/src/drawing/embed-registered-fonts-in-svg.ts
+++ b/packages/web-renderer/src/drawing/embed-registered-fonts-in-svg.ts
@@ -1,72 +1,169 @@
import {NoReactInternals} from 'remotion/no-react';
-const base64ByUrl = new Map<string, Promise<string>>();
+type RegisteredFontFace = ReturnType<
+ typeof NoReactInternals.getRegisteredFontFaces
+>[number];
-const getBase64 = (url: string): Promise<string> => {
- const cached = base64ByUrl.get(url);
+export type EmbeddedFontStyle = {
+ blob: Blob;
+ cacheKey: string;
+ css: string;
+};
+
+const base64ByData = new WeakMap<ArrayBuffer, string>();
+const ruleByFontFace = new WeakMap<RegisteredFontFace, string>();
+const styleByFontFaceSet = new Map<string, EmbeddedFontStyle>();
+const fontIndexesByFamily = new Map<string, number[]>();
+let indexedFontCount = 0;
+
+const getBase64 = (data: ArrayBuffer): string => {
+ const cached = base64ByData.get(data);
if (cached) {
return cached;
}
- const promise = fetch(url)
- .then((response) => {
- if (!response.ok) {
- throw new Error(
- `Failed to load font ${JSON.stringify(url)} for SVG: ${response.status} ${response.statusText}`,
- );
- }
+ const bytes = new Uint8Array(data);
+ let binary = '';
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ }
- return response.arrayBuffer();
- })
- .then((arrayBuffer) => {
- const bytes = new Uint8Array(arrayBuffer);
- let binary = '';
- for (let offset = 0; offset < bytes.length; offset += 0x8000) {
- binary += String.fromCharCode(
- ...bytes.subarray(offset, offset + 0x8000),
- );
- }
+ const base64 = btoa(binary);
+ base64ByData.set(data, base64);
+ return base64;
+};
- return btoa(binary);
- })
- .catch((error) => {
- base64ByUrl.delete(url);
- throw error;
- });
+const normalizeWeight = (value: string): number | null => {
+ if (value === 'normal') {
+ return 400;
+ }
+
+ if (value === 'bold') {
+ return 700;
+ }
+
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+};
+
+const stretchKeywords: Record<string, number> = {
+ 'ultra-condensed': 50,
+ 'extra-condensed': 62.5,
+ condensed: 75,
+ 'semi-condensed': 87.5,
+ normal: 100,
+ 'semi-expanded': 112.5,
+ expanded: 125,
+ 'extra-expanded': 150,
+ 'ultra-expanded': 200,
+};
+
+const normalizeStretch = (value: string): number | null => {
+ const keyword = stretchKeywords[value];
+ if (keyword !== undefined) {
+ return keyword;
+ }
+
+ if (!value.endsWith('%')) {
+ return null;
+ }
- base64ByUrl.set(url, promise);
- return promise;
+ const parsed = Number(value.slice(0, -1));
+ return Number.isFinite(parsed) ? parsed : null;
};
-export const embedRegisteredFontsInSvg = async ({
- svg,
- svgData,
+const valueMatchesRange = ({
+ actual,
+ descriptor,
+ normalize,
}: {
- svg: SVGSVGElement;
- svgData: string;
-}): Promise<string> => {
- const textElements = svg.querySelectorAll('text, tspan, textPath');
- if (textElements.length === 0) {
- return svgData;
+ actual: string;
+ descriptor: string;
+ normalize: (value: string) => number | null;
+}): boolean => {
+ const actualValue = normalize(actual);
+ const range = descriptor.trim().split(/\s+/).map(normalize);
+ if (actualValue === null || range.some((value) => value === null)) {
+ return actual.toLowerCase() === descriptor.toLowerCase();
}
- const usedFontFamilies = new Set<string>();
- for (const textElement of textElements) {
- for (const family of getComputedStyle(textElement).fontFamily.split(',')) {
- usedFontFamilies.add(
- family
- .trim()
- .replace(/^(['"])(.*)\1$/, '$2')
- .toLowerCase(),
- );
- }
+ if (range.length === 1) {
+ return actualValue === range[0];
}
- const fonts = NoReactInternals.getRegisteredFontFaces().filter((font) =>
- usedFontFamilies.has(font.fontFamily.toLowerCase()),
+ return (
+ range.length === 2 &&
+ actualValue >= Math.min(range[0]!, range[1]!) &&
+ actualValue <= Math.max(range[0]!, range[1]!)
);
- if (fonts.length === 0) {
- return svgData;
+};
+
+const descriptorsMatch = (
+ font: RegisteredFontFace,
+ computedStyle: CSSStyleDeclaration,
+): boolean => {
+ const fontStyle = font.style ?? 'normal';
+ if (
+ fontStyle.split(/\s+/)[0]?.toLowerCase() !==
+ computedStyle.fontStyle.split(/\s+/)[0]?.toLowerCase()
+ ) {
+ return false;
+ }
+
+ if (
+ !valueMatchesRange({
+ actual: computedStyle.fontWeight,
+ descriptor: font.weight ?? '400',
+ normalize: normalizeWeight,
+ })
+ ) {
+ return false;
+ }
+
+ return valueMatchesRange({
+ actual: computedStyle.fontStretch || 'normal',
+ descriptor: font.stretch ?? 'normal',
+ normalize: normalizeStretch,
+ });
+};
+
+const unicodeRangeSupportsText = (
+ unicodeRange: string | null,
+ text: string,
+): boolean => {
+ if (unicodeRange === null) {
+ return true;
+ }
+
+ const ranges = unicodeRange.split(',').map((range) => {
+ const match = /^U\+([0-9A-F?]+)(?:-([0-9A-F]+))?$/i.exec(range.trim());
+ if (!match) {
+ return null;
+ }
+
+ return {
+ from: Number.parseInt(match[1]!.replace(/\?/g, '0'), 16),
+ to: Number.parseInt((match[2] ?? match[1]!).replace(/\?/g, 'F'), 16),
+ };
+ });
+
+ if (ranges.some((range) => range === null)) {
+ return true;
+ }
+
+ return Array.from(text).some((character) => {
+ const codePoint = character.codePointAt(0)!;
+ return ranges.some(
+ (range) =>
+ range !== null && codePoint >= range.from && codePoint <= range.to,
+ );
+ });
+};
+
+const getFontFaceRule = (font: RegisteredFontFace): string => {
+ const cached = ruleByFontFace.get(font);
+ if (cached) {
+ return cached;
}
const mimeTypes = {
@@ -75,42 +172,114 @@ export const embedRegisteredFontsInSvg = async ({
woff: 'font/woff',
woff2: 'font/woff2',
} as const;
- const fontRules = await Promise.all(
- fonts.map(async (font) => {
- const declarations = [
- `font-family:${JSON.stringify(font.fontFamily)}`,
- `src:url(data:${mimeTypes[font.format]};base64,${await getBase64(font.fontUrl)}) format(${JSON.stringify(font.format)})`,
- ];
- if (font.style !== null) {
- declarations.push(`font-style:${font.style}`);
- }
+ const declarations = [
+ `font-family:${JSON.stringify(font.fontFamily)}`,
+ `src:url(data:${mimeTypes[font.format]};base64,${getBase64(font.fontData)}) format(${JSON.stringify(font.format)})`,
+ ];
+ const optionalDeclarations = [
+ ['ascent-override', font.ascentOverride],
+ ['descent-override', font.descentOverride],
+ ['font-display', font.display],
+ ['font-feature-settings', font.featureSettings],
+ ['line-gap-override', font.lineGapOverride],
+ ['font-stretch', font.stretch],
+ ['font-style', font.style],
+ ['font-weight', font.weight],
+ ['unicode-range', font.unicodeRange],
+ ['font-variant', font.variant],
+ ] as const;
- if (font.weight !== null) {
- declarations.push(`font-weight:${font.weight}`);
- }
+ for (const [property, value] of optionalDeclarations) {
+ if (value !== null) {
+ declarations.push(`${property}:${value}`);
+ }
+ }
+
+ const rule = `@font-face{${declarations.join(';')}}`;
+ ruleByFontFace.set(font, rule);
+ return rule;
+};
+
+export const getEmbeddedFontStyleForSvg = (
+ svg: SVGSVGElement,
+): EmbeddedFontStyle | null => {
+ const textElements = svg.querySelectorAll('text');
+ if (textElements.length === 0) {
+ return null;
+ }
- if (font.stretch !== null) {
- declarations.push(`font-stretch:${font.stretch}`);
+ const registeredFonts = NoReactInternals.getRegisteredFontFaces();
+ for (let index = indexedFontCount; index < registeredFonts.length; index++) {
+ const family = registeredFonts[index]!.fontFamily.toLowerCase();
+ const indexes = fontIndexesByFamily.get(family) ?? [];
+ indexes.push(index);
+ fontIndexesByFamily.set(family, indexes);
+ }
+
+ indexedFontCount = registeredFonts.length;
+
+ const usedFontIndexes = new Set<number>();
+ for (const textElement of textElements) {
+ const textNodeWalker = svg.ownerDocument.createTreeWalker(textElement, 4);
+ const computedStyleByElement = new WeakMap<Element, CSSStyleDeclaration>();
+ while (textNodeWalker.nextNode()) {
+ const text = textNodeWalker.currentNode.textContent ?? '';
+ if (text.length === 0) {
+ continue;
}
- if (font.unicodeRange !== null) {
- declarations.push(`unicode-range:${font.unicodeRange}`);
+ const parentElement =
+ textNodeWalker.currentNode.parentElement ?? textElement;
+ const computedStyle =
+ computedStyleByElement.get(parentElement) ??
+ (svg.ownerDocument.defaultView ?? window).getComputedStyle(
+ parentElement,
+ );
+ computedStyleByElement.set(parentElement, computedStyle);
+ for (const family of computedStyle.fontFamily.split(',')) {
+ const normalizedFamily = family
+ .trim()
+ .replace(/^(['"])(.*)\1$/, '$2')
+ .toLowerCase();
+ const familyIndexes = fontIndexesByFamily.get(normalizedFamily) ?? [];
+ const matchingIndexes = familyIndexes.filter((index) =>
+ descriptorsMatch(registeredFonts[index]!, computedStyle),
+ );
+ const candidateIndexes =
+ matchingIndexes.length === 0 ? familyIndexes : matchingIndexes;
+
+ for (const index of candidateIndexes) {
+ if (
+ unicodeRangeSupportsText(registeredFonts[index]!.unicodeRange, text)
+ ) {
+ usedFontIndexes.add(index);
+ }
+ }
}
+ }
+ }
- return `@font-face{${declarations.join(';')}}`;
- }),
- );
- const openingTagEnd = svgData.indexOf('>');
- if (openingTagEnd === -1) {
- return svgData;
+ if (usedFontIndexes.size === 0) {
+ return null;
}
- const css = fontRules.join('').replace(/]]>/g, ']]]]><![CDATA[>');
- const style = `<style type="text/css"><![CDATA[${css}]]></style>`;
+ const sortedIndexes = Array.from(usedFontIndexes).sort((a, b) => a - b);
+ const cacheKey = sortedIndexes.join(',');
+ const cached = styleByFontFaceSet.get(cacheKey);
+ if (cached) {
+ return cached;
+ }
- return (
- svgData.slice(0, openingTagEnd + 1) +
- style +
- svgData.slice(openingTagEnd + 1)
- );
+ const css = sortedIndexes
+ .map((index) => getFontFaceRule(registeredFonts[index]!))
+ .join('')
+ .replace(/]]>/g, ']]]]><![CDATA[>');
+ const style = `<style type="text/css"><![CDATA[${css}]]></style>`;
+ const embeddedStyle = {
+ blob: new Blob([style]),
+ cacheKey,
+ css,
+ };
+ styleByFontFaceSet.set(cacheKey, embeddedStyle);
+ return embeddedStyle;
};
diff --git a/packages/web-renderer/src/drawing/turn-svg-into-drawable.ts b/packages/web-renderer/src/drawing/turn-svg-into-drawable.ts
index 60c074bef0..99b0dad90c 100644
--- a/packages/web-renderer/src/drawing/turn-svg-into-drawable.ts
+++ b/packages/web-renderer/src/drawing/turn-svg-into-drawable.ts
@@ -1,6 +1,15 @@
-import {embedRegisteredFontsInSvg} from './embed-registered-fonts-in-svg';
+import {getEmbeddedFontStyleForSvg} from './embed-registered-fonts-in-svg';
-export const turnSvgIntoDrawable = async (svg: SVGSVGElement) => {
+const drawableBySvg = new WeakMap<
+ SVGSVGElement,
+ {
+ fontStyleKey: string | null;
+ serializedSvg: string;
+ drawable: Promise<HTMLImageElement>;
+ }
+>();
+
+export const turnSvgIntoDrawable = (svg: SVGSVGElement) => {
const {fill, color} = getComputedStyle(svg);
const originalTransform = svg.style.transform;
@@ -35,15 +44,29 @@ export const turnSvgIntoDrawable = async (svg: SVGSVGElement) => {
svg.style.transformOrigin = originalTransformOrigin;
svg.style.fill = originalFill;
svg.style.color = originalColor;
- const svgData = await embedRegisteredFontsInSvg({
- svg,
- svgData: serializedSvg,
- });
+ const embeddedFontStyle = getEmbeddedFontStyleForSvg(svg);
+ const fontStyleKey = embeddedFontStyle?.cacheKey ?? null;
+ const cached = drawableBySvg.get(svg);
+ if (
+ cached?.serializedSvg === serializedSvg &&
+ cached.fontStyleKey === fontStyleKey
+ ) {
+ return cached.drawable;
+ }
- return new Promise<HTMLImageElement>((resolve, reject) => {
+ const drawable = new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image();
+ const openingTagEnd = serializedSvg.indexOf('>');
+ const blobParts: BlobPart[] =
+ embeddedFontStyle === null || openingTagEnd === -1
+ ? [serializedSvg]
+ : [
+ serializedSvg.slice(0, openingTagEnd + 1),
+ embeddedFontStyle.blob,
+ serializedSvg.slice(openingTagEnd + 1),
+ ];
const url = URL.createObjectURL(
- new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'}),
+ new Blob(blobParts, {type: 'image/svg+xml;charset=utf-8'}),
);
image.onload = function () {
@@ -58,4 +81,11 @@ export const turnSvgIntoDrawable = async (svg: SVGSVGElement) => {
image.src = url;
});
+ drawableBySvg.set(svg, {fontStyleKey, serializedSvg, drawable});
+ drawable.catch(() => {
+ if (drawableBySvg.get(svg)?.drawable === drawable) {
+ drawableBySvg.delete(svg);
+ }
+ });
+ return drawable;
};
diff --git a/packages/web-renderer/src/test/svg-registered-font-selection.test.ts b/packages/web-renderer/src/test/svg-registered-font-selection.test.ts
new file mode 100644
index 0000000000..5976ce8a00
--- /dev/null
+++ b/packages/web-renderer/src/test/svg-registered-font-selection.test.ts
@@ -0,0 +1,99 @@
+import {NoReactInternals} from 'remotion/no-react';
+import {expect, test} from 'vitest';
+import {getEmbeddedFontStyleForSvg} from '../drawing/embed-registered-fonts-in-svg';
+import {turnSvgIntoDrawable} from '../drawing/turn-svg-into-drawable';
+
+test('embeds only the font faces needed by SVG text', () => {
+ const family = 'Registered SVG font selection test';
+ const register = ({
+ fontData,
+ unicodeRange,
+ weight,
+ }: {
+ fontData: ArrayBuffer;
+ unicodeRange: string;
+ weight: string;
+ }) => {
+ NoReactInternals.registerFontFace({
+ ascentOverride: '90%',
+ descentOverride: '20%',
+ display: 'swap',
+ featureSettings: '"liga" 0',
+ fontFamily: family,
+ fontData,
+ fontUrl: `https://example.com/${weight}-${unicodeRange}.woff2`,
+ format: 'woff2',
+ lineGapOverride: '10%',
+ stretch: null,
+ style: 'normal',
+ unicodeRange,
+ variant: 'small-caps',
+ weight,
+ });
+ };
+
+ register({
+ fontData: new Uint8Array([1]).buffer,
+ unicodeRange: 'U+0000-00FF',
+ weight: '400',
+ });
+ register({
+ fontData: new Uint8Array([2]).buffer,
+ unicodeRange: 'U+0400-04FF',
+ weight: '400',
+ });
+ register({
+ fontData: new Uint8Array([3]).buffer,
+ unicodeRange: 'U+0000-00FF',
+ weight: '700',
+ });
+
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ text.style.fontFamily = family;
+ text.style.fontStyle = 'normal';
+ text.style.fontWeight = '400';
+ text.textContent = 'Hello';
+ svg.appendChild(text);
+ document.body.appendChild(svg);
+
+ try {
+ const embedded = getEmbeddedFontStyleForSvg(svg);
+ expect(embedded).not.toBeNull();
+ expect(embedded!.css).toContain('base64,AQ==');
+ expect(embedded!.css).not.toContain('base64,Ag==');
+ expect(embedded!.css).not.toContain('base64,Aw==');
+ expect(embedded!.css).toContain('ascent-override:90%');
+ expect(embedded!.css).toContain('descent-override:20%');
+ expect(embedded!.css).toContain('font-display:swap');
+ expect(embedded!.css).toContain('font-feature-settings:"liga" 0');
+ expect(embedded!.css).toContain('line-gap-override:10%');
+ expect(embedded!.css).toContain('font-variant:small-caps');
+ } finally {
+ svg.remove();
+ }
+});
+
+test('reuses the drawable while an SVG is unchanged', async () => {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('width', '10');
+ svg.setAttribute('height', '10');
+ const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ rect.setAttribute('width', '10');
+ rect.setAttribute('height', '10');
+ rect.setAttribute('fill', 'red');
+ svg.appendChild(rect);
+ document.body.appendChild(svg);
+
+ try {
+ const first = await turnSvgIntoDrawable(svg);
+ const second = await turnSvgIntoDrawable(svg);
+ expect(second).toBe(first);
+
+ rect.setAttribute('fill', 'blue');
+ const changed = await turnSvgIntoDrawable(svg);
+ expect(changed).not.toBe(first);
+ } finally {
+ svg.remove();
+ }
+});