ws-arch2: font/type1 (PFB / PFA, eexec, Subrs / CharStrings, Type 1 charstrings with flex / hint replacement / seac, AGL code points, rasterize; read) vs fontTools and FreeType; codecs/font/GlyphNames
This commit is contained in:
1 parent
0ee0859298
commit
53b41c7275
5 files changed
+231
-9
No files matched your search
+1
-1
@@ -59,7 +59,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.luau` |
|
||||
| font | psf | .psf .psfu | yes | yes | bitmap: true, variants: "psf1", "psf2" | `tests/font/psf.luau` |
|
||||
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
|
||||
| font | type1 | .pfb .pfa .t1 | yes | - | outlines: "type1", variants: "pfb", "pfa" | **missing** |
|
||||
| font | type1 | .pfb .pfa .t1 | yes | - | outlines: "type1", variants: "pfb", "pfa" | `tests/font/type1.luau` |
|
||||
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
|
||||
| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
|
||||
| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` |
|
||||
|
||||
@@ -65,9 +65,7 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
|
||||
end
|
||||
end
|
||||
local function lineTo(dx: number, dy: number)
|
||||
local first = not open
|
||||
ensureOpen()
|
||||
local _ = first
|
||||
x += dx
|
||||
y += dy
|
||||
local c: any = { op = "lineTo" }
|
||||
@@ -242,11 +240,12 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
|
||||
elseif op == 1206 then -- seac: asb adx ady bchar achar
|
||||
local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5)
|
||||
sp = 0
|
||||
if not ctx.seac then
|
||||
local seac = ctx.seac
|
||||
if not seac then
|
||||
return "seac without base glyphs"
|
||||
end
|
||||
local base = ctx.seac(bchar)
|
||||
local accent = ctx.seac(achar)
|
||||
local base = seac(bchar)
|
||||
local accent = seac(achar)
|
||||
if not base or not accent then
|
||||
return "seac of a missing glyph"
|
||||
end
|
||||
|
||||
@@ -224,10 +224,11 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
if sAt and sAt < csAt then
|
||||
local p = sAt
|
||||
while true do
|
||||
local s, e, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p)
|
||||
local s, e0, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p)
|
||||
if not s or s > csAt then
|
||||
break
|
||||
end
|
||||
local e = e0 :: number
|
||||
local i, n = tonumber(idx) :: number, tonumber(len) :: number
|
||||
if i > 65535 then
|
||||
return nil, Err.new(Err.LIMIT, "too many subroutines")
|
||||
@@ -246,10 +247,11 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local byName: { [string]: number } = {}
|
||||
local p = csAt + 12
|
||||
while true do
|
||||
local s, e, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p)
|
||||
local s, e0, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p)
|
||||
if not s then
|
||||
break
|
||||
end
|
||||
local e = e0 :: number
|
||||
-- stop at the end of the dictionary
|
||||
if string.find(string.sub(ptext, p, s), "%send%s") then
|
||||
break
|
||||
@@ -356,7 +358,8 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
if not g then
|
||||
return nil
|
||||
end
|
||||
return Charstring.run(charstrings[g + 1], { subrs = subrs })
|
||||
local res = Charstring.run(charstrings[g + 1], { subrs = subrs })
|
||||
return res
|
||||
end,
|
||||
}
|
||||
return font, nil
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
-- font/type1 tests (and codecs/font/GlyphNames): Latin Modern PFB fonts and a PFA (t1ascii) against fontTools
|
||||
-- (outline control boxes, areas, advances of sample glyphs including flex, hint replacement, seac accents and
|
||||
-- ligatures; code points from glyph names) and FreeType's unhinted renders (PSNR); errors; the fuzz pass.
|
||||
-- Fixtures: tools/fixtures/type1.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Type1 = require("@formats/font/type1")
|
||||
local GlyphNames = require("@formats/codecs/font/GlyphNames")
|
||||
local Raster = require("@formats/codecs/image/Raster")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/type1")
|
||||
|
||||
local t = T.suite("type1")
|
||||
t:eq(Type1.name, "type1", "name")
|
||||
t:eq(GlyphNames.unicode("Aacute"), 0xC1, "agl")
|
||||
t:eq(GlyphNames.unicode("uni20AC"), 0x20AC, "uniXXXX")
|
||||
t:eq(GlyphNames.unicode("u1F600"), 0x1F600, "uXXXXX")
|
||||
t:eq(GlyphNames.unicode("a.sc"), 0x61, "suffix")
|
||||
t:eq(GlyphNames.unicode("f_f_i"), 0x66, "ligature name")
|
||||
t:eq(GlyphNames.unicode("nosuchname"), nil, "unknown")
|
||||
t:eq(GlyphNames.STANDARD[65], "A", "StandardEncoding")
|
||||
|
||||
-- shoelace area of the flattened outline (font units)
|
||||
local function area(cmds: any): number
|
||||
local polys = Raster.flatten(cmds, nil, 0.02)
|
||||
local a = 0
|
||||
for _, p in polys do
|
||||
local n = #p
|
||||
local x0, y0 = p[n - 1], p[n]
|
||||
for i = 1, n - 1, 2 do
|
||||
a += x0 * p[i + 1] - p[i] * y0
|
||||
x0, y0 = p[i], p[i + 1]
|
||||
end
|
||||
end
|
||||
return a / 2
|
||||
end
|
||||
|
||||
local function psnr(img: any, r: any): (number, number)
|
||||
-- union of both bitmaps, aligned on the pen position
|
||||
local ax0, ay0 = img.meta.left, -img.meta.top
|
||||
local bx0, by0 = r.left, -r.top
|
||||
local x0, y0 = math.min(ax0, bx0), math.min(ay0, by0)
|
||||
local x1, y1 = math.max(ax0 + img.width, bx0 + r.width), math.max(ay0 + img.height, by0 + r.height)
|
||||
local se, n, ink = 0, 0, 0
|
||||
for y = y0, y1 - 1 do
|
||||
for x = x0, x1 - 1 do
|
||||
local a, b = 0, 0
|
||||
local ix, iy = x - ax0, y - ay0
|
||||
if ix >= 0 and iy >= 0 and ix < img.width and iy < img.height then
|
||||
a = buffer.readu8(img.pixels, iy * img.width + ix)
|
||||
end
|
||||
local jx, jy = x - bx0, y - by0
|
||||
if jx >= 0 and jy >= 0 and jx < r.width and jy < r.height then
|
||||
b = string.byte(r.pixels, jy * r.width + jx + 1)
|
||||
end
|
||||
se += (a - b) * (a - b)
|
||||
ink += b
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
if n == 0 or se == 0 then
|
||||
return 99, ink
|
||||
end
|
||||
return 10 * math.log10(255 * 255 / (se / n)), ink
|
||||
end
|
||||
|
||||
|
||||
local worst = 99
|
||||
local samples = {}
|
||||
for _, c in Fx.fonts do
|
||||
local font, err = Type1.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(font, c.name .. ": " .. tostring(err))
|
||||
if font then
|
||||
t:eq(font.unitsPerEm, c.upem, c.name .. ": units per em")
|
||||
t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": glyph count")
|
||||
t:eq(font.info.family, c.family, c.name .. ": family")
|
||||
local byName = {}
|
||||
for k, n in font.meta.glyphNames do
|
||||
byName[n] = k - 1
|
||||
end
|
||||
local maxErr = 0
|
||||
for _, g in c.glyphs do
|
||||
local gi = byName[g.name]
|
||||
t:check(gi, c.name .. ": has " .. g.name)
|
||||
if gi then
|
||||
if g.cp then
|
||||
t:eq(font:glyphIndex(g.cp), gi, c.name .. ": cmap " .. g.name)
|
||||
end
|
||||
t:eq(font:advance(gi), g.advance, c.name .. ": advance " .. g.name)
|
||||
local cmds = font:outline(gi) :: any
|
||||
t:check(cmds, c.name .. ": outline " .. g.name)
|
||||
if g.bounds then
|
||||
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
|
||||
for _, cmd in cmds do
|
||||
for i = 1, #cmd, 2 do
|
||||
x0, x1 = math.min(x0, cmd[i]), math.max(x1, cmd[i])
|
||||
y0, y1 = math.min(y0, cmd[i + 1]), math.max(y1, cmd[i + 1])
|
||||
end
|
||||
end
|
||||
local ok = math.abs(x0 - g.bounds[1]) < 0.01 and math.abs(y0 - g.bounds[2]) < 0.01 and math.abs(x1 - g.bounds[3]) < 0.01 and math.abs(y1 - g.bounds[4]) < 0.01
|
||||
t:check(ok, string.format("%s: %s control box %s %s %s %s vs %s %s %s %s", c.name, g.name, x0, y0, x1, y1, g.bounds[1], g.bounds[2], g.bounds[3], g.bounds[4]))
|
||||
end
|
||||
local a = math.abs(area(cmds))
|
||||
local want = math.abs(g.area)
|
||||
local e = if want > 0 then math.abs(a - want) / want else a
|
||||
maxErr = math.max(maxErr, e)
|
||||
t:check(e < 0.002, string.format("%s: %s area %.1f vs %.1f", c.name, g.name, a, want))
|
||||
end
|
||||
end
|
||||
for _, r in c.renders do
|
||||
local img = font:rasterize(font:glyphIndex(r.cp), r.px) :: any
|
||||
local p = psnr(img, r)
|
||||
worst = math.min(worst, p)
|
||||
t:check(p > 25, string.format("%s: U+%04X at %d px: PSNR %.1f dB vs FreeType", c.name, r.cp, r.px, p))
|
||||
end
|
||||
t:note("%-22s %3d glyphs, area err %.5f", c.name, font.numGlyphs, maxErr)
|
||||
end
|
||||
t:eq(F.detect(c.data), "type1", c.name .. ": detect")
|
||||
table.insert(samples, string.sub(c.data, 1, 4000))
|
||||
end
|
||||
t:note("worst PSNR vs FreeType %.1f dB", worst)
|
||||
|
||||
local function code(s: string): string?
|
||||
local _, e = Type1.decode(Bytes.reader(buffer.fromstring(s)))
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("%!PS-AdobeFont-1.0: X\n/FontName /X def\n"), Err.CORRUPT, "no eexec")
|
||||
t:eq(code("\128\1\255\255\0\0"), Err.TRUNCATED, "cut PFB segment")
|
||||
t:eq(code("%!PS-AdobeFont-1.0\ncurrentfile eexec\n00"), Err.TRUNCATED, "short eexec")
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local f = Type1.decode(Bytes.reader(b))
|
||||
if f then
|
||||
for g = 0, math.min(f.numGlyphs - 1, 20) do
|
||||
f:outline(g)
|
||||
end
|
||||
end
|
||||
return f
|
||||
end, samples, { mutations = 20 })
|
||||
t:done()
|
||||
@@ -0,0 +1,79 @@
|
||||
# Type 1 fixtures (tools/fixtures.py): Latin Modern PFB fonts (nixpkgs#lmodern, GUST font licence; read from the nix
|
||||
# store at fixture time) and a PFA made from one of them by t1utils' `t1ascii`; reference outlines from fontTools
|
||||
# (t1Lib parses and decrypts, T1CharString draws through ControlBoundsPen / AreaPen: control boxes, areas, advances),
|
||||
# code points from fontTools.agl, FreeType renders of a few glyphs (PSNR in the test).
|
||||
# tests/gen/type1.luau { fonts = { { name, data, upem, family, glyphs = { { name, cp?, advance, bounds?, area } },
|
||||
# renders = { { cp, px, width, height, left, top, pixels } } } } }
|
||||
import json, os, subprocess
|
||||
|
||||
CODE = r'''
|
||||
import json, sys
|
||||
from fontTools.t1Lib import T1Font
|
||||
from fontTools.pens.areaPen import AreaPen
|
||||
from fontTools.pens.boundsPen import ControlBoundsPen
|
||||
from fontTools import agl
|
||||
import freetype
|
||||
req = json.load(sys.stdin)
|
||||
out = []
|
||||
for spec in req:
|
||||
f = T1Font(spec["path"])
|
||||
f.parse()
|
||||
cs = f["CharStrings"]
|
||||
fi = f.font.get("FontInfo", {})
|
||||
glyphs = []
|
||||
for name in spec["names"]:
|
||||
if name not in cs:
|
||||
continue
|
||||
g = cs[name]
|
||||
bp = ControlBoundsPen(cs)
|
||||
g.draw(bp)
|
||||
ap = AreaPen(cs)
|
||||
g.draw(ap)
|
||||
e = {"name": name, "advance": g.width, "area": ap.value}
|
||||
if bp.bounds:
|
||||
e["bounds"] = list(bp.bounds)
|
||||
u = agl.toUnicode(name)
|
||||
if len(u) == 1:
|
||||
e["cp"] = ord(u)
|
||||
glyphs.append(e)
|
||||
face = freetype.Face(spec["path"])
|
||||
renders = []
|
||||
for ch in "AgQ&8":
|
||||
face.set_pixel_sizes(0, 48)
|
||||
face.load_char(ch, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING)
|
||||
b = face.glyph.bitmap
|
||||
px = bytearray(b.width * b.rows)
|
||||
for y in range(b.rows):
|
||||
for x in range(b.width):
|
||||
px[y * b.width + x] = b.buffer[y * b.pitch + x]
|
||||
renders.append({"cp": ord(ch), "px": 48, "width": b.width, "height": b.rows, "left": face.glyph.bitmap_left,
|
||||
"top": face.glyph.bitmap_top, "pixels": px.hex()})
|
||||
out.append({"family": fi.get("FamilyName", ""), "upem": round(1 / f["FontMatrix"][0]), "glyphs": glyphs, "renders": renders,
|
||||
"numGlyphs": len(cs.keys())})
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
NAMES = ["A", "B", "O", "Q", "a", "g", "e", "f", "fi", "ffl", "zero", "eight", "ampersand", "Aacute", "eacute", "ccedilla",
|
||||
"Lslash", "dotlessi", "quotedblleft", "emdash", "germandbls", "AE", "oe", "space", "period", "parenleft", "Ydieresis"]
|
||||
|
||||
|
||||
def store(pkg):
|
||||
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
lm = os.path.join(store("lmodern"), "share", "fonts", "type1", "public", "lm")
|
||||
t1 = store("t1utils")
|
||||
paths = [(os.path.join(lm, f), f) for f in ("lmr10.pfb", "lmbx12.pfb", "lmri10.pfb", "lmtt10.pfb")]
|
||||
import tempfile
|
||||
tmp = tempfile.mkdtemp(prefix="type1-")
|
||||
pfa = os.path.join(tmp, "lmr10.pfa")
|
||||
subprocess.run([os.path.join(t1, "bin", "t1ascii"), paths[0][0], pfa], check=True, capture_output=True)
|
||||
paths.append((pfa, "lmr10.pfa (t1ascii)"))
|
||||
refs = json.loads(ctx.python(["fonttools", "freetype-py"], CODE, input=json.dumps([{"path": p, "names": NAMES} for p, _ in paths]).encode()))
|
||||
fonts = []
|
||||
for (p, name), ref in zip(paths, refs):
|
||||
for r in ref["renders"]:
|
||||
r["pixels"] = bytes.fromhex(r["pixels"])
|
||||
fonts.append({"name": name, "data": open(p, "rb").read(), **ref})
|
||||
ctx.emit("type1", {"fonts": fonts})
|
||||
Reference in new issue
Block a user