From 64dc0aa7f5d724886522e8d8a68e5a962f1d8e24 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:42:57 -0500 Subject: [PATCH] ws-arch: font/woff and font/woff2 (glyf/loca/hmtx transforms) with tests: identical glyphs to the sfnt --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 24 ++ src/Formats/font/woff/init.luau | 132 +++++++ src/Formats/font/woff2/Rebuild.luau | 541 ++++++++++++++++++++++++++++ src/Formats/font/woff2/init.luau | 59 +++ tests/font/woff.luau | 100 +++++ tests/font/woff2.luau | 100 +++++ tools/fixtures/_font_reference.py | 6 +- tools/fixtures/fonts.py | 2 +- 9 files changed, 964 insertions(+), 2 deletions(-) create mode 100644 src/Formats/font/woff/init.luau create mode 100644 src/Formats/font/woff2/Rebuild.luau create mode 100644 src/Formats/font/woff2/init.luau create mode 100644 tests/font/woff.luau create mode 100644 tests/font/woff2.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index dc44caa..cde3264 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -7,6 +7,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.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` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 23106c2..bae7d42 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -38,6 +38,30 @@ local list: { Entry } = { return require("@formats/font/ttf") end, }, + { + name = "woff", + category = "font", + path = "font/woff", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, + load = function() + return require("@formats/font/woff") + end, + }, + { + name = "woff2", + category = "font", + path = "font/woff2", + extensions = { "woff2" }, + mime = { "font/woff2" }, + deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, + load = function() + return require("@formats/font/woff2") + end, + }, { name = "7z", category = "archive", diff --git a/src/Formats/font/woff/init.luau b/src/Formats/font/woff/init.luau new file mode 100644 index 0000000..6b1bb91 --- /dev/null +++ b/src/Formats/font/woff/init.luau @@ -0,0 +1,132 @@ +--!strict +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding +-- rebuilds the sfnt and reads it through codecs/TrueType (TrueType or CFF outlines, see font/ttf); the extended +-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Deflate = require("@formats/codecs/Deflate") +local TrueType = require("@formats/codecs/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff = { + name = "woff", + category = "font", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Woff.sniff(r: Bytes.Reader): number + return if r:peek(4) == "wOFF" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err +function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?) + local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local base = r.base + if not r:match("wOFF") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local total = r:u32be() + r:skip(4) + local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be() + r:skip(8) + if r.err then + return nil, r.err + end + if flavor == "ttcf" then + return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4) + end + if length > r:size() then + return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8) + end + if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then + return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12) + end + local dir = {} + for i = 1, numTables do + local e = { tag = r:string(4), offset = r:u32be(), comp = r:u32be(), orig = r:u32be(), sum = r:u32be() } + dir[i] = e + end + if r.err then + return nil, r.err + end + local out = buffer.create(total) + local w = Bytes.writer(12) + w:string(flavor) + w:u16be(numTables) + local es, sel = 1, 0 + while es * 2 <= numTables do + es *= 2 + sel += 1 + end + w:u16be(es * 16) + w:u16be(sel) + w:u16be(numTables * 16 - es * 16) + buffer.copy(out, 0, w.buf, 0, 12) + local p = 12 + 16 * numTables + for i, e in dir do + if e.offset + e.comp > r:size() or e.comp > e.orig then + return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20) + end + if p + e.orig > total then + return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16) + end + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, e.tag) + buffer.writeu32(out, d + 4, bit32.byteswap(e.sum)) + buffer.writeu32(out, d + 8, bit32.byteswap(p)) + buffer.writeu32(out, d + 12, bit32.byteswap(e.orig)) + if e.comp < e.orig then + local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig) + if not t then + return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset) + end + buffer.copy(out, p, t, 0, e.orig) + else + buffer.copy(out, p, r.buf, base + e.offset, e.orig) + end + p += e.orig + p = (p + 3) // 4 * 4 + if p > total then + p = total + end + end + local xml = nil + if metaLength > 0 and metaOffset + metaLength <= r:size() then + local m = Deflate.zlib(r.buf, base + metaOffset, metaLength, metaOrig) + if m then + xml = buffer.tostring(m) + end + end + return out, nil, xml +end + +function Woff.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sfnt, err, xml = Woff.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.woffMetadata = xml + font.meta.source = { format = "woff", outlines = font.meta.outlines } + return font, nil +end + +return Woff diff --git a/src/Formats/font/woff2/Rebuild.luau b/src/Formats/font/woff2/Rebuild.luau new file mode 100644 index 0000000..7cbf3b3 --- /dev/null +++ b/src/Formats/font/woff2/Rebuild.luau @@ -0,0 +1,541 @@ +--!strict +-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table +-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, +-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx +-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). +-- +-- Never throws: malformed data returns nil, message. +local Bytes = require("@formats/core/Bytes") +local Brotli = require("@formats/codecs/Brotli") + +local Rebuild = {} + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local KNOWN = { + "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", + "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", + "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", + "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", + "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill", +} + +-- UIntBase128 from r +local function base128(r: Bytes.Reader): number? + local v = 0 + for i = 1, 5 do + local b = r:u8() + if r.err or (i == 1 and b == 0x80) then + return nil + end + if v >= 2 ^ 25 then + return nil + end + v = v * 128 + band(b, 0x7F) + if b < 0x80 then + return v + end + end + return nil +end + +-- a cursor over a stream inside the decompressed block +type Stream = { buf: buffer, p: number, e: number, bad: boolean } +local function stream(b: buffer, p: number, n: number): Stream + return { buf = b, p = p, e = p + n, bad = false } +end +local function su8(s: Stream): number + if s.p >= s.e then + s.bad = true + return 0 + end + local v = readu8(s.buf, s.p) + s.p += 1 + return v +end +local function su16(s: Stream): number + return su8(s) * 256 + su8(s) +end +local function si16(s: Stream): number + local v = su16(s) + return if v >= 32768 then v - 65536 else v +end +local function s255(s: Stream): number + local c = su8(s) + if c == 253 then + return su16(s) + elseif c == 255 then + return su8(s) + 253 + elseif c == 254 then + return su8(s) + 506 + end + return c +end + +local function withSign(flag: number, v: number): number + return if band(flag, 1) ~= 0 then v else -v +end + +-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat +local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?) + local h = stream(b, p, n) + su16(h) -- reserved + local option = su16(h) + local numGlyphs = su16(h) + local indexFormat = su16(h) + local sizes = {} + for i = 1, 7 do + sizes[i] = su16(h) * 65536 + su16(h) + end + if h.bad then + return nil, "truncated glyf transform header" + end + local at = h.p + local streams: { Stream } = {} + for i = 1, 7 do + if at + sizes[i] > p + n then + return nil, "glyf transform stream past the end" + end + streams[i] = stream(b, at, sizes[i]) + at += sizes[i] + end + local nContour, nPoints, flagS, glyphS, compS, bboxS, instrS = streams[1], streams[2], streams[3], streams[4], streams[5], streams[6], streams[7] + local overlap: Stream? = nil + if band(option, 1) ~= 0 then + overlap = stream(b, at, (numGlyphs + 7) // 8) + if at + (numGlyphs + 7) // 8 > p + n then + return nil, "overlap bitmap past the end" + end + end + -- the bbox bitmap leads the bbox stream + local bitmapLen = 4 * ((numGlyphs + 31) // 32) + if bitmapLen > sizes[6] then + return nil, "bbox bitmap past the end" + end + local bboxBits = bboxS.p + bboxS.p += bitmapLen + local function hasBox(g: number): boolean + return band(readu8(b, bboxBits + g // 8), rshift(0x80, g % 8)) ~= 0 + end + local w = Bytes.writer(n * 2) + local loca = table.create(numGlyphs + 1, 0) + local xMins = table.create(numGlyphs, 0) + for g = 0, numGlyphs - 1 do + loca[g + 1] = w.pos + local nc = si16(nContour) + if nContour.bad then + return nil, "nContour stream truncated" + end + if nc == 0 then + if hasBox(g) then + return nil, "empty glyph with a bounding box" + end + elseif nc > 0 then + -- simple glyph + local ends = table.create(nc, 0) + local total = 0 + for c = 1, nc do + total += s255(nPoints) + ends[c] = total - 1 + end + if nPoints.bad or total > 65535 then + return nil, "bad point counts" + end + local xs, ys, on = table.create(total, 0), table.create(total, 0), table.create(total, false) + local x, y = 0, 0 + for k = 1, total do + local fl = su8(flagS) + on[k] = rshift(fl, 7) == 0 + fl = band(fl, 0x7F) + local dx, dy + if fl < 10 then + dx, dy = 0, withSign(fl, band(fl, 14) * 128 + su8(glyphS)) + elseif fl < 20 then + dx, dy = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)), 0 + elseif fl < 84 then + local b0 = fl - 20 + local b1 = su8(glyphS) + dx = withSign(fl, 1 + band(b0, 0x30) + rshift(b1, 4)) + dy = withSign(rshift(fl, 1), 1 + band(b0, 0x0C) * 4 + band(b1, 0x0F)) + elseif fl < 120 then + local b0 = fl - 84 + dx = withSign(fl, 1 + (b0 // 12) * 256 + su8(glyphS)) + dy = withSign(rshift(fl, 1), 1 + rshift(b0 % 12, 2) * 256 + su8(glyphS)) + elseif fl < 124 then + local b1, b2, b3 = su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 16 + rshift(b2, 4)) + dy = withSign(rshift(fl, 1), band(b2, 0x0F) * 256 + b3) + else + local b1, b2, b3, b4 = su8(glyphS), su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 256 + b2) + dy = withSign(rshift(fl, 1), b3 * 256 + b4) + end + x += dx + y += dy + xs[k], ys[k] = x, y + end + local ilen = s255(glyphS) + if flagS.bad or glyphS.bad then + return nil, "flag / glyph stream truncated" + end + local x0, y0, x1, y1 + if hasBox(g) then + x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) + else + x0, y0, x1, y1 = 32767, 32767, -32768, -32768 + for k = 1, total do + x0, y0 = math.min(x0, xs[k]), math.min(y0, ys[k]) + x1, y1 = math.max(x1, xs[k]), math.max(y1, ys[k]) + end + if total == 0 then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + end + xMins[g + 1] = x0 + w:u16be(nc % 65536) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + for c = 1, nc do + w:u16be(ends[c]) + end + w:u16be(ilen) + if instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:bytes(b, instrS.p, ilen) + instrS.p += ilen + local ov = overlap ~= nil and band(readu8(b, (overlap :: Stream).p + g // 8), rshift(0x80, g % 8)) ~= 0 + -- flags (short vectors, same-as-previous, repeats) and the coordinate deltas, as compilers write them + local fls = table.create(total, 0) + for k = 1, total do + local fl = if on[k] then 1 else 0 + if k == 1 and ov then + fl += 0x40 + end + local dx = xs[k] - (if k > 1 then xs[k - 1] else 0) + local dy = ys[k] - (if k > 1 then ys[k - 1] else 0) + if dx == 0 then + fl += 0x10 + elseif dx > -256 and dx < 256 then + fl += if dx > 0 then 0x12 else 0x02 + end + if dy == 0 then + fl += 0x20 + elseif dy > -256 and dy < 256 then + fl += if dy > 0 then 0x24 else 0x04 + end + fls[k] = fl + end + local k = 1 + while k <= total do + local fl = fls[k] + local run = 0 + while k + run + 1 <= total and fls[k + run + 1] == fl and run < 255 do + run += 1 + end + if run > 1 then + w:u8(fl + 8) + w:u8(run) + k += run + 1 + else + w:u8(fl) + k += 1 + end + end + for pass = 0, 1 do + local cs = if pass == 0 then xs else ys + local short, same = if pass == 0 then 0x02 else 0x04, if pass == 0 then 0x10 else 0x20 + local prev = 0 + for q = 1, total do + local d = cs[q] - prev + prev = cs[q] + local fl = fls[q] + if band(fl, short) ~= 0 then + w:u8(math.abs(d)) + elseif band(fl, same) == 0 then + w:u16be(d % 65536) + end + end + end + elseif nc == -1 then + if not hasBox(g) then + return nil, "composite glyph without a bounding box" + end + local x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) + xMins[g + 1] = x0 + w:u16be(0xFFFF) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + -- copy the component records: their length follows from the flags + local start = compS.p + local instr = false + while true do + local fl = su16(compS) + su16(compS) -- glyph index + local len = if band(fl, 1) ~= 0 then 4 else 2 + if band(fl, 8) ~= 0 then + len += 2 + elseif band(fl, 0x40) ~= 0 then + len += 4 + elseif band(fl, 0x80) ~= 0 then + len += 8 + end + compS.p += len + if band(fl, 0x100) ~= 0 then + instr = true + end + if compS.bad or compS.p > compS.e then + return nil, "composite stream truncated" + end + if band(fl, 0x20) == 0 then + break + end + end + w:bytes(b, start, compS.p - start) + if instr then + local ilen = s255(glyphS) + if glyphS.bad or instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:u16be(ilen) + w:bytes(b, instrS.p, ilen) + instrS.p += ilen + end + else + return nil, "bad contour count " .. nc + end + if bboxS.bad then + return nil, "bbox stream truncated" + end + -- 4-byte alignment + while w.pos % 4 ~= 0 do + w:u8(0) + end + if w.pos > maxBytes then + return nil, "limit" + end + end + loca[numGlyphs + 1] = w.pos + if indexFormat == 0 and w.pos > 0x1FFFE then + indexFormat = 1 -- (head.indexToLocFormat is patched to match) + end + return { glyf = w:finish(), loca = loca, xMins = xMins, numGlyphs = numGlyphs, indexFormat = indexFormat }, nil +end + +-- hmtx transform (version 1): advances + the side bearings that were not dropped +local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: number, xMins: { number }): (buffer?, string?) + local s = stream(b, p, n) + local flags = su8(s) + local out = Bytes.writer(numH * 4 + (numGlyphs - numH) * 2) + local adv = table.create(numH, 0) + for i = 1, numH do + adv[i] = su16(s) + end + local lsb = table.create(numGlyphs, 0) + for i = 1, numH do + lsb[i] = if band(flags, 1) == 0 then si16(s) else (xMins[i] or 0) + end + for i = numH + 1, numGlyphs do + lsb[i] = if band(flags, 2) == 0 then si16(s) else (xMins[i] or 0) + end + if s.bad then + return nil, "hmtx transform truncated" + end + for i = 1, numH do + out:u16be(adv[i]) + out:u16be(lsb[i] % 65536) + end + for i = numH + 1, numGlyphs do + out:u16be(lsb[i] % 65536) + end + return out:finish(), nil +end + +-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") +function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?) + if not r:match("wOF2") then + return nil, "bad signature", "corrupt" + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local totalSfnt = r:u32be() + local totalComp = r:u32be() + r:skip(24) + if r.err then + return nil, "truncated header", "truncated" + end + if flavor == "ttcf" then + return nil, "font collections in WOFF2", "unsupported" + end + if length > r:size() then + return nil, "file shorter than its header says", "truncated" + end + if numTables == 0 or numTables > 1024 then + return nil, "bad table count", "corrupt" + end + local dir = {} + local streamTotal = 0 + for i = 1, numTables do + local flags = r:u8() + local tag = KNOWN[band(flags, 63) + 1] + if band(flags, 63) == 63 then + tag = r:string(4) + end + local version = rshift(flags, 6) + local orig = base128(r) + if not tag or not orig then + return nil, "bad table directory entry " .. i, if r.err then "truncated" else "corrupt" + end + local transformed = if tag == "glyf" or tag == "loca" then version == 0 else version ~= 0 + local tlen = orig + if transformed then + local t = base128(r) + if not t then + return nil, "bad transformLength", "corrupt" + end + tlen = t + end + if (tag == "glyf" or tag == "loca") and not transformed and version ~= 3 then + return nil, "bad glyf / loca transform version", "corrupt" + end + if transformed and tag ~= "glyf" and tag ~= "loca" and tag ~= "hmtx" then + return nil, "unknown transform of " .. tag, "unsupported" + end + dir[i] = { tag = tag, orig = orig, len = tlen, transformed = transformed, at = streamTotal } + streamTotal += tlen + if streamTotal > maxBytes or orig > maxBytes then + return nil, "limit", "limit" + end + end + local compAt = r.pos + if compAt + totalComp > r.limit then + return nil, "compressed data past the end", "truncated" + end + local data, berr = Brotli.decompress(r.buf, compAt, totalComp, { maxBytes = math.max(streamTotal, 1) }) + if not data then + local e = berr :: any + return nil, "brotli: " .. tostring(e.message), if e.code == "LIMIT" then "limit" else "corrupt" + end + if buffer.len(data) < streamTotal then + return nil, "decompressed stream shorter than the tables", "corrupt" + end + -- the tables, glyf / loca / hmtx rebuilt + local byTag: { [string]: any } = {} + for _, e in dir do + byTag[e.tag] = e + end + local tables: { [string]: buffer } = {} + local g = byTag.glyf + local xMins: { number } = {} + local locaLong: boolean? = nil + if g and g.transformed then + if not byTag.loca then + return nil, "glyf without loca", "corrupt" + end + local res, gerr = glyf(data, g.at, g.len, maxBytes) + if not res then + return nil, "glyf: " .. tostring(gerr), if gerr == "limit" then "limit" else "corrupt" + end + tables.glyf = res.glyf + xMins = res.xMins + local short = res.indexFormat == 0 + local lw = Bytes.writer((res.numGlyphs + 1) * 4) + for _, o in res.loca do + if short then + lw:u16be(o // 2) + else + lw:u32be(o) + end + end + tables.loca = lw:finish() + locaLong = not short + end + for _, e in dir do + if e.tag == "glyf" or e.tag == "loca" then + if not e.transformed then + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + elseif e.tag == "hmtx" and e.transformed then + -- needs numGlyphs (maxp) and numberOfHMetrics (hhea) + local mp, hh = byTag.maxp, byTag.hhea + if not mp or not hh or mp.len < 6 or hh.len < 36 then + return nil, "hmtx transform without maxp / hhea", "corrupt" + end + local numGlyphs = readu8(data, mp.at + 4) * 256 + readu8(data, mp.at + 5) + local numH = readu8(data, hh.at + 34) * 256 + readu8(data, hh.at + 35) + if numH < 1 or numH > numGlyphs then + return nil, "bad numberOfHMetrics", "corrupt" + end + local t, herr = hmtx(data, e.at, e.len, numGlyphs, numH, xMins) + if not t then + return nil, herr, "corrupt" + end + tables.hmtx = t + else + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + end + -- head.indexToLocFormat must agree with the rebuilt loca + if locaLong ~= nil and tables.head and buffer.len(tables.head) >= 54 then + buffer.writeu8(tables.head, 50, 0) + buffer.writeu8(tables.head, 51, if locaLong then 1 else 0) + end + -- the sfnt: directory sorted by tag, tables 4-byte aligned + local tags = {} + for t in tables do + table.insert(tags, t) + end + table.sort(tags) + local n = #tags + local size = 12 + 16 * n + for _, t in tags do + size += (buffer.len(tables[t]) + 3) // 4 * 4 + end + if size > maxBytes then + return nil, "limit", "limit" + end + local out = buffer.create(size) + buffer.writestring(out, 0, flavor) + local es, sel = 1, 0 + while es * 2 <= n do + es *= 2 + sel += 1 + end + local function be16(o: number, v: number) + buffer.writeu8(out, o, rshift(v, 8)) + buffer.writeu8(out, o + 1, band(v, 255)) + end + local function be32(o: number, v: number) + buffer.writeu32(out, o, bit32.byteswap(v)) + end + be16(4, n) + be16(6, es * 16) + be16(8, sel) + be16(10, n * 16 - es * 16) + local p = 12 + 16 * n + for i, t in tags do + local tb = tables[t] + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, t) + be32(d + 4, 0) -- checksums are not recomputed + be32(d + 8, p) + be32(d + 12, buffer.len(tb)) + buffer.copy(out, p, tb) + p += (buffer.len(tb) + 3) // 4 * 4 + end + local _ = totalSfnt + return out, nil, nil +end + +return Rebuild diff --git a/src/Formats/font/woff2/init.luau b/src/Formats/font/woff2/init.luau new file mode 100644 index 0000000..1d368b4 --- /dev/null +++ b/src/Formats/font/woff2/init.luau @@ -0,0 +1,59 @@ +--!strict +-- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx +-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/TrueType (TrueType or CFF +-- outlines, see font/ttf). Written from the spec; Brotli is codecs/Brotli. Not supported: collections, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local TrueType = require("@formats/codecs/TrueType") +local Rebuild = require("@formats/font/woff2/Rebuild") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff2 = { + name = "woff2", + category = "font", + extensions = { "woff2" }, + mime = { "font/woff2" }, + deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODES = { truncated = Err.TRUNCATED, corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT } + +-- ------------------------------------------------------------------------------------------------ sniff +function Woff2.sniff(r: Bytes.Reader): number + return if r:peek(4) == "wOF2" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err +function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) + local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local at = r.base + local out, msg, code = Rebuild.sfnt(r, maxBytes) + if not out then + return nil, Err.new(CODES[code or "corrupt"] or Err.CORRUPT, msg or "rebuild failed", at) + end + return out, nil +end + +function Woff2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sfnt, err = Woff2.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.source = { format = "woff2", outlines = font.meta.outlines } + return font, nil +end + +return Woff2 diff --git a/tests/font/woff.luau b/tests/font/woff.luau new file mode 100644 index 0000000..218a1cc --- /dev/null +++ b/tests/font/woff.luau @@ -0,0 +1,100 @@ +-- font/woff tests: every fixture font as WOFF 1.0 (fontTools, zlib tables) decodes to the same font as the sfnt itself (font/ttf, checked against +-- fontTools / FreeType in tests/font/ttf.luau): metrics, names, every glyph's outline, advance and side bearing, +-- cmap and kerning samples; rasterize works; the api detects it; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Woff = require("@formats/font/woff") +local Ttf = require("@formats/font/ttf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("woff") +t:eq(Woff.name, "woff", "name") + +local function same(a: any, b: any, label: string) + for _, k in { "unitsPerEm", "ascent", "descent", "lineGap", "numGlyphs" } do + t:eq(a[k], b[k], label .. ": " .. k) + end + t:eq(a.info.family, b.info.family, label .. ": family") + t:eq(a.info.fullName, b.info.fullName, label .. ": fullName") + for g = 0, a.numGlyphs - 1 do + t:eq(a:advance(g), b:advance(g), label .. ": advance " .. g) + t:eq(a:leftSideBearing(g), b:leftSideBearing(g), label .. ": lsb " .. g) + local oa, ob = a:outline(g), b:outline(g) + t:check(oa and ob and #oa == #ob, label .. ": outline " .. g .. " command count") + for i, c in oa do + local d = ob[i] + local ok = c.op == d.op and #c == #d + for j = 1, #c do + ok = ok and c[j] == d[j] + end + if not ok then + t:check(false, string.format("%s: glyph %d command %d differs", label, g, i)) + end + end + end + for cp = 0, 0x2FF do + t:eq(a:glyphIndex(cp), b:glyphIndex(cp), label .. ": cmap " .. cp) + end + local ga, gv = a:glyphIndex(65), a:glyphIndex(86) + t:eq(a:kern(ga, gv), b:kern(ga, gv), label .. ": kern A V") +end + +local refs: { [string]: string } = {} +for _, c in Fx.fonts do + refs[c.name] = c.data +end +local samples = {} +local n = 0 +for _, w in Fx.woff do + for _, key in { "woff" } do + local data = w[key] + local font, err = Woff.decode(Bytes.reader(buffer.fromstring(data))) + t:check(font, w.name .. " (" .. key .. "): " .. tostring(err)) + t:eq(font.meta.source.format, "woff", "source format") + local ref = assert(Ttf.decode(Bytes.reader(buffer.fromstring(refs[w.name])))) + same(font, ref, w.name .. " (" .. key .. ")") + local img = font:rasterize(font:glyphIndex(65), 24) + t:check(img and img.width > 0, w.name .. ": rasterize") + n += 1 + if #data < 40000 then + table.insert(samples, data) + end + t:note("%-20s %-7s %7d bytes (sfnt %d), %d glyphs identical", w.name, key, #data, #refs[w.name], font.numGlyphs) + end +end +t:check(n >= 6, "fixture count") + +-- the api +do + local data = Fx.woff[1].woff + t:eq(F.detect(data), "woff", "F.detect") + local f = F.font.load(data) + t:check(f and f.kind == "font", "F.font.load") + t:eq(Woff.sniff(Bytes.reader(buffer.fromstring("wOFF"))) + Woff.sniff(Bytes.reader(buffer.fromstring("wOF2"))), 1, "sniff") +end + +-- errors +do + local data = Fx.woff[1].woff + local _, e1 = Woff.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, 30)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated header: " .. tostring(e1)) + local _, e2 = Woff.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, #data - 100)))) + t:check(e2 ~= nil, "truncated data: " .. tostring(e2)) + local _, e3 = Woff.decode(Bytes.reader(buffer.fromstring("ttcf" .. string.rep("\0", 60)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad signature: " .. tostring(e3)) +end + +t:fuzz("decode", function(b: buffer) + local f = Woff.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 40) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + end + return f +end, samples, { mutations = 25, garbage = 200 }) + +t:done() diff --git a/tests/font/woff2.luau b/tests/font/woff2.luau new file mode 100644 index 0000000..ca7af20 --- /dev/null +++ b/tests/font/woff2.luau @@ -0,0 +1,100 @@ +-- font/woff2 tests: every fixture font as WOFF2 (fontTools: the default glyf / loca transform, and with the hmtx transform too) decodes to the same font as the sfnt itself (font/ttf, checked against +-- fontTools / FreeType in tests/font/ttf.luau): metrics, names, every glyph's outline, advance and side bearing, +-- cmap and kerning samples; rasterize works; the api detects it; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Woff2 = require("@formats/font/woff2") +local Ttf = require("@formats/font/ttf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("woff2") +t:eq(Woff2.name, "woff2", "name") + +local function same(a: any, b: any, label: string) + for _, k in { "unitsPerEm", "ascent", "descent", "lineGap", "numGlyphs" } do + t:eq(a[k], b[k], label .. ": " .. k) + end + t:eq(a.info.family, b.info.family, label .. ": family") + t:eq(a.info.fullName, b.info.fullName, label .. ": fullName") + for g = 0, a.numGlyphs - 1 do + t:eq(a:advance(g), b:advance(g), label .. ": advance " .. g) + t:eq(a:leftSideBearing(g), b:leftSideBearing(g), label .. ": lsb " .. g) + local oa, ob = a:outline(g), b:outline(g) + t:check(oa and ob and #oa == #ob, label .. ": outline " .. g .. " command count") + for i, c in oa do + local d = ob[i] + local ok = c.op == d.op and #c == #d + for j = 1, #c do + ok = ok and c[j] == d[j] + end + if not ok then + t:check(false, string.format("%s: glyph %d command %d differs", label, g, i)) + end + end + end + for cp = 0, 0x2FF do + t:eq(a:glyphIndex(cp), b:glyphIndex(cp), label .. ": cmap " .. cp) + end + local ga, gv = a:glyphIndex(65), a:glyphIndex(86) + t:eq(a:kern(ga, gv), b:kern(ga, gv), label .. ": kern A V") +end + +local refs: { [string]: string } = {} +for _, c in Fx.fonts do + refs[c.name] = c.data +end +local samples = {} +local n = 0 +for _, w in Fx.woff do + for _, key in { "woff2", "woff2h" } do + local data = w[key] + local font, err = Woff2.decode(Bytes.reader(buffer.fromstring(data))) + t:check(font, w.name .. " (" .. key .. "): " .. tostring(err)) + t:eq(font.meta.source.format, "woff2", "source format") + local ref = assert(Ttf.decode(Bytes.reader(buffer.fromstring(refs[w.name])))) + same(font, ref, w.name .. " (" .. key .. ")") + local img = font:rasterize(font:glyphIndex(65), 24) + t:check(img and img.width > 0, w.name .. ": rasterize") + n += 1 + if #data < 40000 then + table.insert(samples, data) + end + t:note("%-20s %-7s %7d bytes (sfnt %d), %d glyphs identical", w.name, key, #data, #refs[w.name], font.numGlyphs) + end +end +t:check(n >= 6, "fixture count") + +-- the api +do + local data = Fx.woff[1].woff2 + t:eq(F.detect(data), "woff2", "F.detect") + local f = F.font.load(data) + t:check(f and f.kind == "font", "F.font.load") + t:eq(Woff2.sniff(Bytes.reader(buffer.fromstring("wOFF"))) + Woff2.sniff(Bytes.reader(buffer.fromstring("wOF2"))), 1, "sniff") +end + +-- errors +do + local data = Fx.woff[1].woff2 + local _, e1 = Woff2.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, 30)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated header: " .. tostring(e1)) + local _, e2 = Woff2.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, #data - 100)))) + t:check(e2 ~= nil, "truncated data: " .. tostring(e2)) + local _, e3 = Woff2.decode(Bytes.reader(buffer.fromstring("ttcf" .. string.rep("\0", 60)))) + t:check(e3 and e3.code == Err.CORRUPT, "bad signature: " .. tostring(e3)) +end + +t:fuzz("decode", function(b: buffer) + local f = Woff2.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 40) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + end + return f +end, samples, { mutations = 25, garbage = 200 }) + +t:done() diff --git a/tools/fixtures/_font_reference.py b/tools/fixtures/_font_reference.py index 96e0c2a..17ba026 100644 --- a/tools/fixtures/_font_reference.py +++ b/tools/fixtures/_font_reference.py @@ -148,6 +148,10 @@ def flavors(data): b = io.BytesIO() f.save(b) out[fl] = b64(b.getvalue()) + from fontTools.ttLib import woff2 + src, dst = io.BytesIO(data), io.BytesIO() + woff2.compress(src, dst, transform_tables={"glyf", "loca", "hmtx"}) + out["woff2h"] = b64(dst.getvalue()) return out @@ -170,7 +174,7 @@ def main(): # woff / woff2 of every font (the reference values are the sfnt's own) for name, data in fonts.items(): fl = flavors(data) - res["woff"].append({"name": name, "woff": fl["woff"], "woff2": fl["woff2"]}) + res["woff"].append({"name": name, "woff": fl["woff"], "woff2": fl["woff2"], "woff2h": fl["woff2h"]}) json.dump(res, sys.stdout) diff --git a/tools/fixtures/fonts.py b/tools/fixtures/fonts.py index 35f655b..bab68e6 100644 --- a/tools/fixtures/fonts.py +++ b/tools/fixtures/fonts.py @@ -31,7 +31,7 @@ def generate(ctx): for r in f["renders"]: r["pixels"] = d(r["pixels"]) for w in res["woff"]: - w["woff"], w["woff2"] = d(w["woff"]), d(w["woff2"]) + w["woff"], w["woff2"], w["woff2h"] = d(w["woff"]), d(w["woff2"]), d(w["woff2h"]) if "ttc" in res: res["ttc"]["data"] = d(res["ttc"]["data"]) ctx.emit("fonts", res)