Skip to content

Commit 906da87

Browse files
committed
charge the glyphs renderText rasterizes to its work budget, bound a variable font's instances
1 parent 74672a9 commit 906da87

6 files changed

Lines changed: 71 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation
137137
### Fixes
138138

139139
- `renderSVG()` bounds the points paths are made of: an arc between far-apart ends is drawn with at most 64 curves a turn (a 139-byte path, `M 1e25 100 A 40 30 20 1 1 160 100`, stroked, ran the process out of memory), and the curves of arcs and the points of all paths, also of each copy drawn through `<use>`, count against 2^25 points plus 4 per pixel of the output in one render and 2^21 in one path. Reading path data and placing text along a `<textPath>` count, too, and SVGs embedded as images share the budget of the render they are in. More throw a `LimitError` (which a text's layout no longer takes for a damaged font). A path drawn through `<use>` is read once a render instead of once a copy.
140-
- SVG text: the glyph outlines of all texts count against the render's points before they are made, 16 points a command (20 texts of 1,000 characters of a complex font ran the process out of memory), so very long texts need a larger output; many `<tspan>`s in one `<text>` take linear time (10,000 took 20 s); a `<textPath>` on a long path renders at a normal size; bitmap emoji (CBDT, sbix) are decoded once a render instead of once a draw (copies through `<use>` took minutes), at most 2048x2048 pixels each (larger ones aren't drawn, also in `renderText()`: one that said 16383x16383 ran the process out of memory), and counted before they are decoded, also damaged ones. `renderText()` counts the work of decoding and scaling its bitmap glyphs against 2^28 pixels plus 64 per pixel of the image (more throw a `LimitError`), keeps at most 2^22 pixels of scaled glyphs in a render and none after it (they were kept with the font: 1 GB a size), keeps rasters of outline and color glyphs with the font only up to 256 KB each, 16 MB a font and 8 text colors a glyph (62 letters at size 6000 kept 774 MB, a new color each render grew without end), and doesn't draw a glyph scaled to more than 4 times the image (a strike at ppem 1 made a 32768x32768 copy for a 10x10 image).
140+
- SVG text: the glyph outlines of all texts count against the render's points before they are made, 16 points a command (20 texts of 1,000 characters of a complex font ran the process out of memory), so very long texts need a larger output; many `<tspan>`s in one `<text>` take linear time (10,000 took 20 s); a `<textPath>` on a long path renders at a normal size; bitmap emoji (CBDT, sbix) are decoded once a render instead of once a draw (copies through `<use>` took minutes), at most 2048x2048 pixels each (larger ones aren't drawn, also in `renderText()`: one that said 16383x16383 ran the process out of memory), and counted before they are decoded, also damaged ones. `renderText()` counts the work of decoding and scaling its bitmap glyphs against 2^28 pixels plus 64 per pixel of the image (more throw a `LimitError`), keeps at most 2^22 pixels of scaled glyphs in a render and none after it (they were kept with the font: 1 GB a size), keeps rasters of outline and color glyphs with the font only up to 256 KB each, 16 MB a font and 8 text colors a glyph (62 letters at size 6000 kept 774 MB, a new color each render grew without end), counts the glyphs it rasterizes against the same work budget as bitmap glyphs (2000 huge glyphs without advance took 260 s), frees a size's rasters when its sizes are evicted, and keeps at most 16 instances of a variable font (a new weight each render ran out of memory after 8000), and doesn't draw a glyph scaled to more than 4 times the image (a strike at ppem 1 made a 32768x32768 copy for a 10x10 image).
141141
- `renderText()` takes linear time for many combining marks and lines (400,000 lines took minutes).
142142
- Very long text (50,000 characters in SVG, 200,000 combining marks or lines in `renderText()`) no longer overflows the call stack or says the font is damaged.
143143
- Binary data and dates of other realms (iframes, `node:vm`, Jest) are accepted; objects that only claim to be one by `Symbol.toStringTag` aren't, and a detached buffer throws a `TypeError` that says so.

‎src/render/font.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,11 @@ export class Font {
171171
const cached = base.instances?.get(key);
172172
if (cached) return cached;
173173
const instance = Object.create(base) as Font;
174-
(base.instances ??= new Map()).set(key, instance);
174+
// (at most 16 instances a font, the oldest dropped: a new weight each render kept one for each, with its sizes,
175+
// until the process ran out of memory)
176+
const instances = base.instances ??= new Map();
177+
if (instances.size >= 16) instances.delete(instances.keys().next().value as string);
178+
instances.set(key, instance);
175179
instance.coords = coords;
176180
instance.outlineCache = new Map();
177181
// (the metrics MVAR varies)

‎src/render/text.ts‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,11 @@ function sizedFont(data: Uint8Array, size: number, hinting: boolean, variations:
155155
let shared = colorTables.get(font);
156156
if (!shared) colorTables.set(font, shared = { layers: parseColorLayers(font), paints: parsePaintGlyphs(font) });
157157

158-
if (bySize.size >= SIZES) bySize.clear();
158+
// (the sizes evicted take their rasters with them: the font's kept bytes start again)
159+
if (bySize.size >= SIZES) {
160+
bySize.clear();
161+
keptBytes.delete(font);
162+
}
159163
bySize.set(key, sized = { font, scale: size / font.unitsPerEm, hinter, layers: shared.layers, bitmaps: parseBitmaps(font, size), paints: shared.paints, shaping: shapeFont(font), glyphs: new Map() });
160164
return sized;
161165
}
@@ -315,6 +319,7 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
315319
bitmap = local.get(g)?.get(key) as ColorBitmap | null | undefined;
316320
if (bitmap === undefined) {
317321
const made = 'layers' in g.color ? layeredGlyph(g, g.color.layers, subpixel / SUBPIXELS, foreground) : paintedGlyph(g, subpixel / SUBPIXELS, foreground);
322+
spend(budget, made ? made.width * made.height : 0);
318323
// (at most 8 colors a glyph with the font: one for each text color grew without end)
319324
bitmap = g.colors.size < 8 ? keep(g, key, made, () => g.colors.set(key, made)) : keep(g, key, made, () => {});
320325
}
@@ -327,6 +332,8 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
327332
if (bitmap === undefined) bitmap = local.get(g)?.get(`${subpixel}`) as GlyphBitmap | null | undefined;
328333
if (bitmap === undefined) {
329334
const made = rasterizeGlyph(g.path, g.scale, subpixel / SUBPIXELS);
335+
// (a glyph that isn't kept is rasterized again for each occurrence: 2000 huge ones took 260 s)
336+
spend(budget, made ? made.width * made.height : 0);
330337
bitmap = keep(g, `${subpixel}`, made, () => g.bitmaps[subpixel] = made);
331338
}
332339
if (bitmap) blit(coverage, width, height, bitmap, pixel + bitmap.left, y - bitmap.top);
@@ -549,15 +556,18 @@ function layOutParagraph(p: Paragraph, layout: Layout, font: (i: number) => Size
549556
});
550557
}
551558

559+
/** spends pixels of a render's work budget (decoding, scaling and rasterizing glyphs), a LimitError when it's spent */
560+
function spend(budget: { left: number }, pixels: number): void {
561+
if ((budget.left -= pixels) < 0)
562+
throw new LimitError('Text too complex: its glyphs take more work to decode, scale and rasterize than an image of this size allows (2^28 pixels and 64 per pixel of the image)');
563+
}
564+
552565
// a bitmap glyph's PNG decoded and scaled from its strike to the font size, premultiplied
553566
async function scaledBitmap(glyph: BitmapGlyph, scale: number, budget: { left: number, image: number }): Promise<ColorBitmap | null> {
554-
const spend = (pixels: number): void => {
555-
if ((budget.left -= pixels) < 0) throw new LimitError('Text too complex: its bitmap glyphs take more pixels to decode and scale than an image of this size allows (2^28 and 64 per pixel)');
556-
};
557567
// (decoding takes about the time of 4 pixels a pixel, counted before it, as damaged ones take it too)
558568
const declared = bitmapPixels(glyph.png);
559569
if (!(declared <= MAX_BITMAP_GLYPH_PIXELS)) return null;
560-
spend(4 * Math.max(declared, 1));
570+
spend(budget, 4 * Math.max(declared, 1));
561571
let decoded;
562572
try {
563573
decoded = await decodePNG(glyph.png, MAX_BITMAP_GLYPH_PIXELS);
@@ -568,7 +578,7 @@ async function scaledBitmap(glyph: BitmapGlyph, scale: number, budget: { left: n
568578
// (scaled from its strike to the size: from a strike at ppem 1, a 2048x2048 bitmap became 32768x32768 at size 16. A
569579
// glyph larger than 4 times the image, and than the largest bitmap glyph, isn't drawn)
570580
if (width * height > Math.max(MAX_BITMAP_GLYPH_PIXELS, 4 * budget.image)) return null;
571-
spend(width * height);
581+
spend(budget, width * height);
572582
const data = new Uint8ClampedArray(width * height * 4);
573583
resample(new Uint8ClampedArray(decoded.pixels.buffer, decoded.pixels.byteOffset, decoded.pixels.length), decoded.width, decoded.height, width, height, TRIANGLE, data, true);
574584
premultiply(data);

‎tests/bitmap-glyph-limits.js‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,23 @@ const {Image, LimitError} = require('..');
33

44
// bitmap glyphs (sbix, CBDT) are bounded like the rest of a render: their PNGs count before they are decoded (also those
55
// that turn out damaged), and a glyph scaled from a tiny strike to the font size isn't allocated past the output
6+
// (Bun's JavaScriptCore rasterizes several times slower than V8)
7+
const slack = process.versions.bun ? 4 : 1;
8+
9+
// a collection before a memory check, so that the rasters a render made aren't counted as kept (Node and Bun; where
10+
// no collector can be had, the memory checks are skipped)
11+
const collect = (() => {
12+
try {
13+
if (globalThis.Bun) return () => globalThis.Bun.gc(true);
14+
if (globalThis.gc) return () => globalThis.gc();
15+
require('v8').setFlagsFromString('--expose_gc');
16+
const gc = require('vm').runInNewContext('gc');
17+
return () => gc();
18+
} catch {
19+
return null;
20+
}
21+
})();
22+
623
const panic = message => {
724
console.error(message);
825
process.exit(1);
@@ -38,13 +55,27 @@ const NS = 'xmlns="http://www.w3.org/2000/svg"';
3855
const data = fs.readFileSync(`${__dirname}/fonts/noto colrv1 subset.ttf`);
3956
for (let i = 0; i < 200; i++) await Image.renderText('\u{1F600}', {font: data, size: 500, width: 10, height: 10, maxPixels: 100, color: ((i * 0x01020300 + 0x10000000) | 0xff) >>> 0});
4057
}],
58+
// glyphs too large to keep, over each other (no advance) 1000 times at size 8000: drawn again each time, 260 s
59+
['2000 huge glyphs without advance', () => Image.renderText(text(2).repeat(1000), {font: font('zero'), size: 8000, width: 10, height: 10, maxPixels: 100})],
60+
// every weight of a variable font was an instance of its own, kept with the font for good (with its sizes and
61+
// glyphs): a new weight each render ran out of memory after 8000
62+
['a variable font at 400 weights', async () => {
63+
const data = fs.readFileSync(`${__dirname}/fonts/resvg/RobotoFlex.subset.ttf`);
64+
collect?.();
65+
const heap = process.memoryUsage().heapUsed;
66+
for (let i = 0; i < 400; i++) await Image.renderText('ABCDEFGHIJKLMNOPQRSTUVWXYZ', {font: data, size: 64, variations: {wght: 100 + i * 2}});
67+
collect?.();
68+
if (collect && process.memoryUsage().heapUsed - heap > 128 * 2 ** 20) panic(`a variable font at 400 weights: kept ${(process.memoryUsage().heapUsed - heap) >> 20} MB of heap`);
69+
}],
4170
]) {
42-
globalThis.gc?.();
71+
collect?.();
4372
const begin = Date.now(), before = process.memoryUsage().arrayBuffers;
4473
const result = await run().then(() => 'ok', err => err);
4574
if (result !== 'ok' && !(result instanceof LimitError)) panic(`${name}: ${result}`);
46-
if (Date.now() - begin > 20000) panic(`${name}: took ${Date.now() - begin} ms`);
75+
if (Date.now() - begin > 20000 * slack) panic(`${name}: took ${Date.now() - begin} ms`);
4776
globalThis.gc?.();
48-
if (process.memoryUsage().arrayBuffers - before > 128 * 2 ** 20) panic(`${name}: kept ${(process.memoryUsage().arrayBuffers - before) >> 20} MB`);
77+
collect?.();
78+
// (the rasters of a render that weren't kept are freed later, not on the collection: that case's check is its time)
79+
if (collect && !name.startsWith('2000 huge') && process.memoryUsage().arrayBuffers - before > 128 * 2 ** 20) panic(`${name}: kept ${(process.memoryUsage().arrayBuffers - before) >> 20} MB`);
4980
}
5081
})();
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# python -I mkzero.py out.ttf N : TrueType font, N glyphs (U+E000..) each a full-em square, advance 0 (no third-party data)
2+
import sys
3+
from fontTools.fontBuilder import FontBuilder
4+
from fontTools.pens.ttGlyphPen import TTGlyphPen
5+
out, n = sys.argv[1], int(sys.argv[2])
6+
names = ['.notdef'] + [f'g{i}' for i in range(n)]
7+
fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names)
8+
fb.setupCharacterMap({0xE000 + i: f'g{i}' for i in range(n)})
9+
def sq(i):
10+
p = TTGlyphPen(None); d = i % 7
11+
p.moveTo((d, 0)); p.lineTo((d, 1000)); p.lineTo((1000, 1000)); p.lineTo((1000, d)); p.closePath(); return p.glyph()
12+
glyf = {'.notdef': TTGlyphPen(None).glyph()}; glyf.update({f'g{i}': sq(i) for i in range(n)})
13+
fb.setupGlyf(glyf); fb.setupHorizontalMetrics({k: (0, 0) for k in names})
14+
fb.setupHorizontalHeader(ascent=1000, descent=0)
15+
fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost(); fb.save(out)

‎tests/fonts/bitmap-limits/zero.ttf‎

7.62 KB
Binary file not shown.

0 commit comments

Comments
 (0)