Files
rosetta/src/Formats/font/woff2/Rebuild.luau
T

542 lines
16 KiB
Luau

--!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