Skip to content

Commit fce3f77

Browse files
committed
keep renderText's scaled bitmap glyphs for one render, at most 2^22 pixels
1 parent 79aefee commit fce3f77

9 files changed

Lines changed: 143 additions & 6 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 its bitmap glyphs' decoding and scaling against 2^28 pixels plus 64 per pixel of the image (a `LimitError`), 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), 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/color.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ export interface ColorLayer {
88
color: number | null;
99
}
1010

11-
/** a glyph's PNG and where it goes, in pixels of its strike */
1211
/** the most pixels a bitmap glyph may have: emoji fonts have strikes of 160 at most, one that said 16383x16383 took 1 GB */
1312
export const MAX_BITMAP_GLYPH_PIXELS = 2048 * 2048;
1413

@@ -22,6 +21,7 @@ export function bitmapPixels(png: Uint8Array): number {
2221
return view.getUint32(16) * view.getUint32(20);
2322
}
2423

24+
/** a glyph's PNG and where it goes, in pixels of its strike */
2525
export interface BitmapGlyph {
2626
png: Uint8Array;
2727
/** pixels per em of the strike */

‎src/render/text.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,10 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
262262
// the pixels bitmap glyphs may be decoded and scaled to: 2^28 and 64 per pixel of the image, like the paint of an
263263
// SVG (1000 glyphs of 2048x2048 without advance took 39 s for a 32x1 image)
264264
const budget = { left: 2 ** 28 + 64 * width * height, image: width * height };
265+
// the bitmap glyphs scaled in this render, by glyph, at most 2^22 pixels of them (16 MB): kept with the font, those of
266+
// 64 glyphs from a strike at ppem 1 took 1 GB a size, and were never given back
267+
const scaled = new Map<Glyph, ColorBitmap | null>();
268+
let scaledPixels = 0;
265269

266270
for (const [n, line] of visible.entries()) {
267271
const align = layout.horizontalAlign ?? (line.rtl ? 'right' : 'left');
@@ -283,10 +287,18 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
283287
if ('bitmap' in g.color) subpixel = 0;
284288
const key = 'bitmap' in g.color ? '0' : `${subpixel}:${foreground}`;
285289
let bitmap = g.colors.get(key);
286-
if (bitmap === undefined) g.colors.set(key, bitmap = 'bitmap' in g.color
287-
? await scaledBitmap(g.color.bitmap, size / g.color.bitmap.ppem, budget)
288-
: 'layers' in g.color ? layeredGlyph(g, g.color.layers, subpixel / SUBPIXELS, foreground)
289-
: paintedGlyph(g, subpixel / SUBPIXELS, foreground));
290+
if ('bitmap' in g.color) {
291+
bitmap = scaled.get(g);
292+
if (bitmap === undefined) {
293+
bitmap = await scaledBitmap(g.color.bitmap, size / g.color.bitmap.ppem, budget);
294+
const pixels = bitmap ? bitmap.width * bitmap.height : 0;
295+
if (scaledPixels + pixels <= 2 ** 22) {
296+
scaledPixels += pixels;
297+
scaled.set(g, bitmap);
298+
}
299+
}
300+
} else if (bitmap === undefined) g.colors.set(key, bitmap = 'layers' in g.color ? layeredGlyph(g, g.color.layers, subpixel / SUBPIXELS, foreground)
301+
: paintedGlyph(g, subpixel / SUBPIXELS, foreground));
290302
if (bitmap) blitColor(color ??= new Uint8ClampedArray(width * height * 4), width, height, bitmap, pixel + bitmap.left, y - bitmap.top);
291303
continue;
292304
}

‎tests/bitmap-glyph-limits.js‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ const NS = 'xmlns="http://www.w3.org/2000/svg"';
1919
['1000 large glyphs without advance', () => Image.renderText(text(1000), {font: font('z-ok-1000'), size: 1, maxPixels: 100})],
2020
// 1000 records of one damaged PNG with different ends: each was decoded, and never counted, as it failed
2121
['1000 damaged glyphs in an SVG', () => Image.renderSVG(`<svg ${NS} width="10" height="10"><style>@font-face{font-family:f;src:url(data:font/ttf;base64,${font('sh-bad-1000').toString('base64')})}</style><text y="8" font-family="f" font-size="1">${text(2000)}</text></svg>`, {maxPixels: 100})],
22+
// 64 glyphs from a strike at ppem 1 in a 10x10 box, at 3 sizes of one font: the scaled glyphs were kept with the
23+
// font (1 GB a size, never given back)
24+
['64 scaled glyphs at 3 sizes', async () => {
25+
const data = font('a0-p1-64');
26+
for (const size of [16, 17, 18]) await Image.renderText(text(64), {font: data, size, width: 10, height: 10, maxPixels: 100}).catch(err => {
27+
if (!(err instanceof LimitError)) throw err;
28+
});
29+
}],
2230
]) {
2331
const begin = Date.now(), before = process.memoryUsage().rss;
2432
const result = await run().then(() => 'ok', err => err);
11.8 KB
Binary file not shown.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# python mksbix.py out.ttf N SIZE MODE: sbix font, U+E000+i -> distinct SIZExSIZE RGBA PNG; MODE ok|badfilter (last row filter 5)|trunc
2+
import sys, struct, zlib
3+
from fontTools.fontBuilder import FontBuilder
4+
from fontTools.pens.ttGlyphPen import TTGlyphPen
5+
from fontTools.ttLib import newTable
6+
from fontTools.ttLib.tables.sbixStrike import Strike
7+
from fontTools.ttLib.tables.sbixGlyph import Glyph as SbixGlyph
8+
out, n, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
9+
def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d))
10+
def png(i):
11+
c = zlib.compressobj(9); parts = []
12+
row = b'\0' + bytes([i & 255, i >> 8 & 255, 0, 255]) * size
13+
for y in range(size):
14+
r = row if not (mode == 'badfilter' and y == size - 1) else b'\5' + row[1:]
15+
if mode == 'trunc' and y == size - 1: break
16+
parts.append(c.compress(r))
17+
parts.append(c.flush())
18+
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
19+
names = ['.notdef'] + [f'g{i}' for i in range(n)]
20+
fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names)
21+
fb.setupCharacterMap({0xE000 + i: f'g{i}' for i in range(n)})
22+
fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names})
23+
fb.setupHorizontalMetrics({k: (1000, 0) for k in names})
24+
fb.setupHorizontalHeader(ascent=900, descent=-100)
25+
fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost()
26+
st = Strike(ppem=64, resolution=72)
27+
for i in range(n): st.glyphs[f'g{i}'] = SbixGlyph(glyphName=f'g{i}', graphicType='png ', originOffsetX=0, originOffsetY=0, imageData=png(i))
28+
sb = newTable('sbix'); sb.version = 1; sb.flags = 1; sb.strikes = {64: st}; fb.font['sbix'] = sb
29+
fb.save(out)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# python mksbix3.py out.ttf N SIZE MODE PPEM ADV: sbix font, U+E000+i -> distinct SIZExSIZE PNGs in one strike at PPEM, advance ADV units (of 1000)
2+
import sys, struct, zlib
3+
from fontTools.fontBuilder import FontBuilder
4+
from fontTools.pens.ttGlyphPen import TTGlyphPen
5+
from fontTools.ttLib import newTable
6+
from fontTools.ttLib.tables.sbixStrike import Strike
7+
from fontTools.ttLib.tables.sbixGlyph import Glyph as SbixGlyph
8+
out, n, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]; PPEM = int(sys.argv[5]) if len(sys.argv) > 5 else 64
9+
def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d))
10+
def png(i):
11+
c = zlib.compressobj(9); parts = []
12+
row = b'\0' + bytes([i & 255, i >> 8 & 255, 0, 255]) * size
13+
for y in range(size):
14+
r = row if not (mode == 'badfilter' and y == size - 1) else b'\5' + row[1:]
15+
if mode == 'trunc' and y == size - 1: break
16+
parts.append(c.compress(r))
17+
parts.append(c.flush())
18+
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
19+
ADV = int(sys.argv[6]) if len(sys.argv) > 6 else 1000
20+
names = ['.notdef'] + [f'g{i}' for i in range(n)]
21+
fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names)
22+
fb.setupCharacterMap({0xE000 + i: f'g{i}' for i in range(n)})
23+
fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names})
24+
fb.setupHorizontalMetrics({k: (ADV, 0) for k in names})
25+
fb.setupHorizontalHeader(ascent=900, descent=-100)
26+
fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost()
27+
st = Strike(ppem=PPEM, resolution=72)
28+
for i in range(n): st.glyphs[f'g{i}'] = SbixGlyph(glyphName=f'g{i}', graphicType='png ', originOffsetX=0, originOffsetY=0, imageData=png(i))
29+
sb = newTable('sbix'); sb.version = 1; sb.flags = 1; sb.strikes = {64: st}; fb.font['sbix'] = sb
30+
fb.save(out)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# python mkshared.py out.ttf M SIZE MODE: sbix font with 2M+1 glyphs; glyph 2k (U+E000+k) = the SAME PNG bytes at one
2+
# start offset, with end = start+len+k (distinct (offset,length) cache keys); odd glyphs are fillers (end<start -> null)
3+
import sys, struct, zlib
4+
from fontTools.fontBuilder import FontBuilder
5+
from fontTools.pens.ttGlyphPen import TTGlyphPen
6+
from fontTools.ttLib.tables.DefaultTable import DefaultTable
7+
out, M, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
8+
def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d))
9+
c = zlib.compressobj(9); row = b'\0' + b'\xff\x00\x00\xff' * size; parts = []
10+
for y in range(size): parts.append(c.compress(b'\5' + row[1:] if mode == 'badfilter' and y == size - 1 else row))
11+
parts.append(c.flush())
12+
png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
13+
n = 2 * M + 2 # .notdef + 2M+1 glyphs
14+
names = ['.notdef'] + [f'g{i}' for i in range(n - 1)]
15+
fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names)
16+
fb.setupCharacterMap({0xE000 + k: f'g{2 * k}' for k in range(M)})
17+
fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names})
18+
fb.setupHorizontalMetrics({k: (1000, 0) for k in names})
19+
fb.setupHorizontalHeader(ascent=900, descent=-100)
20+
fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost()
21+
hdr = 4 + 4 * (n + 1); S = hdr; L = 8 + len(png)
22+
offs = []
23+
for gid in range(n + 1):
24+
if gid == 0: offs.append(S + L + M + 10) # .notdef: start beyond, end S -> null
25+
elif (gid - 1) % 2 == 0: offs.append(S) # glyph g{2k}: start S
26+
else: offs.append(S + L + (gid - 2) // 2) # end of g{2k} = S+L+k
27+
strike = struct.pack('>HH', 64, 72) + b''.join(struct.pack('>I', o) for o in offs) + struct.pack('>hh4s', 0, 0, b'png ') + png + b'\0' * (M + 16)
28+
t = DefaultTable('sbix'); t.data = struct.pack('>HHII', 1, 1, 1, 12) + strike
29+
fb.font['sbix'] = t; fb.save(out); print('png', len(png), 'font', len(open(out, 'rb').read()))
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# python mkshared.py out.ttf M SIZE MODE: sbix font with 2M+1 glyphs; glyph 2k (U+E000+k) = the SAME PNG bytes at one
2+
# start offset, with end = start+len+k (distinct (offset,length) cache keys); odd glyphs are fillers (end<start -> null)
3+
import sys, struct, zlib
4+
from fontTools.fontBuilder import FontBuilder
5+
from fontTools.pens.ttGlyphPen import TTGlyphPen
6+
from fontTools.ttLib.tables.DefaultTable import DefaultTable
7+
out, M, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]
8+
def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d))
9+
c = zlib.compressobj(9); row = b'\0' + b'\xff\x00\x00\xff' * size; parts = []
10+
for y in range(size): parts.append(c.compress(b'\5' + row[1:] if mode == 'badfilter' and y == size - 1 else row))
11+
parts.append(c.flush())
12+
png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
13+
n = 2 * M + 2 # .notdef + 2M+1 glyphs
14+
names = ['.notdef'] + [f'g{i}' for i in range(n - 1)]
15+
fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names)
16+
fb.setupCharacterMap({0xE000 + k: f'g{2 * k}' for k in range(M)})
17+
fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names})
18+
fb.setupHorizontalMetrics({k: (0, 0) for k in names})
19+
fb.setupHorizontalHeader(ascent=900, descent=-100)
20+
fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost()
21+
hdr = 4 + 4 * (n + 1); S = hdr; L = 8 + len(png)
22+
offs = []
23+
for gid in range(n + 1):
24+
if gid == 0: offs.append(S + L + M + 10) # .notdef: start beyond, end S -> null
25+
elif (gid - 1) % 2 == 0: offs.append(S) # glyph g{2k}: start S
26+
else: offs.append(S + L + (gid - 2) // 2) # end of g{2k} = S+L+k
27+
strike = struct.pack('>HH', 64, 72) + b''.join(struct.pack('>I', o) for o in offs) + struct.pack('>hh4s', 0, 0, b'png ') + png + b'\0' * (M + 16)
28+
t = DefaultTable('sbix'); t.data = struct.pack('>HHII', 1, 1, 1, 12) + strike
29+
fb.font['sbix'] = t; fb.save(out); print('png', len(png), 'font', len(open(out, 'rb').read()))

0 commit comments

Comments
 (0)