diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..fa63e2f 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,7 +6,25 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.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` | +| archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | +| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | +| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | +| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written +- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec +- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): +- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..8c83472 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -4,6 +4,8 @@ |---|---|---| | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | +| `src/Formats/codecs/Brotli/Static.luau` (static dictionary, context lookup table, word transforms; generated by `tools/brotli_static.py`), `src/Formats/codecs/Brotli/Decode.luau` (written from RFC 7932, structure after the reference decoder) | google/brotli | MIT: [brotli-LICENSE.txt](brotli-LICENSE.txt) | +| `src/Formats/codecs/Lzma/`, `src/Formats/archive/xz/`, `src/Formats/archive/7z/` | written from the LZMA specification / LzmaSpec.cpp and 7zFormat.txt (LZMA SDK, Igor Pavlov), the xz file format specification and xz-embedded's BCJ filters (Lasse Collin) | all public domain: [lzma-xz-PUBLIC-DOMAIN.txt](lzma-xz-PUBLIC-DOMAIN.txt) | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/licenses/brotli-LICENSE.txt b/licenses/brotli-LICENSE.txt new file mode 100644 index 0000000..33b7cdd --- /dev/null +++ b/licenses/brotli-LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/licenses/lzma-xz-PUBLIC-DOMAIN.txt b/licenses/lzma-xz-PUBLIC-DOMAIN.txt new file mode 100644 index 0000000..eb3afbd --- /dev/null +++ b/licenses/lzma-xz-PUBLIC-DOMAIN.txt @@ -0,0 +1,9 @@ +LZMA SDK (Igor Pavlov): "LZMA SDK is placed in the public domain. Anyone is free to copy, modify, publish, use, +compile, sell, or distribute the original LZMA SDK code, either in source code form or as a compiled binary, for any +purpose, commercial or non-commercial, and by any means." (https://www.7-zip.org/sdk.html). This covers the LZMA +specification (lzma-specification.txt, LzmaSpec.cpp) and 7zFormat.txt that codecs/Lzma and archive/7z follow. + +XZ Utils / xz-embedded (Lasse Collin): the xz file format specification and xz-embedded (including xz_dec_bcj.c, whose +BCJ filters codecs/Lzma/Filters follows) were released into the public domain ("This file has been put into the public +domain. You can do whatever you want with this file."); newer releases use the 0BSD licence, which imposes no +conditions either. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..c0070ac 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,138 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "bmfont", + category = "font", + path = "font/bmfont", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } }, + load = function() + return require("@formats/font/bmfont") + end, + }, + { + name = "ttf", + category = "font", + path = "font/ttf", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, + load = function() + 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", + path = "archive/7z", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, + load = function() + return require("@formats/archive/7z") + end, + }, + { + name = "br", + category = "archive", + path = "archive/br", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return require("@formats/archive/br") + end, + }, + { + name = "bz2", + category = "archive", + path = "archive/bz2", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return require("@formats/archive/bz2") + end, + }, + { + name = "gzip", + category = "archive", + path = "archive/gzip", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, + load = function() + return require("@formats/archive/gzip") + end, + }, + { + name = "tar", + category = "archive", + path = "archive/tar", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, + load = function() + return require("@formats/archive/tar") + end, + }, + { + name = "xz", + category = "archive", + path = "archive/xz", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } }, + load = function() + return require("@formats/archive/xz") + end, + }, + { + name = "zst", + category = "archive", + path = "archive/zst", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return require("@formats/archive/zst") + end, + }, } return list diff --git a/src/Formats/archive/7z/Header.luau b/src/Formats/archive/7z/Header.luau new file mode 100644 index 0000000..c85accc --- /dev/null +++ b/src/Formats/archive/7z/Header.luau @@ -0,0 +1,542 @@ +--!strict +-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): +-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams / +-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and +-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local Header = {} + +export type Coder = { id: string, numIn: number, numOut: number, props: buffer } +export type Folder = { + coders: { Coder }, + bindPairs: { { inIndex: number, outIndex: number } }, + packed: { number }, -- in-stream index of each packed stream + unpackSizes: { number }, -- per out stream + crc: number?, + firstPack: number, -- index of the folder's first pack stream (0-based) + numSub: number, -- substreams (files) in the folder +} +export type Streams = { + packPos: number, + packSizes: { number }, + folders: { Folder }, + subSizes: { number }, -- every substream, folder by folder + subCrcs: { [number]: number }, -- 1-based substream index -> CRC +} +export type File = { + name: string, + emptyStream: boolean, + emptyFile: boolean, + anti: boolean, + mtime: number?, + attributes: number?, +} +export type Parsed = { streams: Streams?, files: { File }, encoded: Streams? } + +local K = { + End = 0x00, + Header = 0x01, + ArchiveProperties = 0x02, + AdditionalStreamsInfo = 0x03, + MainStreamsInfo = 0x04, + FilesInfo = 0x05, + PackInfo = 0x06, + UnPackInfo = 0x07, + SubStreamsInfo = 0x08, + Size = 0x09, + CRC = 0x0A, + Folder = 0x0B, + CodersUnPackSize = 0x0C, + NumUnPackStream = 0x0D, + EmptyStream = 0x0E, + EmptyFile = 0x0F, + Anti = 0x10, + Name = 0x11, + MTime = 0x14, + WinAttributes = 0x15, + EncodedHeader = 0x17, + Dummy = 0x19, +} +Header.K = K + +local Fail = {} + +local function bad(r: Bytes.Reader, msg: string, code: string?): never + error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) +end + +local function check(r: Bytes.Reader) + if r.err then + error(setmetatable({ err = r.err }, Fail), 0) + end +end + +local function byte(r: Bytes.Reader): number + local v = r:u8() + check(r) + return v +end + +-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes +local function number(r: Bytes.Reader): number + local first = byte(r) + local mask = 0x80 + local value = 0 + for i = 0, 7 do + if bit32.band(first, mask) == 0 then + local high = bit32.band(first, mask - 1) + return value + high * 2 ^ (8 * i) + end + value += byte(r) * 2 ^ (8 * i) + mask = bit32.rshift(mask, 1) + end + return value +end + +-- a count bounded by the bytes left (every counted item takes at least `min` bytes) +local function count(r: Bytes.Reader, min: number?): number + local n = number(r) + if n * (min or 1) > r:remaining() + 1 then + bad(r, "count " .. n .. " is larger than the header") + end + return n +end + +local function bits(r: Bytes.Reader, n: number): { boolean } + local out = table.create(n, false) + local cur, mask = 0, 0 + for i = 1, n do + if mask == 0 then + cur = byte(r) + mask = 0x80 + end + out[i] = bit32.band(cur, mask) ~= 0 + mask = bit32.rshift(mask, 1) + end + return out +end + +-- bits preceded by an "all defined" byte +local function defined(r: Bytes.Reader, n: number): { boolean } + if byte(r) ~= 0 then + return table.create(n, true) + end + return bits(r, n) +end + +local function digests(r: Bytes.Reader, n: number): { [number]: number } + local def = defined(r, n) + local out = {} + for i = 1, n do + if def[i] then + out[i] = r:u32le() + end + end + check(r) + return out +end + +local function packInfo(r: Bytes.Reader, s: Streams) + s.packPos = number(r) + local n = count(r) + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.Size then + for i = 1, n do + s.packSizes[i] = number(r) + end + elseif t == K.CRC then + digests(r, n) + else + bad(r, "unexpected property " .. t .. " in pack info") + end + end + if #s.packSizes ~= n then + bad(r, "missing pack sizes") + end +end + +local function folder(r: Bytes.Reader): Folder + local ncoders = count(r) + if ncoders == 0 or ncoders > 64 then + bad(r, "bad coder count " .. ncoders) + end + local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 } + local totalIn, totalOut = 0, 0 + for _ = 1, ncoders do + local flags = byte(r) + if bit32.band(flags, 0x80) ~= 0 then + bad(r, "alternative coder methods", Err.UNSUPPORTED) + end + local idSize = bit32.band(flags, 0x0F) + local id = r:string(idSize) + check(r) + local nin, nout = 1, 1 + if bit32.band(flags, 0x10) ~= 0 then + nin, nout = number(r), number(r) + if nin > 64 or nout > 64 then + bad(r, "bad coder stream count") + end + end + local props = buffer.create(0) + if bit32.band(flags, 0x20) ~= 0 then + local n = count(r) + props = r:bytes(n) + check(r) + end + table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props }) + totalIn += nin + totalOut += nout + end + if totalOut == 0 then + bad(r, "a folder without output") + end + for _ = 1, totalOut - 1 do + local i, o = number(r), number(r) + table.insert(f.bindPairs, { inIndex = i, outIndex = o }) + end + local npacked = totalIn - (totalOut - 1) + if npacked < 1 then + bad(r, "bad bind pairs") + end + if npacked == 1 then + for i = 0, totalIn - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.inIndex == i then + bound = true + end + end + if not bound then + table.insert(f.packed, i) + break + end + end + if #f.packed ~= 1 then + bad(r, "no packed stream") + end + else + for _ = 1, npacked do + table.insert(f.packed, number(r)) + end + end + return f +end + +-- the folder's main out stream: the one no bind pair consumes +function Header.mainOut(f: Folder): number? + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for o = 0, total - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.outIndex == o then + bound = true + end + end + if not bound then + return o + end + end + return nil +end + +function Header.unpackSize(f: Folder): number + local m = Header.mainOut(f) + return if m then f.unpackSizes[m + 1] or 0 else 0 +end + +local function unpackInfo(r: Bytes.Reader, s: Streams) + if byte(r) ~= K.Folder then + bad(r, "expected the folder list") + end + local n = count(r) + if byte(r) ~= 0 then + bad(r, "external folders", Err.UNSUPPORTED) + end + for i = 1, n do + s.folders[i] = folder(r) + end + if byte(r) ~= K.CodersUnPackSize then + bad(r, "expected the coder unpack sizes") + end + for _, f in s.folders do + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for k = 1, total do + f.unpackSizes[k] = number(r) + end + end + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.CRC then + local d = digests(r, n) + for i = 1, n do + s.folders[i].crc = d[i] + end + else + bad(r, "unexpected property " .. t .. " in unpack info") + end + end +end + +local function subStreamsInfo(r: Bytes.Reader, s: Streams) + local t = byte(r) + if t == K.NumUnPackStream then + for _, f in s.folders do + f.numSub = count(r, 0) + end + t = byte(r) + end + local sizes = s.subSizes + if t == K.Size then + for _, f in s.folders do + if f.numSub > 0 then + local sum = 0 + for _ = 1, f.numSub - 1 do + local v = number(r) + sum += v + table.insert(sizes, v) + end + local total = Header.unpackSize(f) + if sum > total then + bad(r, "substream sizes exceed the folder") + end + table.insert(sizes, total - sum) + end + end + t = byte(r) + else + for _, f in s.folders do + if f.numSub > 1 then + bad(r, "missing substream sizes") + elseif f.numSub == 1 then + table.insert(sizes, Header.unpackSize(f)) + end + end + end + -- CRCs for the streams whose folder CRC does not already cover them + local unknown = 0 + for _, f in s.folders do + if not (f.numSub == 1 and f.crc) then + unknown += f.numSub + end + end + while t ~= K.End do + if t == K.CRC then + local d = digests(r, unknown) + local k, si = 1, 1 + for _, f in s.folders do + if f.numSub == 1 and f.crc then + s.subCrcs[si] = f.crc + si += 1 + else + for _ = 1, f.numSub do + s.subCrcs[si] = d[k] + k += 1 + si += 1 + end + end + end + else + bad(r, "unexpected property " .. t .. " in substreams info") + end + t = byte(r) + end +end + +local function streamsInfo(r: Bytes.Reader): Streams + local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + local sawSub = false + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.PackInfo then + packInfo(r, s) + elseif t == K.UnPackInfo then + unpackInfo(r, s) + elseif t == K.SubStreamsInfo then + subStreamsInfo(r, s) + sawSub = true + else + bad(r, "unexpected property " .. t .. " in streams info") + end + end + if not sawSub then + for i, f in s.folders do + f.numSub = 1 + table.insert(s.subSizes, Header.unpackSize(f)) + if f.crc then + s.subCrcs[i] = f.crc + end + end + end + local p = 0 + for _, f in s.folders do + f.firstPack = p + p += #f.packed + end + if p > #s.packSizes then + bad(r, "folders use more pack streams than exist") + end + return s +end + +local function utf16(b: buffer, o: number, n: number): string + local out = {} + local i = 0 + while i + 1 < n do + local u = buffer.readu16(b, o + i) + i += 2 + if u >= 0xD800 and u < 0xDC00 and i + 1 < n then + local lo = buffer.readu16(b, o + i) + if lo >= 0xDC00 and lo < 0xE000 then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + i += 2 + end + end + table.insert(out, utf8.char(u)) + end + return table.concat(out) +end + +local function filesInfo(r: Bytes.Reader): { File } + local n = count(r, 0) + if n > 1000000 then + bad(r, "too many files", Err.LIMIT) + end + local files: { File } = table.create(n) + for i = 1, n do + files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } + end + local empties = {} + while true do + local t = byte(r) + if t == K.End then + break + end + local size = number(r) + if size > r:remaining() then + bad(r, "file property past the header") + end + local pr = r:slice(size) + check(r) + if t == K.EmptyStream then + local v = bits(pr, n) + empties = {} + for i = 1, n do + files[i].emptyStream = v[i] + if v[i] then + table.insert(empties, i) + end + end + elseif t == K.EmptyFile or t == K.Anti then + local v = bits(pr, #empties) + for k, i in empties do + if t == K.EmptyFile then + files[i].emptyFile = v[k] + else + files[i].anti = v[k] + end + end + elseif t == K.Name then + if byte(pr) ~= 0 then + bad(pr, "external names", Err.UNSUPPORTED) + end + local b = pr.buf + local p = pr.pos + for i = 1, n do + local q = p + while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do + q += 2 + end + if q + 1 >= pr.limit then + bad(pr, "unterminated name") + end + files[i].name = utf16(b, p, q - p) + p = q + 2 + end + elseif t == K.MTime or t == K.WinAttributes then + local def = defined(pr, n) + if byte(pr) ~= 0 then + bad(pr, "external file properties", Err.UNSUPPORTED) + end + for i = 1, n do + if def[i] then + if t == K.MTime then + local ft = pr:u64le() + files[i].mtime = math.floor(ft / 1e7 - 11644473600) + else + files[i].attributes = pr:u32le() + end + end + end + check(pr) + end + -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped + end + return files +end + +local function header(r: Bytes.Reader): Parsed + local p: Parsed = { streams = nil, files = {}, encoded = nil } + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.ArchiveProperties then + while true do + local pt = byte(r) + if pt == 0 then + break + end + r:skip(number(r)) + check(r) + end + elseif t == K.AdditionalStreamsInfo then + streamsInfo(r) + elseif t == K.MainStreamsInfo then + p.streams = streamsInfo(r) + elseif t == K.FilesInfo then + p.files = filesInfo(r) + else + bad(r, "unexpected property " .. t .. " in the header") + end + end + return p +end + +-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to +-- decode and parse again. +function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) + local r = Bytes.reader(b, o, n) + local ok, res = pcall(function(): Parsed + local t = byte(r) + if t == K.Header then + return header(r) + elseif t == K.EncodedHeader then + return { streams = nil, files = {}, encoded = streamsInfo(r) } + end + return bad(r, "bad header type " .. t) + end) + if ok then + return res, nil + end + if type(res) == "table" and getmetatable(res :: any) == Fail then + return nil, (res :: any).err + end + error(res, 0) +end + +return Header diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau new file mode 100644 index 0000000..39097fd --- /dev/null +++ b/src/Formats/archive/7z/init.luau @@ -0,0 +1,387 @@ +--!strict +-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose +-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) +-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 / +-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM, +-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, +-- Windows / Unix attributes, folder and file CRC-32s (verified on read). +-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other +-- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Types = require("@formats/Types") +local Lzma = require("@formats/codecs/Lzma") +local Deflate = require("@formats/codecs/Deflate") +local Bzip2 = require("@formats/codecs/Bzip2") +local Zstd = require("@formats/codecs/Zstd") +local Archive = require("@formats/containers/Archive") +local Header = require("@formats/archive/7z/Header") + +-- ------------------------------------------------------------------------------------------------ contract +local SevenZip = { + name = "7z", + category = "archive", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30) + checkCrc: boolean?, -- verify CRC-32s on read (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "7z\188\175\39\28" + +-- method id -> xz filter id (BCJ / delta) +local FILTERS: { [string]: number } = { + ["\3\3\1\3"] = 0x04, -- x86 + ["\3\3\2\5"] = 0x05, -- PowerPC + ["\3\3\5\1"] = 0x07, -- ARM + ["\3\3\7\1"] = 0x08, -- ARM-Thumb + ["\3\3\8\5"] = 0x09, -- SPARC + ["\10"] = 0x0A, -- ARM64 + ["\3"] = 0x03, -- delta +} +local NAMES: { [string]: string } = { + ["\0"] = "copy", + ["\3\1\1"] = "lzma", + ["\33"] = "lzma2", + ["\4\1\8"] = "deflate", + ["\4\1\9"] = "deflate64", + ["\4\2\2"] = "bzip2", + ["\3\4\1"] = "ppmd", + ["\3\3\1\27"] = "bcj2", + ["\6\241\7\1"] = "aes", + ["\4\247\17\1"] = "zstd", + ["\4\247\17\2"] = "brotli", + ["\3\3\1\3"] = "bcj", + ["\3\3\2\5"] = "ppc", + ["\3\3\5\1"] = "arm", + ["\3\3\7\1"] = "armt", + ["\3\3\8\5"] = "sparc", + ["\10"] = "arm64", + ["\3"] = "delta", +} + +local function methodName(id: string): string + local n = NAMES[id] + if n then + return n + end + local hex = {} + for i = 1, #id do + table.insert(hex, string.format("%02x", string.byte(id, i))) + end + return "method " .. table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function SevenZip.sniff(r: Bytes.Reader): number + return if r:peek(6) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream +type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number } + +local function packStart(ctx: Ctx, s: Header.Streams, index: number): number + local p = ctx.base + 32 + s.packPos + for i = 1, index do + p += s.packSizes[i] + end + return p +end + +local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) + -- coder -> first in / out stream index + local inBase, outBase = {}, {} + local ni, no = 0, 0 + for i, c in f.coders do + inBase[i], outBase[i] = ni, no + ni += c.numIn + no += c.numOut + end + local depth = 0 + local function out(outIdx: number): (buffer?, Err.Err?) + depth += 1 + if depth > 32 then + return nil, Err.new(Err.CORRUPT, "coder graph too deep") + end + local ci + for i, c in f.coders do + if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then + ci = i + end + end + if not ci then + return nil, Err.new(Err.CORRUPT, "bad bind pair") + end + local c = f.coders[ci] + if c.numIn ~= 1 or c.numOut ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)") + end + local size = f.unpackSizes[outIdx + 1] or 0 + if size > ctx.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) + end + -- the coder's input: another coder's output, or a packed stream + local inIdx = inBase[ci] + local src: buffer, so: number, sl: number + local bound = nil + for _, bp in f.bindPairs do + if bp.inIndex == inIdx then + bound = bp.outIndex + end + end + if bound then + local b, e = out(bound) + if not b then + return nil, e + end + src, so, sl = b, 0, buffer.len(b) + else + local k = table.find(f.packed, inIdx) + if not k then + return nil, Err.new(Err.CORRUPT, "unbound coder input") + end + local pi = f.firstPack + k - 1 + if pi >= #s.packSizes then + return nil, Err.new(Err.CORRUPT, "missing pack stream") + end + so = packStart(ctx, s, pi) + sl = s.packSizes[pi + 1] + if so + sl > ctx.limit or so < ctx.base then + return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so) + end + src = ctx.buf + end + local id = c.id + local opts = { maxBytes = ctx.maxBytes } + if id == "\0" then + if sl < size then + return nil, Err.new(Err.TRUNCATED, "short stored stream") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + return b + elseif id == "\3\1\1" then + if buffer.len(c.props) < 5 then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties") + end + local b, e = Lzma.lzma(src, so, sl, c.props, size, opts) + return b, if b then nil else e + elseif id == "\33" then + local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) + return b, if b then nil else e + elseif id == "\4\1\8" then + local b, e = Deflate.inflate(src, so, sl, size) + return b, if b then nil else e + elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames) + local b, e + if id == "\4\2\2" then + b, e = Bzip2.decompress(src, so, sl, opts) + else + b, e = Zstd.decompress(src, so, sl, opts) + end + if not b then + return nil, e + end + if buffer.len(b) ~= size then + return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") + end + return b + elseif FILTERS[id] then + if sl ~= size then + return nil, Err.new(Err.CORRUPT, "filter size mismatch") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props) + if not ok then + return nil, e + end + return b + end + return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") + end + local main = Header.mainOut(f) + if not main then + return nil, Err.new(Err.CORRUPT, "folder without a main output") + end + return out(main) +end + +local function folderMethod(f: Header.Folder): string + local names = {} + for _, c in f.coders do + table.insert(names, methodName(c.id)) + end + return table.concat(names, "+") +end + +function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local o = opts or {} + local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30 + local checkCrc = o.checkCrc ~= false + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "truncated signature header", base) + end + if buffer.readstring(b, base, 6) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad 7z signature", base) + end + if buffer.readu8(b, base + 6) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6) + end + if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then + return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8) + end + local hr = Bytes.reader(b, base + 12, 20) + local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le() + local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes } + local a = Archive.new("7z") + if nextSize == 0 then + return a, nil -- an empty archive + end + local ho = base + 32 + nextOff + if nextOff < 0 or ho + nextSize > limit then + return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12) + end + if Crc32.raw(b, ho, nextSize) ~= nextCrc then + return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho) + end + local hbuf, hoff, hlen = b, ho, nextSize + local parsed + for _ = 1, 4 do + local p, perr = Header.parse(hbuf, hoff, hlen) + if not p then + return nil, perr + end + if not p.encoded then + parsed = p + break + end + -- an encoded header: decode folder 1 of its streams, then parse again + local es = p.encoded + local f = es.folders[1] + if not f then + return nil, Err.new(Err.CORRUPT, "encoded header without a folder") + end + local hb, herr = decodeFolder(ctx, es, f) + if not hb then + return nil, herr + end + if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch") + end + hbuf, hoff, hlen = hb, 0, buffer.len(hb) + end + if not parsed then + return nil, Err.new(Err.CORRUPT, "nested encoded headers") + end + local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + a.meta.folders = #s.folders + a.meta.solid = false + -- folder caches and the substream -> folder map + local cache: { [number]: buffer } = {} + local subFolder, subOffset = {}, {} + do + local si = 1 + for fi, f in s.folders do + if f.numSub > 1 then + a.meta.solid = true + end + local off = 0 + for _ = 1, f.numSub do + subFolder[si], subOffset[si] = fi, off + off += s.subSizes[si] or 0 + si += 1 + end + if off > Header.unpackSize(f) then + return nil, Err.new(Err.CORRUPT, "substreams exceed their folder") + end + end + end + local function folderData(fi: number): (buffer?, Err.Err?) + local c = cache[fi] + if c then + return c + end + local f = s.folders[fi] + local d, e = decodeFolder(ctx, s, f) + if not d then + return nil, e + end + if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") + end + cache[fi] = d + return d + end + local si = 0 + for _, file in parsed.files do + if file.anti then + continue + end + local attr = file.attributes + local isDir = file.emptyStream and not file.emptyFile + if attr and bit32.band(attr, 0x10) ~= 0 then + isDir = true + end + local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil + local e: Archive.Entry = { + name = file.name, + size = 0, + dir = isDir, + mtime = file.mtime, + attributes = attr, + mode = mode, + } + if not file.emptyStream then + si += 1 + local idx = si + local fi = subFolder[idx] + if not fi then + return nil, Err.new(Err.CORRUPT, "more files than streams") + end + local size = s.subSizes[idx] + e.size = size + e.method = folderMethod(s.folders[fi]) + if s.folders[fi].numSub == 1 then + local pk = 0 + for k = 1, #s.folders[fi].packed do + pk += s.packSizes[s.folders[fi].firstPack + k] or 0 + end + e.compressedSize = pk + end + e.crc = s.subCrcs[idx] + e.load = function(): (buffer?, Err.Err?) + local d, derr = folderData(fi) + if not d then + return nil, derr + end + local off = subOffset[idx] + if off + size > buffer.len(d) then + return nil, Err.new(Err.CORRUPT, "substream past its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, d, off, size) + local want = s.subCrcs[idx] + if checkCrc and want and Crc32.raw(out, 0, size) ~= want then + return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name) + end + return out + end + end + Archive.put(a, e) + end + return a, nil +end + +return SevenZip diff --git a/src/Formats/archive/br/init.luau b/src/Formats/archive/br/init.luau new file mode 100644 index 0000000..6949a02 --- /dev/null +++ b/src/Formats/archive/br/init.luau @@ -0,0 +1,76 @@ +--!strict +-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar +-- inside). Decoding through codecs/Brotli. The entry is named after opts.name without ".br" (else "data"). +-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number: +-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a +-- low confidence, so the extension decides between candidates. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Brotli = require("@formats/codecs/Brotli") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Br = { + name = "br", + category = "archive", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +export type DecodeOptions = { + name: string?, -- the file name (the api passes it): the entry is named after it + maxBytes: number?, -- refuse output larger than this (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff +local SNIFF_PREFIX = 65536 + +-- ------------------------------------------------------------------------------------------------ sniff +function Br.sniff(r: Bytes.Reader): number + local n = r:remaining() + if n == 0 then + return 0 + end + if n <= SNIFF_WHOLE then + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 }) + if out and consumed == r.limit then + return if buffer.len(out) > 0 then 0.3 else 0.05 + end + return 0 + end + local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 }) + if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then + return 0.05 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local n = r:remaining() + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes }) + if not out then + local e: Err.Err = consumed + e.message = string.gsub(e.message, "^brotli: ", "") + return nil, e + end + local a = Archive.new("br") + a.meta.stream = true + a.meta.compressedSize = consumed - r.pos + Archive.put(a, { + name = Archive.streamName(opts, Br.extensions), + size = buffer.len(out), + compressedSize = consumed - r.pos, + method = "brotli", + dir = false, + data = out, + }) + return a, nil +end + +return Br diff --git a/src/Formats/archive/bz2/init.luau b/src/Formats/archive/bz2/init.luau new file mode 100644 index 0000000..7483ab0 --- /dev/null +++ b/src/Formats/archive/bz2/init.luau @@ -0,0 +1,63 @@ +--!strict +-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated +-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), +-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). Read only. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local Bzip2 = require("@formats/codecs/Bzip2") + +-- ------------------------------------------------------------------------------------------------ contract +local Bz2 = { + name = "bz2", + category = "archive", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger output (default 2^30) + name: string?, -- the file name (the api passes it): names the entry +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bz2.sniff(r: Bytes.Reader): number + local h = r:peek(10) + if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then + return 0 + end + local lv = string.byte(h, 4) + if lv < 0x31 or lv > 0x39 then + return 0 + end + local magic = string.sub(h, 5, 10) + if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) + if not out then + return nil, consumed + end + local a = Archive.new("bz2") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(opts, Bz2.extensions), + size = buffer.len(out), + compressedSize = consumed - r.base, + method = "bzip2", + dir = false, + data = out, + }) + return a, nil +end + +return Bz2 diff --git a/src/Formats/archive/gzip/init.luau b/src/Formats/archive/gzip/init.luau new file mode 100644 index 0000000..38ddeca --- /dev/null +++ b/src/Formats/archive/gzip/init.luau @@ -0,0 +1,187 @@ +--!strict +-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the +-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d +-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive +-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the +-- inner tar, meta.compression = "gzip"). Deflate is codecs/Deflate. Not supported: FHCRC verification. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/Deflate") +local Archive = require("@formats/containers/Archive") +local Tar = require("@formats/containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Gzip = { + name = "gzip", + category = "archive", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, +} + +export type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME +export type EncodeOptions = { + level: number?, -- 0..9, default 6 + name: string?, -- FNAME (default: the entry's name; none for a buffer) + mtime: number?, -- MTIME (default: the entry's mtime, else 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Gzip.sniff(r: Bytes.Reader): number + return if r:peek(3) == "\31\139\8" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent) +local function header(b: buffer, o: number, e: number): { [string]: any } + local h: { [string]: any } = {} + if o + 10 > e then + return h + end + local flg = buffer.readu8(b, o + 3) + h.mtime = buffer.readu32(b, o + 4) + h.os = buffer.readu8(b, o + 9) + local q = o + 10 + if bit32.band(flg, 4) ~= 0 and q + 2 <= e then + q += 2 + buffer.readu16(b, q) + end + for _, f in { { 8, "name" }, { 16, "comment" } } do + if bit32.band(flg, f[1]) ~= 0 then + local s = q + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + if q < e then + h[f[2]] = buffer.readstring(b, s, q - s) + end + q += 1 + end + end + return h +end + +function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base) + if not out then + return nil, err + end + local h = header(r.buf, r.base, r.limit) + local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) + return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip", os = h.os } + a.meta.comment = h.comment + local name = h.name + if not name or name == "" or string.find(name, "[/\\]") then + name = Archive.streamName(opts, Gzip.extensions) + end + Archive.put(a, { + name = name, + size = buffer.len(out), + compressedSize = r.limit - r.base, + method = "deflate", + mtime = if h.mtime and h.mtime > 0 then h.mtime else nil, + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o = opts or {} + local level = if o.level == nil then 6 else o.level + if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then + return nil, Err.new(Err.ARG, "level must be 0..9") + end + local data: buffer + local name: string? = o.name + local mtime: number = o.mtime or 0 + if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + else + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local files = {} + for _, it in items do + if not it.entry.dir then + table.insert(files, it) + end + end + if #files == 1 and #items == 1 then + local b, err = files[1].read() + if not b then + return nil, err + end + data = b + name = name or files[1].entry.name + mtime = o.mtime or files[1].entry.mtime or 0 + else + -- several entries: a tar inside + local list = {} + for _, it in items do + local e: any = it.entry + local b = nil + if not e.dir then + local rb, err = it.read() + if not rb then + return nil, err + end + b = rb + end + table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode }) + end + local t, terr = Tar.write(list) + if not t then + return nil, terr + end + data = t + end + end + if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then + mtime = 0 + end + local raw, cerr = Deflate.compress(data, { level = level }) + if not raw then + return nil, cerr + end + local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0)) + w:string("\31\139\8") + w:u8(if name then 8 else 0) + w:u32le(math.floor(mtime)) + w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0) + w:u8(255) + if name then + local z = string.find(name, "\0", 1, true) + w:cstring(if z then string.sub(name, 1, z - 1) else name) + end + w:bytes(raw) + w:u32le(Crc32.raw(data, 0, buffer.len(data))) + w:u32le(buffer.len(data) % 4294967296) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz) +function Gzip.new(data: (buffer | string)?, name: string?): any + local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) + return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip" } + if data then + a:add(name or "data", data) + end + return a +end + +return Gzip diff --git a/src/Formats/archive/tar/init.luau b/src/Formats/archive/tar/init.luau new file mode 100644 index 0000000..ea1e304 --- /dev/null +++ b/src/Formats/archive/tar/init.luau @@ -0,0 +1,120 @@ +--!strict +-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value +-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() + +-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which +-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format). +-- Not supported: sparse files, multi-volume archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local Tar = require("@formats/containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local TarFormat = { + name = "tar", + category = "archive", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, +} + +export type DecodeOptions = { maxEntries: number? } -- default 1e6 +export type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed + +-- ------------------------------------------------------------------------------------------------ sniff +function TarFormat.sniff(r: Bytes.Reader): number + if r:remaining() < 512 then + return 0 + end + if not Tar.valid(r.buf, r.pos) then + return 0 + end + return if r:peek(5, 257) == "ustar" then 0.95 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return TarFormat.encode(archive, opts) +end + +function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, err + end + local a = Archive.new("tar", encode) + for _, e in list do + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + mode = e.mode, + uid = e.uid, + gid = e.gid, + uname = e.uname, + gname = e.gname, + type = e.type, + link = e.link, + method = "store", + load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size), + }) + end + a.meta.source = { format = "tar" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local list: { Tar.WriteEntry } = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir and e.type ~= "1" and e.type ~= "2" then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(list, { + name = e.name, + data = data, + dir = e.dir, + type = if type(e.type) == "string" and #e.type == 1 then e.type else nil, + link = if type(e.link) == "string" then e.link else nil, + mode = if type(e.mode) == "number" then e.mode else nil, + uid = if type(e.uid) == "number" then e.uid else nil, + gid = if type(e.gid) == "number" then e.gid else nil, + uname = if type(e.uname) == "string" then e.uname else nil, + gname = if type(e.gname) == "string" then e.gname else nil, + mtime = if type(e.mtime) == "number" then e.mtime else nil, + }) + end + return Tar.write(list, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write() +function TarFormat.new(): any + local a = Archive.new("tar", encode) + a.meta.source = { format = "tar" } + return a +end + +return TarFormat diff --git a/src/Formats/archive/xz/init.luau b/src/Formats/archive/xz/init.luau new file mode 100644 index 0000000..9225302 --- /dev/null +++ b/src/Formats/archive/xz/init.luau @@ -0,0 +1,101 @@ +--!strict +-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one +-- entry (the decompressed data). Built on codecs/Lzma. Supports: concatenated streams, stream padding, every block +-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters +-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters. +-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true: +-- the api unwraps an inner archive (a .tar.xz loads as the tar). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Lzma = require("@formats/codecs/Lzma") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Xz = { + name = "xz", + category = "archive", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + name: string?, -- the file name (the api passes it): names the entry +} + +-- ------------------------------------------------------------------------------------------------ constants +local XZ_MAGIC = "\253" .. "7zXZ\0" + +-- ------------------------------------------------------------------------------------------------ sniff +-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1), +-- a size of -1 or under 2^40, and a 0 range coder byte +local function aloneScore(r: Bytes.Reader): number + local h = r:peek(14) + if #h < 14 then + return 0 + end + local d = string.byte(h, 1) + if d >= 225 or string.byte(h, 14) ~= 0 then + return 0 + end + local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216 + local okDict = false + for n = 12, 31 do + if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then + okDict = true + break + end + end + if not okDict then + return 0 + end + local s = string.sub(h, 6, 13) + if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then + return 0 + end + return if d == 0x5D then 0.4 else 0.2 +end + +function Xz.sniff(r: Bytes.Reader): number + if r:peek(6) == XZ_MAGIC then + return 1 + end + return aloneScore(r) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local o = opts or {} + local n = r.limit - r.base + local out, res + local method + if r:peek(6) == XZ_MAGIC then + out, res = Lzma.xz(r.buf, r.base, n, o) + method = "lzma2" + else + out, res = Lzma.alone(r.buf, r.base, n, o) + method = "lzma" + end + if not out then + return nil, res + end + local a = Archive.new("xz") + a.meta.stream = true + a.meta.container = if method == "lzma" then "lzma" else "xz" + Archive.put(a, { + name = Archive.streamName(o, Xz.extensions), + size = buffer.len(out), + compressedSize = n, + method = method, + dir = false, + data = out, + }) + return a, nil +end + +return Xz diff --git a/src/Formats/archive/zst/init.luau b/src/Formats/archive/zst/init.luau new file mode 100644 index 0000000..af5eef6 --- /dev/null +++ b/src/Formats/archive/zst/init.luau @@ -0,0 +1,63 @@ +--!strict +-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded +-- through codecs/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else +-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only. +-- Not supported: dictionaries, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Zstd = require("@formats/codecs/Zstd") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zst = { + name = "zst", + category = "archive", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a decompressed size over this (default 2^30) + verify: boolean?, -- check the content checksum (default true) + name: string?, -- the file name, for the entry name (the api passes it) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Zst.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == Zstd.MAGIC then + return 1 + end + -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame + if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local len = r.limit - r.base + local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify }) + if not out then + return nil, err + end + local a = Archive.new("zst") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(o, Zst.extensions), + size = buffer.len(out), + compressedSize = len, + method = "zstd", + dir = false, + data = out, + }) + return a, nil +end + +return Zst diff --git a/src/Formats/codecs/Brotli/Decode.luau b/src/Formats/codecs/Brotli/Decode.luau new file mode 100644 index 0000000..e17e7d8 --- /dev/null +++ b/src/Formats/codecs/Brotli/Decode.luau @@ -0,0 +1,996 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the +-- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet +-- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed, +-- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse +-- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and +-- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words. +-- +-- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next +-- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits. +-- +-- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each +-- meta-block before it is decoded); bad data returns nil, message. +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill + +local Decode = {} + +export type Static = { + dictionary: buffer, -- 122784 bytes + context: buffer, -- 2048 bytes: 4 modes x (256 for p1, 256 for p2) + prefixSuffix: buffer, -- length-prefixed strings + prefixSuffixMap: { number }, + transforms: { number }, -- 121 x (prefix id, type, suffix id) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 } +local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 } +local BL_OFF = { + 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625, +} +local BL_BITS = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24 } +local INS_BASE = { 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594 } +local INS_EXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24 } +local CPY_BASE = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118 } +local CPY_EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24 } +local CELL_INS = { 0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16 } +local CELL_CPY = { 0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16 } +-- static dictionary: bits of the word index per word length 0..24 (index + 1), and the offsets +local NDBITS = { 0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5 } +local DOFF = table.create(25, 0) +do + local o = 0 + for l = 4, 24 do + DOFF[l + 1] = o + o += l * 2 ^ NDBITS[l + 1] + end +end +local NTRANSFORMS = 121 +local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC + +-- 8-bit reversal +local REV8 = bcreate(256) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = v // 2 + end + writeu8(REV8, i, r) +end +local function reverse(code: number, len: number): number + -- len <= 15 + local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) + return rshift(r, 16 - len) +end + +-- ------------------------------------------------------------------------------------------------ prefix tables +local count = table.create(16, 0) +local nextc = table.create(16, 0) +local subBits = table.create(256, 0) +local subOff = table.create(256, 0) + +-- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set. +-- Also leaves count / nextc / subBits ready for build(). +local function prepare(lens: buffer, n: number): number + for l = 1, 16 do + count[l] = 0 + end + local used = 0 + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + count[l] += 1 + used += 1 + end + end + if used <= 1 then + return 256 + end + local left = 1 + for l = 1, 15 do + left = left * 2 - count[l] + if left < 0 then + return -1 + end + end + -- canonical codes: the first code of length l is (first(l - 1) + count(l - 1)) * 2 + local code = 0 + for l = 1, 15 do + nextc[l] = code + code = (code + count[l]) * 2 + end + for i = 1, 256 do + subBits[i] = 0 + end + local nc = table.clone(nextc) + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 8 then + local c = nc[l] + nc[l] = c + 1 + local pre = band(reverse(c, l), 255) + local k = l - 8 + if k > subBits[pre + 1] then + subBits[pre + 1] = k + end + elseif l > 0 then + nc[l] += 1 + end + end + local size = 256 + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + subOff[i] = size + size += lshift(1, k) + end + end + return size +end + +-- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room) +local function build(lens: buffer, n: number, T: buffer, at: number) + local single = -1 + local used = 0 + for s = 0, n - 1 do + if readu8(lens, s) > 0 then + used += 1 + single = s + end + end + if used <= 1 then + local e = (if single < 0 then 0 else single) * 32 + for i = 0, 255 do + writeu32(T, (at + i) * 4, e) + end + return + end + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + writeu32(T, (at + i - 1) * 4, subOff[i] * 32 + 16 + k) + end + end + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local rev = reverse(c, l) + local e = s * 32 + l + if l <= 8 then + local step = lshift(1, l) + local i = rev + while i < 256 do + writeu32(T, (at + i) * 4, e) + i += step + end + else + local pre = band(rev, 255) + local sb = subBits[pre + 1] + local base = at + subOff[pre + 1] + local step = lshift(1, l - 8) + local i = rshift(rev, 8) + local lim = lshift(1, sb) + while i < lim do + writeu32(T, (base + i) * 4, e) + i += step + end + end + end + end +end + +-- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference +-- decoder's BrotliCalculateDistanceCodeLimit +local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number + if maxDistance <= ndirect then + return maxDistance + 16 + end + local offset = maxDistance + 1 - ndirect - 1 + offset = rshift(offset, npostfix) + 4 + local ndistbits = 0 + local tmp = offset // 2 + while tmp ~= 0 do + ndistbits += 1 + tmp = rshift(tmp, 1) + end + ndistbits -= 1 + local half = band(rshift(offset, ndistbits), 1) + local group = bor(lshift(ndistbits - 1, 1), half) + if group == 0 then + return ndirect + 16 + end + group -= 1 + local postfix = lshift(1, npostfix) - 1 + return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 +end + +-- ------------------------------------------------------------------------------------------------ decoder +-- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message +function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) + local lim = off + len + local ip = off + local bb, bc = 0, 0 + + local function fill() + while bc <= 24 do + local byte = 0 + if ip < lim then + byte = readu8(src, ip) + end + ip += 1 + bb = bor(bb, lshift(byte, bc)) + bc += 8 + end + end + local function bits(n: number): number + if bc < n then + fill() + end + local v = band(bb, lshift(1, n) - 1) + bb = rshift(bb, n) + bc -= n + return v + end + local function bitsLong(n: number): number + if n <= 24 then + return bits(n) + end + local lo = bits(16) + return lo + bits(n - 16) * 65536 + end + local function overrun(): boolean + return (ip - lim) * 8 > bc + end + + -- prefix tables of the current meta-block: T (u32 entries), tpos entries used + local T = bcreate(4096 * 4) + local tpos = 0 + local LENS = bcreate(1128) + local CLL = bcreate(18) + local CLT = bcreate(256 * 4) + + local function decodeSym(base: number): number + if bc < 15 then + fill() + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc -= l + return rshift(e, 5) + end + + -- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1 + local function install(n: number): number + local size = prepare(LENS, n) + if size < 0 then + return -1 + end + local need = (tpos + size) * 4 + if need > blen(T) then + local nt = bcreate(math.max(blen(T) * 2, need)) + bcopy(nt, 0, T, 0, tpos * 4) + T = nt + end + build(LENS, n, T, tpos) + local base = tpos + tpos += size + return base + end + + -- readCode(alphabetMax, limit) -> table base | -1 (corrupt) + local function readCode(alphabetMax: number, limit: number): number + bfill(LENS, 0, 0, limit) + local hskip = bits(2) + if hskip == 1 then + local nsym = bits(2) + 1 + local maxBits = 0 + local x = alphabetMax - 1 + while x > 0 do + maxBits += 1 + x = rshift(x, 1) + end + local s1, s2, s3, s4 = -1, -1, -1, -1 + for i = 1, nsym do + local v = bits(maxBits) + if v >= limit then + return -1 + end + if i == 1 then + s1 = v + elseif i == 2 then + s2 = v + elseif i == 3 then + s3 = v + else + s4 = v + end + end + if nsym >= 2 and (s1 == s2 or s1 == s3 or s1 == s4 or (nsym >= 3 and (s2 == s3 or s2 == s4)) or (nsym == 4 and s3 == s4)) then + return -1 + end + if nsym == 1 then + writeu8(LENS, s1, 1) + elseif nsym == 2 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 1) + elseif nsym == 3 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + else + if bits(1) == 0 then + writeu8(LENS, s1, 2) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + writeu8(LENS, s4, 2) + else + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 3) + writeu8(LENS, s4, 3) + end + end + return install(limit) + end + -- complex: the code length code + bfill(CLL, 0, 0, 18) + local space, num = 32, 0 + for i = hskip + 1, 18 do + if bc < 4 then + fill() + end + local ix = band(bb, 15) + local v = CLP_VAL[ix + 1] + local dl = CLP_LEN[ix + 1] + bb = rshift(bb, dl) + bc -= dl + writeu8(CLL, CL_ORDER[i], v) + if v ~= 0 then + space -= rshift(32, v) + num += 1 + if space <= 0 then + break + end + end + end + if not (num == 1 or space == 0) then + return -1 + end + -- its table (lengths <= 5) + do + local size = prepare(CLL, 18) + if size ~= 256 then + return -1 + end + build(CLL, 18, CLT, 0) + end + -- the symbol code lengths + local sym, prev, rep, repLen = 0, 8, 0, 0 + space = 32768 + while sym < limit and space > 0 do + if bc < 15 then + fill() + end + local e = readu32(CLT, band(bb, 255) * 4) + local l = band(e, 31) + bb = rshift(bb, l) + bc -= l + local cl = rshift(e, 5) + if cl < 16 then + rep = 0 + writeu8(LENS, sym, cl) + if cl ~= 0 then + prev = cl + space -= rshift(32768, cl) + end + sym += 1 + else + local extra = if cl == 16 then 2 else 3 + local d = bits(extra) + local newLen = if cl == 16 then prev else 0 + if repLen ~= newLen then + rep = 0 + repLen = newLen + end + local old = rep + if rep > 0 then + rep = (rep - 2) * lshift(1, extra) + end + rep += d + 3 + local delta = rep - old + if sym + delta > limit then + return -1 + end + if repLen ~= 0 then + bfill(LENS, sym, repLen, delta) + space -= delta * rshift(32768, repLen) + end + sym += delta + end + if overrun() then + return -1 + end + end + if space ~= 0 then + return -1 + end + return install(limit) + end + + local function varLen8(): number + if bits(1) == 0 then + return 0 + end + local n = bits(3) + if n == 0 then + return 1 + end + return bits(n) + lshift(1, n) + end + + local function blockLen(base: number): number + local code = decodeSym(base) + return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) + end + + -- readContextMap(size) -> ntrees, map buffer | -1 + local function readContextMap(size: number): (number, buffer) + local ntrees = varLen8() + 1 + local map = bcreate(size) + if ntrees < 2 then + return ntrees, map + end + local rleMax = 0 + if bits(1) == 1 then + rleMax = bits(4) + 1 + end + local base = readCode(ntrees + rleMax, ntrees + rleMax) + if base < 0 then + return -1, map + end + local i = 0 + while i < size do + local code = decodeSym(base) + if code == 0 then + i += 1 + elseif code > rleMax then + writeu8(map, i, code - rleMax) + i += 1 + else + local reps = lshift(1, code) + bits(code) + if i + reps > size then + return -1, map + end + i += reps -- zeros (map is zero-filled) + end + if overrun() then + return -1, map + end + end + if bits(1) == 1 then -- inverse move-to-front + local mtf = table.create(256, 0) + for k = 1, 256 do + mtf[k] = k - 1 + end + for k = 0, size - 1 do + local idx = readu8(map, k) + local v = mtf[idx + 1] + writeu8(map, k, v) + if idx > 0 then + table.move(mtf, 1, idx, 2) + mtf[1] = v + end + end + end + return ntrees, map + end + + -- ------------------------------------------------------------------ stream header + fill() + local wbits + local large = false + if bits(1) == 0 then + wbits = 16 + else + local n = bits(3) + if n ~= 0 then + wbits = 17 + n + else + local m = bits(3) + if m == 1 then + if not largeWindow then + return nil, "unsupported: large-window brotli (pass opts.largeWindow = true)" + end + if bits(1) == 1 then + return nil, "bad window bits" + end + large = true + wbits = bits(6) + if wbits < 10 or wbits > 30 then + return nil, "bad large window bits" + end + elseif m ~= 0 then + wbits = 8 + m + else + wbits = 17 + end + end + end + local maxBackward = 2 ^ wbits - 16 + + local dict = S.dictionary + local LUT = S.context + local PS = S.prefixSuffix + local PSMAP = S.prefixSuffixMap + local TRANS = S.transforms + local WORD = bcreate(64) + + local out = bcreate(math.max(256, math.min(len * 4, maxBytes))) + local op = 0 + -- distance ring buffer: last, second, third, fourth + local d0, d1, d2, d3 = 4, 11, 15, 16 + + while true do + -- ---------------------------------------------------------------- meta-block header + if overrun() then + return nil, "truncated stream" + end + local isLast = bits(1) == 1 + if isLast and bits(1) == 1 then + break -- ISLASTEMPTY + end + local mn = bits(2) + local mlen = 0 + if mn == 3 then + -- metadata + if bits(1) ~= 0 then + return nil, "reserved bit set" + end + local nbytes = bits(2) + for i = 0, nbytes - 1 do + local b = bits(8) + if i + 1 == nbytes and nbytes > 1 and b == 0 then + return nil, "exuberant metadata length byte" + end + mlen += b * 2 ^ (8 * i) + end + if nbytes > 0 then + mlen += 1 + end + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip -= rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated metadata" + end + ip += mlen + if isLast then + break + end + continue + end + local nib = mn + 4 + for i = 0, nib - 1 do + local v = bits(4) + if i + 1 == nib and nib > 4 and v == 0 then + return nil, "exuberant nibble" + end + mlen += v * 2 ^ (4 * i) + end + mlen += 1 + local uncompressed = false + if not isLast then + uncompressed = bits(1) == 1 + end + if op + mlen > maxBytes then + return nil, "limit: output over " .. maxBytes .. " bytes" + end + if op + mlen + 8 > blen(out) then + local nb = bcreate(math.min(math.max(blen(out) * 2, op + mlen + 8), maxBytes + 8)) + bcopy(nb, 0, out, 0, op) + out = nb + end + if uncompressed then + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip -= rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, ip, mlen) + ip += mlen + op += mlen + if isLast then + break + end + continue + end + + -- ---------------------------------------------------------------- compressed meta-block + tpos = 0 + -- block types / counts: 1 = literals, 2 = commands, 3 = distances + local nbtL, nbtI, nbtD = 1, 1, 1 + local btTreeL, btTreeI, btTreeD = 0, 0, 0 + local blTreeL, blTreeI, blTreeD = 0, 0, 0 + local cntL, cntI, cntD = 1073741824, 1073741824, 1073741824 + for c = 1, 3 do + local nbt = varLen8() + 1 + local btt, blt, cnt = 0, 0, 1073741824 + if nbt >= 2 then + btt = readCode(nbt + 2, nbt + 2) + if btt < 0 then + return nil, "bad block type code" + end + blt = readCode(26, 26) + if blt < 0 then + return nil, "bad block count code" + end + cnt = blockLen(blt) + end + if c == 1 then + nbtL, btTreeL, blTreeL, cntL = nbt, btt, blt, cnt + elseif c == 2 then + nbtI, btTreeI, blTreeI, cntI = nbt, btt, blt, cnt + else + nbtD, btTreeD, blTreeD, cntD = nbt, btt, blt, cnt + end + end + if overrun() then + return nil, "truncated meta-block header" + end + local npostfix = bits(2) + local ndirect = lshift(bits(4), npostfix) + local postMask = lshift(1, npostfix) - 1 + local modes = table.create(nbtL, 0) + for i = 1, nbtL do + modes[i] = bits(2) + end + local ntreesL, cmapL = readContextMap(64 * nbtL) + if ntreesL < 0 then + return nil, "bad literal context map" + end + local ntreesD, cmapD = readContextMap(4 * nbtD) + if ntreesD < 0 then + return nil, "bad distance context map" + end + -- the tree groups + local litBase = table.create(ntreesL, 0) + for i = 1, ntreesL do + local b = readCode(256, 256) + if b < 0 then + return nil, "bad literal code" + end + litBase[i] = b + end + local cmdBase = table.create(nbtI, 0) + for i = 1, nbtI do + local b = readCode(704, 704) + if b < 0 then + return nil, "bad insert-and-copy code" + end + cmdBase[i] = b + end + local distMax = 16 + ndirect + lshift(if large then 62 else 24, npostfix + 1) + local distLimit = if large then distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) else distMax + local distBase = table.create(ntreesD, 0) + for i = 1, ntreesD do + local b = readCode(distMax, distLimit) + if b < 0 then + return nil, "bad distance code" + end + distBase[i] = b + end + if overrun() then + return nil, "truncated meta-block header" + end + -- context map slices resolved to table bases + local litMap = table.create(64 * nbtL, 0) + for i = 0, 64 * nbtL - 1 do + litMap[i + 1] = litBase[readu8(cmapL, i) + 1] + end + local distMap = table.create(4 * nbtD, 0) + for i = 0, 4 * nbtD - 1 do + distMap[i + 1] = distBase[readu8(cmapD, i) + 1] + end + + -- block state: current type, previous type + local typeL, prevL = 0, 1 + local typeI, prevI = 0, 1 + local typeD, prevD = 0, 1 + local lutBase = modes[1] * 512 + local litSlice = 0 + local cmdTree = cmdBase[1] + local distSlice = 0 + + local remaining = mlen + while remaining > 0 do + if ip > lim + 4 then + return nil, "truncated stream" + end + -- command block switch + if cntI == 0 then + local t = decodeSym(btTreeI) + if t == 1 then + t = typeI + 1 + elseif t == 0 then + t = prevI + else + t -= 2 + end + if t >= nbtI then + t -= nbtI + end + prevI, typeI = typeI, t + cntI = blockLen(blTreeI) + cmdTree = cmdBase[t + 1] + end + cntI -= 1 + local cmd = decodeSym(cmdTree) + local cell = rshift(cmd, 6) + local insCode = CELL_INS[cell + 1] + band(rshift(cmd, 3), 7) + local cpyCode = CELL_CPY[cell + 1] + band(cmd, 7) + local insLen = INS_BASE[insCode + 1] + local ie = INS_EXTRA[insCode + 1] + if ie > 0 then + insLen += bits(ie) + end + local cpyLen = CPY_BASE[cpyCode + 1] + local ce = CPY_EXTRA[cpyCode + 1] + if ce > 0 then + cpyLen += bits(ce) + end + -- literals + if insLen > remaining then + return nil, "insert past the meta-block end" + end + if insLen > 0 then + local p1 = if op > 0 then readu8(out, op - 1) else 0 + local p2 = if op > 1 then readu8(out, op - 2) else 0 + for _ = 1, insLen do + if cntL == 0 then + local t = decodeSym(btTreeL) + if t == 1 then + t = typeL + 1 + elseif t == 0 then + t = prevL + else + t -= 2 + end + if t >= nbtL then + t -= nbtL + end + prevL, typeL = typeL, t + cntL = blockLen(blTreeL) + lutBase = modes[t + 1] * 512 + litSlice = t * 64 + end + cntL -= 1 + local ctx = bor(readu8(LUT, lutBase + p1), readu8(LUT, lutBase + 256 + p2)) + local base = litMap[litSlice + ctx + 1] + if bc < 16 then + if ip + 2 <= lim then + bb = bor(bb, lshift(readu16(src, ip), bc)) + ip += 2 + bc += 16 + else + fill() + end + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc -= l + local lit = rshift(e, 5) + writeu8(out, op, lit) + op += 1 + p2 = p1 + p1 = lit + end + remaining -= insLen + if remaining == 0 then + break + end + end + -- distance + local dist + local push = true + if cell < 2 then + dist = d0 + push = false + else + if cntD == 0 then + local t = decodeSym(btTreeD) + if t == 1 then + t = typeD + 1 + elseif t == 0 then + t = prevD + else + t -= 2 + end + if t >= nbtD then + t -= nbtD + end + prevD, typeD = typeD, t + cntD = blockLen(blTreeD) + distSlice = t * 4 + end + cntD -= 1 + local dctx = if cpyLen > 4 then 3 else cpyLen - 2 + local dcode = decodeSym(distMap[distSlice + dctx + 1]) + if dcode < 16 then + if dcode == 0 then + dist = d0 + push = false + elseif dcode == 1 then + dist = d1 + elseif dcode == 2 then + dist = d2 + elseif dcode == 3 then + dist = d3 + elseif dcode < 10 then + local k = (dcode - 2) // 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3 + dist = if dcode % 2 == 0 then d0 - k else d0 + k + else + local k = (dcode - 8) // 2 -- 10,11 -> 1; ... + dist = if dcode % 2 == 0 then d1 - k else d1 + k + end + if dist <= 0 then + return nil, "bad distance" + end + elseif dcode < 16 + ndirect then + dist = dcode - 15 + else + local x = dcode - ndirect - 16 + local ndistbits = 1 + rshift(x, npostfix + 1) + local hcode = rshift(x, npostfix) + local lcode = band(x, postMask) + local offset = (2 + band(hcode, 1)) * 2 ^ ndistbits - 4 + dist = (offset + bitsLong(ndistbits)) * 2 ^ npostfix + lcode + ndirect + 1 + end + end + local maxDist = if op < maxBackward then op else maxBackward + if dist > maxDist then + -- a static dictionary word + if dist > MAX_ALLOWED_DISTANCE or cpyLen < 4 or cpyLen > 24 then + return nil, "bad dictionary reference" + end + local nb = NDBITS[cpyLen + 1] + local addr = dist - maxDist - 1 + local widx = band(addr, lshift(1, nb) - 1) + local tidx = rshift(addr, nb) + if tidx >= NTRANSFORMS then + return nil, "bad dictionary transform" + end + local woff = DOFF[cpyLen + 1] + widx * cpyLen + -- transform into WORD + local pfx = PSMAP[TRANS[tidx * 3 + 1] + 1] + local ttype = TRANS[tidx * 3 + 2] + local sfx = PSMAP[TRANS[tidx * 3 + 3] + 1] + local w = 0 + local pl = readu8(PS, pfx) + for k = 1, pl do + writeu8(WORD, w, readu8(PS, pfx + k)) + w += 1 + end + local wl = cpyLen + local wo = woff + if ttype <= 9 then + wl -= ttype + elseif ttype >= 12 and ttype <= 20 then + local skip = ttype - 11 + wo += skip + wl -= skip + end + local ws = w + if wl > 0 then + bcopy(WORD, w, dict, wo, wl) + w += wl + end + if ttype == 10 then + -- uppercase the first character + local c = readu8(WORD, ws) + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, ws, c - 32) + end + elseif c < 0xE0 then + writeu8(WORD, ws + 1, bit32.bxor(readu8(WORD, ws + 1), 32)) + else + writeu8(WORD, ws + 2, bit32.bxor(readu8(WORD, ws + 2), 5)) + end + elseif ttype == 11 then + local p = ws + local left = wl + while left > 0 do + local c = readu8(WORD, p) + local step + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, p, c - 32) + end + step = 1 + elseif c < 0xE0 then + writeu8(WORD, p + 1, bit32.bxor(readu8(WORD, p + 1), 32)) + step = 2 + else + writeu8(WORD, p + 2, bit32.bxor(readu8(WORD, p + 2), 5)) + step = 3 + end + p += step + left -= step + end + end + local sl = readu8(PS, sfx) + for k = 1, sl do + writeu8(WORD, w, readu8(PS, sfx + k)) + w += 1 + end + if w == 0 and dist <= 120 then + return nil, "empty dictionary word" + end + if w > remaining then + return nil, "dictionary word past the meta-block end" + end + bcopy(out, op, WORD, 0, w) + op += w + remaining -= w + else + if cpyLen > remaining then + return nil, "copy past the meta-block end" + end + if push then + d3, d2, d1, d0 = d2, d1, d0, dist + end + local from = op - dist + if dist >= cpyLen then + bcopy(out, op, out, from, cpyLen) + else + for k = 0, cpyLen - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += cpyLen + remaining -= cpyLen + end + end + if isLast then + break + end + end + -- the final byte's padding bits must be zero + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding at the end" + end + ip -= rshift(bc, 3) + if ip > lim then + return nil, "truncated stream" + end + return out, op, ip +end + +return Decode diff --git a/src/Formats/codecs/Brotli/Static.luau b/src/Formats/codecs/Brotli/Static.luau new file mode 100644 index 0000000..d9170fa --- /dev/null +++ b/src/Formats/codecs/Brotli/Static.luau @@ -0,0 +1,866 @@ +--!strict +-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see +-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64), +-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B). +return { + dictionarySize = 122784, + dictionaryCrc = 1362545412, + dictionary = { + "eNo8velyHMe1LvrbiOA7lNpni8Q20QBJTSYGB0dJ3hq4Bcq+2z4ORXZVdncB1VWtyiqATUkR4ICB4ABSnAXOMyUCIDhiIIGI", + "wxeg/pH/FOeiuhsR9yHu962EbBkS0J2VlcMavrVyrZWJX9FeNBgGflEHupgUlNvvRp72VKJMORqMwqBm/ES7flKLqjrsS00S", + "+P26GGs9GMX9id6X1LSKowEdFyKvFuCXYhRXClHUXw1ULfAHdOCHuqyDajmqaON7uhLFfNYLorCUlHVlwNeDRT/0qqqE99ZM", + "MQ2CslZeouOKVm5ZxVoV46iSxKmuqLhfFQKdVqOw7JfKGKcOVOiFetDoAR2GGI+rjC5ESbkamSQ12qsoT5fRpqzx3rJKQlXR", + "n/lhfyGISsbfrwtoj/GhXT/690M8E69vdf5UjgJPh54Z9JPyF+gfw/AG0YfxS2GCtmU1oEvoy2gduioIqiopD2r8N0hNRYdp", + "0Q8qVRUnfZEfJmXfBL5JSlGEsWpvEPMc1AbfFUwFc1eBiTCcKPbdMt5vAmWSRCtMt1Ir4pl+PywN+kGg8fmgir0Cni36sd6D", + "NesPo0GFDvPVsFTB+ieYbBApr4S1NzoohlGiK6lbLmquRViLI7ffd6MwCl0dYJ/K2BPP194n2J84DXQZ66b61D4/LEZukBYC", + "NWgCbUxZBUXDPURf+6NQb+ro+A/8x7jYoL2go1i5uhCk2P80HtS6v4i/yyCaEtYJm4j9xtjLOsSa9PfralJVBp361TiKKp/s", + "/fwz0Eu4t1YFPaJTPNOvdbUYqBLopx+r4xUxnwTjjbHnCWi2L61UE6yWh/4wBnwPCgYtYvS1fqwV1iEpYl9UmkSgjTjvgoZU", + "0A+6rg5gTTz0XwGtY0eTJI3DQoQf0Ak4IYgjo9M42GCw8HEUaDwKUkwMlht7q7GPgZfvq5bAGpUBFdfwTAJaDg0Ix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n2Wx2rX6vizsYid98gy1ibFGFiBrMtc0y4B6peylLK7Ai5lZZK+kb", + "W/96o8RZSNipH3kb6XO357fWryaBg3K4vhbjydqVBK61bTYQJZFzw1q/xRqigte1kJuwK4qhV1EYpixaGuywAY7i7GdCkVBr", + "FAuQoNcGi4rmG/GhG8t9ZbZEXpuNazZfujwq42UNNNIsBzj0fOGBndbroOnUI2IxZZ6r8Z62gCd3gXUz4c9uP5GYFQZYDVBO", + "2NBSUShrxQ2NJboWa6TlfZqO0IPW9LJ68xvl8NIxgKF+lry3oVAbiagxsW8sgcplYbx/hCuw0UbbQcHKwhSE8SpyhxzUp9SB", + "d+wZn0M+EzVhiI1tDWXH0pkRNBHXbJF049hDoj02fglChltnY8i9otx6yIN1coccw/sho/QAVKig6TGzLnFeZ8TFYolfWD72", + "YFpigoJAbthzlC3e6diK33l2TQ32mRJcwSPhNPkECwgqEOu6UOPxmrV6eBrm+VI4uiBhTDUxfQJl9ZiRWpeJIY+VSB70voax", + "Lqbm97rSTvfXvXym1x6T2bKYRs5oQY6yAnlKC7zPnrRv5HWQPIdNpV6ksFMQWPDUbuXKN9/YuqyfqBgiz2uXO5esjBNMSe8q", + "Y70YcMEy80CH/TVsnvqaGXCelgPNdS3bElb+VXKEndp7tWobeU90QGMLf+V61qpgym2LjgJcpzcc1MOFlQr22Ly1gG0RAg6r", + "ojrftdj4I94HzUlvFGak9qJ3lJba33n/tOaOu0po4hPWWqYkkqCFtbqS31miZRwdfR5FiU3lgvCOcswPI6vYtzMgaZCxOEnM", + "HEdesoWVFV3KAVTouObaR/HXhpEuXdROBNasS+ubNhslVraePZbDxFtofcodjJoHCLyOjf7dRGwZam3aS3KKYXwbXFa0KmF7", + "WgS4imx5zi5xvkNex9z/aIc9MhArxw9tDdC14HFRnwDesG4HAPZtdXznB16ixRM2hx3JjToq4NFZyPBfysH2JOW1jyxmy4Pw", + "XrBeReJ/eQzY5nQppxzb6xagrJ0vvtzr2HL6G2VPFIRf7Nia+XTTJ1b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tf3KRRx95F77yEtBHzXyT7n7j64geCg75A8TMhEhgxeuAPF7kCv+kFvrm/U76HkhqU1ZZxN", + "xMahuHotkhQ9lG1Vf/3S2I6x0Xi7/utLf/W0/QnB7L96xn/522uP/u3V7//t1R9/+v1XPn3h7Gdn/lKAvU/OfV+IPfvl/3nu", + "hf/r8rn/+/k3P756/eO3j3987YnPzr/08/Pfh1b92e99dv4Cvnj6O5/99PlPnjn+6QvPfPLUS5/82emPr//JZw9/7+fv/vGn", + "T7z/yQsXPr7+2sfvv/Hxte/+4pHTnzx+/edPPvHzU+99+p0/+eylpz999QV78bPvvvvpj9757P0///jq8U/PvfLp917/+O0f", + "fHL+L35x5unPXn/45z96+JPXvvfJH//g43d++OlzFz595vwn1//00ytPfPbmtc+On/zkqb/85OTZT86f+uz86c/OX//k6euf", + "vvXGJy9c+uTqiU//5Nyn33vP2vPJ09//+PpZe+WTU699cu7Vn3/vxc+uPPXpX7xi//7cHue7j+Hi77/06cOvW5sDTtjY3Ltx", + "znyGAUw3TORypQRsGxmSMUFw1dAxYN0EEjT7qieYE2wt5G1thrtTY0t6TITXyo3ryOmy+lxoISq1kyVA3g2CsUIPOvy07g7C", + "eBtuh5OVkIQAXgHUR5oUgqH6MGZZm65zuYUzJlxkU3uAa6DKaELvVseE36nW+ca5st688RLsi0DJlsOAVw2ZcwHSEuX2vKmZ", + "cTd+soYqfUhkOSZLIDIV0+oWxMlhpr7Ug1a915/bpusAqsYjZnVp2z9SFWXjNduDxkFZoVprPW+NufHS6kh1JQRGeh/WjiSz", + "V9DL7FUsHDY1nsJR3oSrEcZX9rzuhcwL9gK4EMhaCS+9BItTH3qG/Yes+dVDEUA2L7/H2VIGjK9xswxTYAhkZR9IvJeYyQAk", + "lxgxtJmTZKv0bwVasAmYZPT8oAlR7ROUxH7fJbchOn6CwtgSBb/Kf1/hu5f51gV+7PFQIpdI+cN/e+rP/S18/iz/fZWK3dfi", + "OlIlv8YPPxvXOc5m6Kavshmn4+unujWYKgarjUu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COX2c3r1oIz+JZ94zRfA6+VnhWcYedTbzzl7XvDP3fi5mX7", + "rz0D23EycaqR/4yf/2nwscWz8Wm838guJtayR8RrhiuBSY3Phh56nc/zE3J+vYG2qE/BiGavgSHM+8Ce9wS5tx6z755ka8TQ", + "hc9dZk+etB56A0/EfiALnL3PpxGTGBnbToPbLI0CPneJXGInwWQG1jH2Pe74pPjMwI7mn8PdzqonfKStpX43tsaZzbzvnZPu", + "tTTGL2NmgDUuWM78Kuc5lpx/N1/15z2hUSSj2uvW9pP2/K/dfAs9jJlorXmU4/aWva4Zpj7XTD5LprM3Me7qe/vU686U9xZm", + "THP75Ei5DlakWUmNMEO4twUtzK/Xa/6qzmUC30LlWli4njvdnTYLlirGYPyL5MtMN+GneLGqv10PB0SneI6NsBiEZLcAyKqI", + "K9rsls3GYqoqR1mEpxqXFpQGpyeJmJmnuz35H6i1asQgMyP7GxTJbrPR+xJNV2d5TwvwqURCAM/BAT4C4qB21aO7IudxORz3", + "uw94RJOwpoCGkEd4y73IauR6ybPjYW/W4RebeAqmQxphenaDaplOCFMyKFajyW/X3dVGsto8ezP/pfu/+E1ybH0zWUmjSsm7", + "JZBpt5mexaU2W7JhlpJ1F9yumZm7o2xSejGCSiLctA9J5cXVQUIySn+5UObdXFSY9fs7ItVg0xGW+d+qElZ5Iiqpulsbg5GT", + "HAWDDMIOvdFiM94CtFGJH+ByJvexOopmffAyWfdtlsdUv7e/01gjHtIn7miHO7FM9cDe76QyxdJCSDYtjzYY4Vuph91hldiu", + "hF/jPMNIRZ7RI1h11QAw0njGL8Vam5kdydNpkSLdqHijUpSYyBAadp66Onh6ASfo/i/tlGtj4IsM9rIqGQXPIV/CPlOcNLz+", + "NVxRYUPzvw+srTMfMVJo2J25e21yQRl5MJxtzKmDB09UTF8e20olmSwnxCChQknBamnX2o2XWmgRIysqeawpGcoQWt3fpqNp", + "Dd41v64pPruLZjg9rd4dFRTJGFfotN5hrSAzO/VYGflWqSv5qwh8aJG1wQWFI+jkhi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a+m966oHhCia2YMC1AwXkxCmTqJQ", + "evEDvzMd1c0khUkHKvmVKILBdocNzXOlyLl8sxXMW/qt7mCVnFQMPjqzp22JFbJES9MB46nMnFm+01v5dHKnaQNh6xXSelMh", + "3RmCSFYhTLtKqG2knuDnA7qo+GFKVuaJmyYiO94qj24o790pMmsvHS7g6RQocWb68ItLRXy8DSPQeZ4KbdMXzfy1XYtTruqU", + "6d9Z3jWdhVuZyum0z7s6GDxY3xJBXPgW+uobsp337VnMNURAB+o65n6p+elkB47ZzDuaQn3NzOTJYzs7l6ZHJUu/4cqdKWxB", + "p63bcFbqIhdh8SRqzCt5bCks2VmeihpOW19L5ujq80cHw24zF9naQulaF/BOrN0ZeyoEI6atNWvV0arXa2ULipzFfed0MMN7", + "xcWwZzLV9jBpPPqblNBH9Yorxrqxl6pWphyefdOpqqViOhUfyQC3Xr5IzftEyTsd4vy8Z15tNt5v3T1piebUjDZtgXogT4NF", + "EIgTudXy7hRTa6WFm2nGw6ltbcovD7F6B8eKgxvj4epGJlyMD0/7vcR3ZYtHQJYNQs3MiPvWrtnc0tJYx+M2CceqS/s0azKA", + "5n3MChCml5am8MsZ1GM87M0yxty6pM0t3k+k5WQOT1VX9pNXmwWs2jQF75v5PRklID7fei4KhBVTSRXGjdr+i+oq93xaQC8R", + "k9O72fLRpGnNqUIq1K+DvByX3p9peGdGf3izwf3rkshmmAanpPueOZF7Fk0Sp2W2ykRrFrIviKZM5dlCHnzcugNFsOQy5JSH", + "IYvct7MRzRFUjMP0euVW2ihZE9lGX5N2pd6V6IwjZlcmmY680yfactaNiHZelzq9tga2qi0NSOtYIIZyuu707umNUSTwyS/M", + "wmThymZxpq/2JbVoT4jBW57egnKQI0Ohg637h4Otcr0MtmTXYM5qUCL6mpV9YIKIVs5c+fU+IKFVH/Gfw4iX2jO2eWfd6BDz", + "UmlU2q2KW2FWGLttc1Z+7HawTk7jWZwLNMX7p2qord3T6B7FcxOcLi92CTR2mwWf2kR3zpiDn0tZpbmqTYY5EcdLYpVphrol", + "sa9uihxkHEeMajoXi2kYDpZGprkj5sNiVpyIu5LKoMQM2yNV4oc5+AubW6pHxYom3ccZ0nSIoCmxAD0TjBznM76pi8H/821n", + "hgFdyemgFbqYcVKdDoqP51peF3z4ojNWnXreaUyc4eeHwZHyPslAzjltjr97xVmYnPUlb1Vilfl+ECslUpHg2sJ94/POoWRN", + "fZJfOR8sNO8Hscy1jFvG2vwIOEbwlR/xyj8m7cmpjHXqhaDKec6v7Jd6MThzxMTyfHbZn5IZ5ulgUzkdzUj8MGJAejXePTtF", + "OuTMJ8H8k4jC0qB4T55yWien5HqYb50NypfX4+snguPl1YwDJyihcKM/j1bpvuJ4eSsa/0LQlD0ZvEan+JZor07wjk/wymIM", + "+3YQOp0JEq2X+fuPg48op38RW9FPgwHmGfaMrvx83Pck5+EzbOd7+PcV0nk5y9BVp9DB76eiD58NZio90bmYPz9AY3ApsYG9", + "yktdjUF81Se2P8K1eN7oSZ9sz/ArifnqtSA7ej9olC5H152K532VVEIvxndPx3WuxBhpbiQeuVdj0p4KSqIXggXoTMZy9lZM", + "Zt3ieKygRD+VWHROxWp6OHaDx7NReC8YgcQv9JJTD+HDz8WIvx6sRKdjLTzil/J19O244Ivs57SfnGi3CO9MNemHMduD18uv", + "LG6fi/HhmLHek4k0LLoOH3vOv4K3RNkUXF748/W40QuxNYFFatg0v5NrbOweTWd5+HLO5T5KIGGm1acN7pmlW2AYxVRdWa9e", + "vsUrHnnN6Lzt5bzU/KodQg+2ma1i+jzZfYtJOxPXT351Oe2y71q8JTcE9HLXzB0ZKPuKW2zVFp9Ec2hf8LF7KLa4XbhklGv3", + "gTIKXcewqpcYiYVGGigCqv1C4LXewi2e3wzgGLneWKJ1Ce3ZbpfwuXvoe1TDhB9WQWzR3DIAC7fECpwD2SzTZmJX2OxMm5B7", + "RyQO39/5OjL3D3aWyUlTtMjLDO0NON7izC0Rg7liOptf0sRuNbtucdaX0v09w7h4SwcIp9CaqsTq5OWZxTTiKXN+VJ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AgMCAwIDAgMAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQECAgICAgICAgICAQEBAQEBAQICAgICAgICAgICAgICAgICAgICAgIC", + "AgICAQEBAQEBAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMBAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICAgIC", + "AgICAgICAgICAgICAgICAgICAgICAgICAAgICAgICAgICAgICAgICBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", + "EBAQEBAQEBAQEBAQEBAQEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", + "GBgYGBgYGBggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg", + "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoMDAwMDAwMDAwMDAwMDAwOAABAQEBAQEB", + "AQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMD", + "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", + "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF", + "BQUFBQUFBQUFBQUFBQUFBQYGBgYGBgYGBgYGBgYGBgc=", + }, + prefixSuffix = "ASACLCAIIG9mIHRoZSAEIG9mIAJzIAEuBSBhbmQgBCBpbiABIgQgdG8gAiI+AQoCLiABXQUgZm9yIAMgYSAGIHRoYXQgAScGIHdpdGggBiBmcm9tIAQgYnkgASgGLiBUaGUgBCBvbiAEIGFzIAQgaXMgBGluZyACCgkBOgNlZCACPSIEIGF0IANseSABLAI9JwUuY29tLwcuIFRoaXMgBSBub3QgA2VyIANhbCAEZnVsIARpdmUgBWxlc3MgBGVzdCAEaXplIALCoARvdXMgBSB0aGUgAmUgAA==", + prefixSuffixMap = { 0, 2, 5, 14, 19, 22, 24, 30, 35, 37, 42, 45, 47, 50, 52, 58, 62, 69, 71, 78, 85, 90, 92, 99, 104, 109, 114, 119, 122, 124, 128, 131, 136, 140, 142, 145, 151, 159, 165, 169, 173, 178, 183, 189, 194, 199, 202, 207, 213, 216 }, + transforms = { + 49, 0, 49, 49, 0, 0, 0, 0, 0, 49, 12, 49, 49, 10, 0, 49, 0, 47, 0, 0, 49, 4, 0, 0, 49, 0, 3, 49, 10, 49, + 49, 0, 6, 49, 13, 49, 49, 1, 49, 1, 0, 0, 49, 0, 1, 0, 10, 0, 49, 0, 7, 49, 0, 9, 48, 0, 0, 49, 0, 8, + 49, 0, 5, 49, 0, 10, 49, 0, 11, 49, 3, 49, 49, 0, 13, 49, 0, 14, 49, 14, 49, 49, 2, 49, 49, 0, 15, 49, 0, 16, + 0, 10, 49, 49, 0, 12, 5, 0, 49, 0, 0, 1, 49, 15, 49, 49, 0, 18, 49, 0, 17, 49, 0, 19, 49, 0, 20, 49, 16, 49, + 49, 17, 49, 47, 0, 49, 49, 4, 49, 49, 0, 22, 49, 11, 49, 49, 0, 23, 49, 0, 24, 49, 0, 25, 49, 7, 49, 49, 1, 26, + 49, 0, 27, 49, 0, 28, 0, 0, 12, 49, 0, 29, 49, 20, 49, 49, 18, 49, 49, 6, 49, 49, 0, 21, 49, 10, 1, 49, 8, 49, + 49, 0, 31, 49, 0, 32, 47, 0, 3, 49, 5, 49, 49, 9, 49, 0, 10, 1, 49, 10, 8, 5, 0, 21, 49, 11, 0, 49, 10, 10, + 49, 0, 30, 0, 0, 5, 35, 0, 49, 47, 0, 2, 49, 10, 17, 49, 0, 36, 49, 0, 33, 5, 0, 0, 49, 10, 21, 49, 10, 5, + 49, 0, 37, 0, 0, 30, 49, 0, 38, 0, 11, 0, 49, 0, 39, 0, 11, 49, 49, 0, 34, 49, 11, 8, 49, 10, 12, 0, 0, 21, + 49, 0, 40, 0, 10, 12, 49, 0, 41, 49, 0, 42, 49, 11, 17, 49, 0, 43, 0, 10, 5, 49, 11, 10, 0, 0, 34, 49, 10, 33, + 49, 0, 44, 49, 11, 5, 45, 0, 49, 0, 0, 33, 49, 10, 30, 49, 11, 30, 49, 0, 46, 49, 11, 1, 49, 10, 34, 0, 10, 33, + 0, 11, 30, 0, 11, 1, 49, 11, 33, 49, 11, 21, 49, 11, 12, 0, 11, 5, 49, 11, 34, 0, 11, 12, 0, 10, 30, 0, 11, 34, + 0, 10, 34, + }, +} diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/Brotli/init.luau new file mode 100644 index 0000000..391ec29 --- /dev/null +++ b/src/Formats/codecs/Brotli/init.luau @@ -0,0 +1,150 @@ +--!strict +-- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written +-- from the RFC (decoder in codecs/Brotli/Decode); the static dictionary, context table and word transforms come from +-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/Brotli/Static (tools/brotli_static.py). +-- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static +-- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression, +-- shared / compound dictionaries (draft "shared brotli"). +-- +-- local Brotli = require("@formats/codecs/Brotli") +-- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string +-- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 }) +-- +-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG). +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/Deflate") +local Decode = require("@formats/codecs/Brotli/Decode") +local StaticData = require("@formats/codecs/Brotli/Static") + +local Brotli = {} + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + largeWindow: boolean?, -- accept the large-window extension (windows up to 2^30; default true) +} + +-- ------------------------------------------------------------------------------------------------ static data +local B64 = {} +do + local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + for i = 1, 64 do + B64[string.byte(alphabet, i)] = i - 1 + end +end + +local function unbase64(s: string): buffer + local n = #s + local pad = 0 + if string.sub(s, -2) == "==" then + pad = 2 + elseif string.sub(s, -1) == "=" then + pad = 1 + end + local out = buffer.create(n // 4 * 3 - pad) + local o = 0 + for i = 1, n, 4 do + local a, b, c, d = string.byte(s, i, i + 3) + local v = B64[a] * 262144 + B64[b] * 4096 + (B64[c] or 0) * 64 + (B64[d] or 0) + buffer.writeu8(out, o, v // 65536) + if o + 1 < buffer.len(out) then + buffer.writeu8(out, o + 1, (v // 256) % 256) + end + if o + 2 < buffer.len(out) then + buffer.writeu8(out, o + 2, v % 256) + end + o += 3 + end + return out +end + +local static: Decode.Static? = nil + +-- tables() -> the decoded static data (inflated once, on first use) +local function tables(): (Decode.Static?, Err.Err?) + if static then + return static, nil + end + local z = unbase64(table.concat(StaticData.dictionary)) + local dict, err = Deflate.zlib(z, 0, nil, StaticData.dictionarySize) + if not dict then + return nil, err + end + if Crc32.of(dict) ~= StaticData.dictionaryCrc then + return nil, Err.new(Err.CHECKSUM, "brotli: static dictionary damaged") + end + static = { + dictionary = dict, + context = unbase64(table.concat(StaticData.context)), + prefixSuffix = unbase64(StaticData.prefixSuffix), + prefixSuffixMap = StaticData.prefixSuffixMap, + transforms = StaticData.transforms, + } + return static, nil +end + +-- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders) +function Brotli.dictionary(): buffer? + local s = tables() + return if s then s.dictionary else nil +end + +-- ------------------------------------------------------------------------------------------------ decompress +local function toBuffer(b: any): buffer? + if type(b) == "string" then + return buffer.fromstring(b) + end + return if type(b) == "buffer" then b else nil +end + +-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past +-- the stream (trailing bytes are ignored). +function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b = toBuffer(buf) + if not b then + return nil, Err.new(Err.ARG, "Brotli.decompress: expected a buffer or a string, got " .. typeof(buf)) + end + local n = buffer.len(b) + local o = offset or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Brotli.decompress: bad offset " .. tostring(offset)) + end + local l = length or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Brotli.decompress: bad length " .. tostring(length)) + end + l = math.min(l, n - o) + local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 30 + if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Brotli.decompress: bad maxBytes") + end + local large = not (opts and opts.largeWindow == false) + if l == 0 then + return nil, Err.new(Err.TRUNCATED, "brotli: empty input", o) + end + local S, serr = tables() + if not S then + return nil, serr + end + local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) + if not out then + local msg = tostring(size) + local code = Err.CORRUPT + if string.find(msg, "truncated", 1, true) then + code = Err.TRUNCATED + elseif string.sub(msg, 1, 6) == "limit:" then + code = Err.LIMIT + elseif string.sub(msg, 1, 12) == "unsupported:" then + code = Err.UNSUPPORTED + end + return nil, Err.new(code, "brotli: " .. msg, o) + end + local res = out + if buffer.len(out) ~= size then + res = buffer.create(size) + buffer.copy(res, 0, out, 0, size) + end + return res, consumed +end + +return Brotli diff --git a/src/Formats/codecs/Bzip2/Decode.luau b/src/Formats/codecs/Bzip2/Decode.luau new file mode 100644 index 0000000..66df42e --- /dev/null +++ b/src/Formats/codecs/Bzip2/Decode.luau @@ -0,0 +1,538 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and +-- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. +-- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for +-- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index +-- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is +-- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. +-- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). +-- +-- Never throws: every buffer access is in range by construction; failures return nil, message, kind +-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local Decode = {} + +-- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected) +local CT = table.create(256, 0) +for i = 0, 255 do + local c = lshift(i, 24) + for _ = 1, 8 do + if band(c, 0x80000000) ~= 0 then + c = bxor(lshift(c, 1), 0x04C11DB7) + else + c = lshift(c, 1) + end + end + CT[i + 1] = c +end +Decode.crcTable = CT + +local MASK = table.create(33, 0) +for i = 0, 32 do + MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 +end + +local PBITS = 10 -- primary lookup width +local PSIZE = 1024 +local MAXGROUPS = 6 +local MAXALPHA = 258 +local MAXLEN = 20 + +-- scratch tables, reused across calls (single-threaded) +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LENS = bcreate(MAXGROUPS * MAXALPHA) +local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order +local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length +local MAXL = table.create(MAXGROUPS, 0) +local CFTAB = table.create(257, 0) +local MTF = table.create(256, 0) +local SEQ = table.create(256, 0) + +-- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed +local function buildGroup(g: number, n: number): boolean + local lbase = g * MAXALPHA + local cbase = g * (MAXLEN + 1) + for l = 0, MAXLEN do + COUNT[cbase + l + 1] = 0 + end + local maxLen = 0 + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + COUNT[cbase + l + 1] += 1 + if l > maxLen then + maxLen = l + end + end + MAXL[g + 1] = maxLen + -- canonical codes: by length, then symbol + local code, idx = 0, 0 + for l = 1, MAXLEN do + FIRST[cbase + l + 1] = code + OFFS[cbase + l + 1] = idx + local c = COUNT[cbase + l + 1] + code += c + idx += c + if code > 2 ^ l then + return false + end + code *= 2 + end + -- perm + lookup + local pbase = g * MAXALPHA + local tbase = g * PSIZE * 4 + bfill(LOOK, tbase, 0, PSIZE * 4) + local next = table.create(MAXLEN + 1, 0) + for l = 1, MAXLEN do + next[l + 1] = OFFS[cbase + l + 1] + end + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + local k = next[l + 1] + next[l + 1] = k + 1 + PERM[pbase + k + 1] = s + if l <= PBITS then + local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) + local shift = PBITS - l + local from = lshift(c, shift) + local entry = s * 32 + l + for j = from, from + lshift(1, shift) - 1 do + writeu32(LOOK, tbase + j * 4, entry) + end + end + end + return true +end + +local function grow(out: buffer, op: number, need: number): buffer + local nb = bcreate(math.max(blen(out) * 2, need, 65536)) + bcopy(nb, 0, out, 0, op) + return nb +end + +-- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind +function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) + local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) + local op = 0 + local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local bb, bc = 0, 0 + local tt: buffer? = nil + local ttSize = 0 + local streams = 0 + local consumedEnd = o + + while true do + -- stream header (byte aligned) + if streams > 0 then + if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + break -- trailing data after a stream is ignored, as bzip2 -d does + end + end + if p + 4 > e then + return nil, "truncated stream header", "truncated" + end + if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + return nil, "bad magic", "corrupt" + end + local level = readu8(b, p + 3) - 0x30 + if level < 1 or level > 9 then + return nil, "bad block size", "corrupt" + end + local maxBlock = level * 100000 + if ttSize < maxBlock then + tt = bcreate(maxBlock * 4) + ttSize = maxBlock + end + local T = tt :: buffer + p += 4 + bb, bc = 0, 0 + local combined = 0 + + while true do + -- 48-bit magic + 32-bit CRC + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local c1 = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 + bc -= 16 + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block header", "truncated" + end + if m1 == 0x177245 and m2 == 0x385090 then + if storedCrc ~= combined then + return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" + end + -- align to the byte after the stream + p -= bc // 8 + bb, bc = 0, 0 + break + end + if m1 ~= 0x314159 or m2 ~= 0x265359 then + return nil, "bad block magic", "corrupt" + end + + -- randomised bit, origPtr, symbol map + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local rnd = band(rshift(bb, bc - 1), 1) + bc -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + if rnd ~= 0 then + return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" + end + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local used = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + local nInUse = 0 + for i = 0, 15 do + if band(used, lshift(1, 15 - i)) ~= 0 then + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local bits = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + for j = 0, 15 do + if band(bits, lshift(1, 15 - j)) ~= 0 then + SEQ[nInUse + 1] = i * 16 + j + nInUse += 1 + end + end + end + end + if nInUse == 0 then + return nil, "no symbols in use", "corrupt" + end + local alphaSize = nInUse + 2 + + -- groups and selectors + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local nGroups = band(rshift(bb, bc - 3), 7) + bc -= 3 + local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) + bc -= 15 + if nGroups < 2 or nGroups > 6 then + return nil, "bad number of Huffman groups", "corrupt" + end + if nSelectors < 1 then + return nil, "no selectors", "corrupt" + end + local selectors = buffer.create(nSelectors) + local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 + for i = 0, nSelectors - 1 do + local j = 0 + while true do + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + j += 1 + if j >= nGroups then + return nil, "bad selector", "corrupt" + end + end + -- move-to-front over the group list + local v + if j == 0 then + v = mtfg0 + elseif j == 1 then + v = mtfg1 + mtfg1 = mtfg0 + elseif j == 2 then + v = mtfg2 + mtfg2, mtfg1 = mtfg1, mtfg0 + elseif j == 3 then + v = mtfg3 + mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 + elseif j == 4 then + v = mtfg4 + mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 + else + v = mtfg5 + mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 + end + mtfg0 = v + writeu8(selectors, i, v) + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated selectors", "truncated" + end + + -- code lengths (delta coded) + for g = 0, nGroups - 1 do + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local len = band(rshift(bb, bc - 5), 31) + bc -= 5 + for s = 0, alphaSize - 1 do + while true do + if len < 1 or len > MAXLEN then + return nil, "bad code length", "corrupt" + end + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + len += 1 + else + len -= 1 + end + end + writeu8(LENS, g * MAXALPHA + s, len) + end + if not buildGroup(g, alphaSize) then + return nil, "over-subscribed Huffman code", "corrupt" + end + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated code lengths", "truncated" + end + + -- MTF / RUNA / RUNB symbols -> T low bytes + for i = 0, 255 do + CFTAB[i + 1] = 0 + MTF[i + 1] = i + end + local eob = alphaSize - 1 + local nblock = 0 + local selIdx = 0 + local left = 0 + local g = 0 + local tbase, pbase, cbase, gmax = 0, 0, 0, 0 + local runLen, runBit = 0, 1 + while true do + if left == 0 then + if selIdx >= nSelectors then + return nil, "ran out of selectors", "corrupt" + end + g = readu8(selectors, selIdx) + selIdx += 1 + left = 50 + tbase = g * PSIZE * 4 + pbase = g * MAXALPHA + cbase = g * (MAXLEN + 1) + gmax = MAXL[g + 1] + end + left -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) + local sym + if ent ~= 0 then + bc -= band(ent, 31) + sym = rshift(ent, 5) + else + -- a code longer than PBITS: canonical search + local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) + sym = -1 + for l = PBITS + 1, gmax do + local c = rshift(v, gmax - l) + local f = FIRST[cbase + l + 1] + local k = c - f + if k >= 0 and k < COUNT[cbase + l + 1] then + sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] + bc -= l + break + end + end + if sym < 0 then + return nil, "bad Huffman code", "corrupt" + end + end + if sym <= 1 then + -- RUNA / RUNB: bijective base-2 run length of the front symbol + runLen += runBit * (sym + 1) + runBit *= 2 + if runLen > maxBlock then + return nil, "run past the block size", "corrupt" + end + else + if runLen > 0 then + if nblock + runLen > maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local ch = SEQ[MTF[1] + 1] + CFTAB[ch + 1] += runLen + for k = nblock, nblock + runLen - 1 do + writeu32(T, k * 4, ch) + end + nblock += runLen + runLen, runBit = 0, 1 + end + if sym == eob then + break + end + local idx = sym - 1 + if idx >= nInUse then + return nil, "bad MTF index", "corrupt" + end + if nblock >= maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local v = MTF[idx + 1] + for k = idx, 1, -1 do + MTF[k + 1] = MTF[k] + end + MTF[1] = v + local ch = SEQ[v + 1] + CFTAB[ch + 1] += 1 + writeu32(T, nblock * 4, ch) + nblock += 1 + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block data", "truncated" + end + end + if origPtr >= nblock then + return nil, "bad BWT origin pointer", "corrupt" + end + + -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position + local sum = 0 + for i = 0, 255 do + local c = CFTAB[i + 1] + CFTAB[i + 1] = sum + sum += c + end + for i = 0, nblock - 1 do + local ch = band(readu32(T, i * 4), 255) + local k = CFTAB[ch + 1] + CFTAB[ch + 1] = k + 1 + writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) + end + + -- walk, undo RLE1, CRC + if op + nblock + 4096 > blen(out) then + out = grow(out, op, op + nblock + 4096) + end + local cap = blen(out) + local crc = 0xFFFFFFFF + local tPos = rshift(readu32(T, origPtr * 4), 8) + local last, run = -1, 0 + local i = 0 + while i < nblock do + local v = readu32(T, tPos * 4) + local ch = band(v, 255) + tPos = rshift(v, 8) + i += 1 + if run == 4 then + -- ch is a repeat count for the previous byte + if ch > 0 then + if op + ch > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + if op + ch + 256 > cap then + out = grow(out, op, op + ch + nblock - i + 4096) + cap = blen(out) + end + bfill(out, op, last, ch) + op += ch + for _ = 1, ch do + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) + end + end + run = 0 + last = -1 + else + if ch == last then + run += 1 + else + run = 1 + last = ch + end + if op + 256 > cap then + if op >= maxBytes then + return nil, "output larger than maxBytes", "limit" + end + out = grow(out, op, op + nblock - i + 4096) + cap = blen(out) + end + writeu8(out, op, ch) + op += 1 + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) + end + end + if op > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + crc = bxor(crc, 0xFFFFFFFF) + if crc ~= storedCrc then + return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" + end + combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) + end + streams += 1 + consumedEnd = p + if p >= e then + break + end + end + return out, op, consumedEnd +end + +return Decode diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/Bzip2/init.luau new file mode 100644 index 0000000..e492aee --- /dev/null +++ b/src/Formats/codecs/Bzip2/init.luau @@ -0,0 +1,77 @@ +--!strict +-- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec +-- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). +-- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). +-- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. +-- +-- local Bzip2 = require("@formats/codecs/Bzip2") +-- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err +-- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) +-- +-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). +local Err = require("@formats/core/Err") +local Decode = require("@formats/codecs/Bzip2/Decode") + +local Bzip2 = {} + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) +} + +local KINDS = { + truncated = Err.TRUNCATED, + corrupt = Err.CORRUPT, + checksum = Err.CHECKSUM, + limit = Err.LIMIT, + unsupported = Err.UNSUPPORTED, +} + +-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err +function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b: buffer + if type(buf) == "string" then + b = buffer.fromstring(buf) + elseif type(buf) == "buffer" then + b = buf + else + return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf)) + end + local n = buffer.len(b) + local o = offset or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset)) + end + local l = length or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length)) + end + l = math.min(l, n - o) + local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 + if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes") + end + local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) + if not out then + return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o) + end + local res = out + if buffer.len(out) ~= nOut then + res = buffer.create(nOut) + buffer.copy(res, 0, out, 0, nOut) + end + return res, consumed +end + +-- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) +function Bzip2.crc(buf: buffer, offset: number?, length: number?): number + local CT = Decode.crcTable + local o = offset or 0 + local e = o + (length or (buffer.len(buf) - o)) + local c = 0xFFFFFFFF + for i = o, e - 1 do + c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) + end + return bit32.bxor(c, 0xFFFFFFFF) +end + +return Bzip2 diff --git a/src/Formats/codecs/Cff/init.luau b/src/Formats/codecs/Cff/init.luau new file mode 100644 index 0000000..bdec1dc --- /dev/null +++ b/src/Formats/codecs/Cff/init.luau @@ -0,0 +1,657 @@ +--!strict +-- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts +-- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed +-- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands +-- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 +-- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, +-- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage +-- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). +-- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. +-- +-- local cff, err = Cff.parse(buf, offset, length) +-- local cmds, err = Cff.outline(cff, glyphIndex) +-- +-- Never throws: malformed data returns nil, message. +local Cff = {} + +local readu8 = buffer.readu8 +local blen = buffer.len + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function uN(b: buffer, o: number, n: number): number + local v = 0 + for i = 0, n - 1 do + v = v * 256 + u8(b, o + i) + end + return v +end + +export type Index = { count: number, offSize: number, offsets: number, data: number, next: number } +export type Font = { + buf: buffer, + base: number, + limit: number, + charStrings: Index, + gsubrs: Index, + subrs: Index?, -- name-keyed fonts + fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict + fdSelect: number?, -- absolute offset of FDSelect + numGlyphs: number, + cid: boolean, + fontMatrix: { number }?, +} + +-- INDEX at absolute offset p (within [base, limit)) -> Index | nil +local function index(b: buffer, p: number, limit: number): Index? + if p + 2 > limit then + return nil + end + local count = uN(b, p, 2) + if count == 0 then + return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 } + end + local offSize = u8(b, p + 2) + if offSize < 1 or offSize > 4 then + return nil + end + local offsets = p + 3 + local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based + if data + 1 > limit then + return nil + end + local last = uN(b, offsets + count * offSize, offSize) + if data + last > limit then + return nil + end + return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } +end + +-- item(idx, i) -> absolute start, length (nil when out of range / corrupt) +local function item(b: buffer, idx: Index, i: number): (number?, number) + if i < 0 or i >= idx.count then + return nil, 0 + end + local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize) + local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize) + if s < 1 or e < s or idx.data + e > idx.next then + return nil, 0 + end + return idx.data + s, e - s +end +Cff.item = item + +-- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +local function dict(b: buffer, p: number, n: number): { [number]: { number } } + local out: { [number]: { number } } = {} + local ops: { number } = {} + local e = p + n + while p < e do + local b0 = u8(b, p) + if b0 <= 21 then + local op = b0 + p += 1 + if b0 == 12 then + op = 1200 + u8(b, p) + p += 1 + end + out[op] = ops + ops = {} + elseif b0 == 28 then + local v = uN(b, p + 1, 2) + table.insert(ops, if v >= 32768 then v - 65536 else v) + p += 3 + elseif b0 == 29 then + local v = uN(b, p + 1, 4) + table.insert(ops, if v >= 2147483648 then v - 4294967296 else v) + p += 5 + elseif b0 == 30 then -- real number: BCD nibbles + local s = {} + p += 1 + local done = false + while p < e and not done do + local byte = u8(b, p) + p += 1 + for _, nib in { byte // 16, byte % 16 } do + if nib <= 9 then + table.insert(s, tostring(nib)) + elseif nib == 10 then + table.insert(s, ".") + elseif nib == 11 then + table.insert(s, "E") + elseif nib == 12 then + table.insert(s, "E-") + elseif nib == 14 then + table.insert(s, "-") + elseif nib == 15 then + done = true + break + end + end + end + table.insert(ops, tonumber(table.concat(s)) or 0) + elseif b0 >= 32 and b0 <= 246 then + table.insert(ops, b0 - 139) + p += 1 + elseif b0 >= 247 and b0 <= 250 then + table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108) + p += 2 + elseif b0 >= 251 and b0 <= 254 then + table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108) + p += 2 + else + p += 1 -- reserved + end + if #ops > 48 then + return out + end + end + return out +end + +local function privateSubrs(b: buffer, base: number, limit: number, d: { [number]: { number } }): Index? + local pr = d[18] + if not pr or #pr < 2 then + return nil + end + local size, off = pr[1], pr[2] + local ps = base + off + if size < 0 or off < 0 or ps + size > limit then + return nil + end + local pd = dict(b, ps, size) + local s = pd[19] + if not s or #s < 1 then + return nil + end + return index(b, ps + s[1], limit) +end + +-- parse(buf, offset, length) -> Font | nil, message +function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?) + local base, limit = offset, math.min(offset + length, blen(b)) + if limit - base < 4 then + return nil, "truncated CFF header" + end + local major, hdrSize = u8(b, base), u8(b, base + 2) + if major == 2 then + return nil, "unsupported: CFF2 (variable font outlines)" + end + if major ~= 1 then + return nil, "bad CFF version " .. major + end + local names = index(b, base + hdrSize, limit) + if not names then + return nil, "bad name INDEX" + end + local tops = index(b, names.next, limit) + if not tops or tops.count < 1 then + return nil, "bad Top DICT INDEX" + end + local strings = index(b, tops.next, limit) + if not strings then + return nil, "bad String INDEX" + end + local gsubrs = index(b, strings.next, limit) + if not gsubrs then + return nil, "bad global subrs INDEX" + end + local ts, tl = item(b, tops, 0) + if not ts then + return nil, "bad Top DICT" + end + local top = dict(b, ts, tl) + local cso = top[17] + if not cso or #cso < 1 then + return nil, "no CharStrings" + end + local cst = top[1206] + if cst and cst[1] ~= 2 then + return nil, "unsupported: charstring type " .. tostring(cst[1]) + end + local charStrings = index(b, base + cso[1], limit) + if not charStrings then + return nil, "bad CharStrings INDEX" + end + local f: Font = { + buf = b, + base = base, + limit = limit, + charStrings = charStrings, + gsubrs = gsubrs, + subrs = nil, + fdSubrs = nil, + fdSelect = nil, + numGlyphs = charStrings.count, + cid = top[1230] ~= nil, + fontMatrix = top[1207], + } + if f.cid then + local fda, fds = top[1236], top[1237] + if not fda or not fds then + return nil, "CID font without FDArray / FDSelect" + end + local fdArray = index(b, base + fda[1], limit) + if not fdArray then + return nil, "bad FDArray" + end + local list: { Index? } = {} + for i = 0, math.min(fdArray.count, 256) - 1 do + local s, l = item(b, fdArray, i) + list[i + 1] = if s then privateSubrs(b, base, limit, dict(b, s, l)) else nil + end + f.fdSubrs = list + f.fdSelect = base + fds[1] + else + f.subrs = privateSubrs(b, base, limit, top) + end + return f, nil +end + +local function bias(count: number): number + return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 +end + +-- the local subrs of glyph g (CID fonts: through FDSelect) +local function localSubrs(f: Font, g: number): Index? + if not f.cid then + return f.subrs + end + local b, p = f.buf, f.fdSelect :: number + local fmt = u8(b, p) + local fd = -1 + if fmt == 0 then + fd = u8(b, p + 1 + g) + elseif fmt == 3 then + local n = uN(b, p + 1, 2) + local first = uN(b, p + 3, 2) + for i = 0, n - 1 do + local q = p + 5 + i * 3 + local v = u8(b, q) + local nxt = uN(b, q + 1, 2) + if g >= first and g < nxt then + fd = v + break + end + first = nxt + end + end + local list = f.fdSubrs :: { Index? } + return list[fd + 1] +end + +local BUDGET = 200000 -- operators per glyph (subroutine bombs) + +-- outline(f, g) -> path commands | nil, message +function Cff.outline(f: Font, g: number): ({ any }?, string?) + local b = f.buf + local p, len = item(b, f.charStrings, g) + if not p then + return nil, "bad glyph index " .. tostring(g) + end + local e = p + len + local cmds: { any } = {} + local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count + local sp = 0 + local trans: { number } = table.create(32, 0) + local x, y = 0, 0 + local open = false + local maskbits = 0 + local inHeader = true + local stack: { { number } } = {} -- return addresses { p, e } + local subrs: Index? = nil + local haveSubrs = false + local ops = 0 + local seed = 12345 + + local function moveTo(dx: number, dy: number) + if open then + table.insert(cmds, { op = "close" }) + end + x += dx + y += dy + table.insert(cmds, { op = "moveTo", x, y }) + open = true + end + local function lineTo(dx: number, dy: number) + if not open then + moveTo(0, 0) + end + x += dx + y += dy + table.insert(cmds, { op = "lineTo", x, y }) + end + local function curveTo(dx1: number, dy1: number, dx2: number, dy2: number, dx3: number, dy3: number) + if not open then + moveTo(0, 0) + end + local x1, y1 = x + dx1, y + dy1 + local x2, y2 = x1 + dx2, y1 + dy2 + x, y = x2 + dx3, y2 + dy3 + table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) + end + local function S(i: number): number -- operand i (0-based), 0 past the stack + return s[i + 1] or 0 + end + + while true do + if p >= e then + -- the end of a subroutine without return, or of the charstring without endchar + if #stack > 0 then + local r = table.remove(stack) :: { number } + p, e = r[1], r[2] + continue + end + break + end + ops += 1 + if ops > BUDGET then + return nil, "charstring too long (subroutine loop?)" + end + local b0 = u8(b, p) + p += 1 + local clear = true + local i = 0 + if b0 == 19 or b0 == 20 then -- hintmask, cntrmask + if inHeader then + maskbits += sp // 2 + end + inHeader = false + p += (maskbits + 7) // 8 + elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm + maskbits += sp // 2 + elseif b0 == 21 then -- rmoveto + inHeader = false + if sp < 2 then + return nil, "rmoveto stack" + end + moveTo(S(sp - 2), S(sp - 1)) + elseif b0 == 4 then -- vmoveto + inHeader = false + if sp < 1 then + return nil, "vmoveto stack" + end + moveTo(0, S(sp - 1)) + elseif b0 == 22 then -- hmoveto + inHeader = false + if sp < 1 then + return nil, "hmoveto stack" + end + moveTo(S(sp - 1), 0) + elseif b0 == 5 then -- rlineto + if sp < 2 then + return nil, "rlineto stack" + end + while i + 1 < sp do + lineTo(S(i), S(i + 1)) + i += 2 + end + elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate + if sp < 1 then + return nil, "hlineto stack" + end + local horiz = b0 == 6 + while i < sp do + if horiz then + lineTo(S(i), 0) + else + lineTo(0, S(i)) + end + horiz = not horiz + i += 1 + end + elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate + if sp < 4 then + return nil, "hvcurveto stack" + end + local horiz = b0 == 31 + while i + 3 < sp do + local last = if sp - i == 5 then S(i + 4) else 0 + if horiz then + curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3)) + else + curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last) + end + horiz = not horiz + i += 4 + end + elseif b0 == 8 then -- rrcurveto + if sp < 6 then + return nil, "rrcurveto stack" + end + while i + 5 < sp do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i += 6 + end + elseif b0 == 24 then -- rcurveline + if sp < 8 then + return nil, "rcurveline stack" + end + while i + 5 < sp - 2 do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i += 6 + end + lineTo(S(i), S(i + 1)) + elseif b0 == 25 then -- rlinecurve + if sp < 8 then + return nil, "rlinecurve stack" + end + while i + 1 < sp - 6 do + lineTo(S(i), S(i + 1)) + i += 2 + end + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto + if sp < 4 then + return nil, "vv/hhcurveto stack" + end + local f0 = 0 + if sp % 2 == 1 then + f0 = S(0) + i = 1 + end + while i + 3 < sp do + if b0 == 27 then + curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0) + else + curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3)) + end + f0 = 0 + i += 4 + end + elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr + if b0 == 10 and not haveSubrs then + subrs = localSubrs(f, g) + haveSubrs = true + end + if sp < 1 then + return nil, "callsubr stack" + end + local idx = if b0 == 10 then subrs else f.gsubrs + if not idx then + return nil, "no subroutines" + end + local n = math.floor(S(sp - 1)) + bias(idx.count) + sp -= 1 + if #stack >= 10 then + return nil, "subroutine recursion limit" + end + local sp0, sl = item(b, idx, n) + if not sp0 then + return nil, "subroutine " .. n .. " not found" + end + table.insert(stack, { p, e }) + p, e = sp0, sp0 + sl + clear = false + elseif b0 == 11 then -- return + if #stack == 0 then + return nil, "return outside a subroutine" + end + local r = table.remove(stack) :: { number } + p, e = r[1], r[2] + clear = false + elseif b0 == 14 then -- endchar + if open then + table.insert(cmds, { op = "close" }) + end + return cmds, nil + elseif b0 == 12 then -- escape + local b1 = u8(b, p) + p += 1 + if b1 == 34 then -- hflex + if sp < 7 then + return nil, "hflex stack" + end + curveTo(S(0), 0, S(1), S(2), S(3), 0) + curveTo(S(4), 0, S(5), -S(2), S(6), 0) + elseif b1 == 35 then -- flex + if sp < 13 then + return nil, "flex stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), S(10), S(11)) + elseif b1 == 36 then -- hflex1 + if sp < 9 then + return nil, "hflex1 stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), 0) + curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7))) + elseif b1 == 37 then -- flex1 + if sp < 11 then + return nil, "flex1 stack" + end + local dx = S(0) + S(2) + S(4) + S(6) + S(8) + local dy = S(1) + S(3) + S(5) + S(7) + S(9) + local dx6, dy6 = S(10), S(10) + if math.abs(dx) > math.abs(dy) then + dy6 = -dy + else + dx6 = -dx + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), dx6, dy6) + else + -- arithmetic and storage operators: they leave results on the stack + clear = false + local top = sp + local a, c = S(top - 2), S(top - 1) + local function set(n: number, v: number) + -- pop n operands, push v + sp = math.max(0, sp - n) + sp += 1 + s[sp] = v + end + if b1 == 3 then + set(2, if a ~= 0 and c ~= 0 then 1 else 0) -- and + elseif b1 == 4 then + set(2, if a ~= 0 or c ~= 0 then 1 else 0) -- or + elseif b1 == 5 then + set(1, if c == 0 then 1 else 0) -- not + elseif b1 == 9 then + set(1, math.abs(c)) + elseif b1 == 10 then + set(2, a + c) + elseif b1 == 11 then + set(2, a - c) + elseif b1 == 12 then + set(2, if c ~= 0 then a / c else 0) + elseif b1 == 14 then + set(1, -c) + elseif b1 == 15 then + set(2, if a == c then 1 else 0) + elseif b1 == 18 then + sp = math.max(0, sp - 1) -- drop + elseif b1 == 20 then -- put: val i + local k = math.floor(c) + if k >= 0 and k < 32 then + trans[k + 1] = a + end + sp = math.max(0, sp - 2) + elseif b1 == 21 then -- get + local k = math.floor(c) + set(1, if k >= 0 and k < 32 then trans[k + 1] else 0) + elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2 + local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1) + set(4, if v1 <= v2 then s1 else s2) + elseif b1 == 23 then -- random (deterministic) + seed = (seed * 1103515245 + 12345) % 2147483648 + set(0, (seed % 65535 + 1) / 65536) + elseif b1 == 24 then + set(2, a * c) + elseif b1 == 26 then + set(1, math.sqrt(math.max(0, c))) + elseif b1 == 27 then + set(0, c) -- dup + elseif b1 == 28 then -- exch + if sp >= 2 then + s[sp - 1], s[sp] = s[sp], s[sp - 1] + end + elseif b1 == 29 then -- index + local k = math.floor(c) + local v = if k < 0 then S(top - 2) else S(top - 2 - k) + set(1, v) + elseif b1 == 30 then -- roll: n j + local n, j = math.floor(a), math.floor(c) + sp = math.max(0, sp - 2) + if n > 0 and n <= sp then + local base = sp - n + local tmp = table.create(n, 0) + for k = 0, n - 1 do + tmp[((k + j) % n) + 1] = s[base + k + 1] + end + for k = 0, n - 1 do + s[base + k + 1] = tmp[k + 1] + end + end + else + return nil, "unknown operator 12 " .. b1 + end + if sp > 48 then + return nil, "stack overflow" + end + end + elseif b0 >= 32 or b0 == 28 then -- operands + local v + if b0 == 28 then + v = uN(b, p, 2) + if v >= 32768 then + v -= 65536 + end + p += 2 + elseif b0 <= 246 then + v = b0 - 139 + elseif b0 <= 250 then + v = (b0 - 247) * 256 + u8(b, p) + 108 + p += 1 + elseif b0 <= 254 then + v = -(b0 - 251) * 256 - u8(b, p) - 108 + p += 1 + else -- 255: 16.16 fixed + v = uN(b, p, 4) + if v >= 2147483648 then + v -= 4294967296 + end + v /= 65536 + p += 4 + end + if sp >= 48 then + return nil, "operand stack overflow" + end + sp += 1 + s[sp] = v + clear = false + else + return nil, "reserved operator " .. b0 + end + if clear then + sp = 0 + end + end + return nil, "no endchar" +end + +return Cff diff --git a/src/Formats/codecs/Lzma/Crc64.luau b/src/Formats/codecs/Lzma/Crc64.luau new file mode 100644 index 0000000..19f682f --- /dev/null +++ b/src/Formats/codecs/Lzma/Crc64.luau @@ -0,0 +1,37 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit +-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws. +local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor +local readu8 = buffer.readu8 + +local THI, TLO = table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local hi, lo = 0, n + for _ = 1, 8 do + local low = band(lo, 1) + lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31)) + hi = rshift(hi, 1) + if low ~= 0 then + hi = bxor(hi, 0xC96C5795) + lo = bxor(lo, 0xD7870F42) + end + end + THI[n + 1], TLO[n + 1] = hi, lo +end + +local Crc64 = {} + +-- of(buf, offset, length) -> hi, lo +function Crc64.of(b: buffer, o: number, n: number): (number, number) + local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF + for i = o, o + n - 1 do + local idx = band(bxor(lo, readu8(b, i)), 255) + 1 + lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24))) + hi = bxor(THI[idx], rshift(hi, 8)) + end + return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF) +end + +return Crc64 diff --git a/src/Formats/codecs/Lzma/Decode.luau b/src/Formats/codecs/Lzma/Decode.luau new file mode 100644 index 0000000..51be654 --- /dev/null +++ b/src/Formats/codecs/Lzma/Decode.luau @@ -0,0 +1,492 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). +-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the +-- structure (probability model layout, state transitions, distance / length decoding) follows that document. +-- +-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last +-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep +-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by +-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. +-- +-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as +-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local rshift, band = bit32.rshift, bit32.band + +-- probability offsets (u16 entries) +local IS_MATCH = 0 -- 12 states x 16 pos states +local IS_REP = 192 +local IS_REP_G0 = 204 +local IS_REP_G1 = 216 +local IS_REP_G2 = 228 +local IS_REP0_LONG = 240 -- 12 x 16 +local POS_SLOT = 432 -- 4 x 64 +local SPEC_POS = 688 -- 115 +local ALIGN = 803 -- 16 +local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 +local REP_LEN = 1333 +local LITERAL = 1847 -- 0x300 << (lc + lp) + +local TOP = 16777216 -- 2^24 + +local Decode = {} + +export type State = { + out: buffer, + cap: number, + op: number, -- bytes decoded so far (the next write offset) + dictStart: number, -- the last dictionary reset: matches may not reach before it + maxBytes: number, + probs: buffer, + nprobs: number, + lc: number, + lp: number, + pb: number, + state: number, + rep0: number, + rep1: number, + rep2: number, + rep3: number, + remLen: number, -- a match cut by outEnd, finished by the next run + range: number, + code: number, +} + +-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap +function Decode.new(cap: number, maxBytes: number): State + local c = math.max(64, math.min(cap, maxBytes)) + return { + out = bcreate(c), + cap = c, + op = 0, + dictStart = 0, + maxBytes = maxBytes, + probs = bcreate(2), + nprobs = 0, + lc = 0, + lp = 0, + pb = 0, + state = 0, + rep0 = 0, + rep1 = 0, + rep2 = 0, + rep3 = 0, + remLen = 0, + range = 0xFFFFFFFF, + code = 0, + } +end + +-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) +function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) + if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then + return false, "bad lc / lp / pb" + end + st.lc, st.lp, st.pb = lc, lp, pb + local n = LITERAL + 0x300 * 2 ^ (lc + lp) + if blen(st.probs) < n * 2 then + st.probs = bcreate(n * 2) + end + st.nprobs = n + Decode.resetState(st) + return true, nil +end + +-- resetState(st): probabilities to 1/2, LZ state and reps to 0 +function Decode.resetState(st: State) + local p = st.probs + for i = 0, st.nprobs - 1 do + writeu16(p, i * 2, 1024) + end + st.state = 0 + st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 + st.remLen = 0 +end + +-- resetDict(st): matches may no longer reach before the current position +function Decode.resetDict(st: State) + st.dictStart = st.op + st.remLen = 0 +end + +-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes +function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) + if ip + 5 > iend then + return nil, "truncated range coder init" + end + if readu8(b, ip) ~= 0 then + return nil, "bad range coder init byte" + end + st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) + st.range = 0xFFFFFFFF + if st.code == st.range then + return nil, "bad range coder init" + end + return ip + 5, nil +end + +-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) +local function ensure(st: State, need: number): boolean + if need <= st.cap then + return true + end + if need > st.maxBytes then + return false + end + local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) + local nb = bcreate(c) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + st.cap = c + return true +end +Decode.ensure = ensure + +-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range +function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) + if not ensure(st, st.op + n) then + return false, "limit: output over maxBytes" + end + bcopy(st.out, st.op, b, ip, n) + st.op += n + return true, nil +end + +-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT +-- traces stay valid across calls; run() is not re-entrant, and never yields) +local EMPTY = bcreate(2) +local probs: buffer = EMPTY +local inb: buffer = EMPTY +local range, code, ip, iend, over = 0, 0, 0, 0, 0 + +-- decode one bit with the probability at index i +local function bit(i: number): number + local p = i * 2 + local prob = readu16(probs, p) + local bound = rshift(range, 11) * prob + local r + if code < bound then + range = bound + writeu16(probs, p, prob + rshift(2048 - prob, 5)) + r = 0 + else + range -= bound + code -= bound + writeu16(probs, p, prob - rshift(prob, 5)) + r = 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + return r +end + +local function tree(base: number, nbits: number): number + local m = 1 + for _ = 1, nbits do + m = m * 2 + bit(base + m) + end + return m - 2 ^ nbits +end + +local function reverse(base: number, nbits: number): number + local m = 1 + local sym = 0 + for i = 0, nbits - 1 do + local b = bit(base + m) + m = m * 2 + b + sym += b * 2 ^ i + end + return sym +end + +local function direct(nbits: number): number + local res = 0 + for _ = 1, nbits do + range = rshift(range, 1) + local b = 0 + if code >= range then + code -= range + b = 1 + end + res = res * 2 + b + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + return res +end + +local function length(base: number, posState: number): number + if bit(base) == 0 then + return tree(base + 2 + posState * 8, 3) + end + if bit(base + 1) == 0 then + return 8 + tree(base + 130 + posState * 8, 3) + end + return 16 + tree(base + 258, 8) +end + +-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end +-- marker). The range coder must have been initialised (rcInit). +function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) + probs = st.probs + inb = inb0 + iend = iend0 + local out = st.out + local cap = st.cap + local op = st.op + local dictStart = st.dictStart + range, code = st.range, st.code + ip = ip0 + over = 0 + local state = st.state + local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 + local lc = st.lc + local lcShift = 2 ^ (8 - lc) + local lpMask = 2 ^ st.lp - 1 + local pbMask = 2 ^ st.pb - 1 + local lcMul = 2 ^ lc + + local status: string? = nil + local msg: string? = nil + + -- a pending match from the previous call + local remLen = st.remLen + if remLen > 0 then + local n = math.min(remLen, outEnd - op) + if n > 0 then + if op + n > cap then + st.op = op + if not ensure(st, op + n) then + probs, inb = EMPTY, EMPTY + return nil, "limit: output over maxBytes" + end + out, cap = st.out, st.cap + end + local src = op - rep0 - 1 + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + op += n + remLen -= n + end + end + + while true do + if op >= outEnd then + status = "full" + break + end + if over > 0 then + msg = "truncated" + break + end + if op + 273 > cap then + st.op = op + if not ensure(st, math.min(op + 273, outEnd)) then + msg = "limit: output over maxBytes" + break + end + out, cap = st.out, st.cap + end + local pos = op - dictStart + local posState = band(pos, pbMask) + -- is match? (inlined bit) + local pidx = (IS_MATCH + state * 16 + posState) * 2 + local prob = readu16(probs, pidx) + local bound = rshift(range, 11) * prob + if code < bound then + range = bound + writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + -- literal + local prev = if op > dictStart then readu8(out, op - 1) else 0 + local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift) + local sym = 1 + if state >= 7 then + local mpos = op - rep0 - 1 + local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0 + repeat + local matchBit = band(rshift(matchByte, 7), 1) + matchByte *= 2 + local b = bit(base + (1 + matchBit) * 256 + sym) + sym = sym * 2 + b + if matchBit ~= b then + break + end + until sym >= 256 + end + while sym < 256 do + local p2 = (base + sym) * 2 + local pr = readu16(probs, p2) + local bd = rshift(range, 11) * pr + if code < bd then + range = bd + writeu16(probs, p2, pr + rshift(2048 - pr, 5)) + sym = sym * 2 + else + range -= bd + code -= bd + writeu16(probs, p2, pr - rshift(pr, 5)) + sym = sym * 2 + 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + writeu8(out, op, sym - 256) + op += 1 + state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6 + else + range -= bound + code -= bound + writeu16(probs, pidx, prob - rshift(prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + local len + if bit(IS_REP + state) == 0 then + -- simple match + len = length(LEN, posState) + state = if state < 7 then 7 else 10 + rep3, rep2, rep1 = rep2, rep1, rep0 + local lenState = if len < 3 then len else 3 + local slot = tree(POS_SLOT + lenState * 64, 6) + if slot < 4 then + rep0 = slot + else + local nd = slot // 2 - 1 + local dist = (2 + slot % 2) * 2 ^ nd + if slot < 14 then + dist += reverse(SPEC_POS + dist - slot, nd) + else + dist += direct(nd - 4) * 16 + dist += reverse(ALIGN, 4) + end + rep0 = dist + end + if rep0 == 0xFFFFFFFF then + status = "eos" + break + end + else + if bit(IS_REP_G0 + state) == 0 then + if bit(IS_REP0_LONG + state * 16 + posState) == 0 then + -- short rep: one byte at rep0 + if op == dictStart or rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + state = if state < 7 then 9 else 11 + writeu8(out, op, readu8(out, op - rep0 - 1)) + op += 1 + continue + end + else + local dist + if bit(IS_REP_G1 + state) == 0 then + dist = rep1 + else + if bit(IS_REP_G2 + state) == 0 then + dist = rep2 + else + dist = rep3 + rep3 = rep2 + end + rep2 = rep1 + end + rep1 = rep0 + rep0 = dist + end + len = length(REP_LEN, posState) + state = if state < 7 then 8 else 11 + end + -- copy len + 2 bytes from rep0 + 1 back + if rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + local n = len + 2 + local room = outEnd - op + if n > room then + remLen = n - room + n = room + end + local src = op - rep0 - 1 + if rep0 + 1 >= n then + bcopy(out, op, out, src, n) + else + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + end + op += n + end + end + st.op = op + st.range, st.code = range, code + st.state = state + st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 + st.remLen = remLen + probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + if msg then + return nil, msg + end + if over > 0 then + return nil, "truncated" + end + return status, ip +end + +-- finish(st) -> a buffer of exactly the decoded bytes +function Decode.finish(st: State): buffer + if st.cap == st.op then + return st.out + end + local b = bcreate(st.op) + bcopy(b, 0, st.out, 0, st.op) + return b +end + +return Decode diff --git a/src/Formats/codecs/Lzma/Filters.luau b/src/Formats/codecs/Lzma/Filters.luau new file mode 100644 index 0000000..60a5d59 --- /dev/null +++ b/src/Formats/codecs/Lzma/Filters.luau @@ -0,0 +1,177 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole +-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, +-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V. +-- Never throws: every access is inside [o, o + n). +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap + +local TWO32 = 4294967296 + +local Filters = {} + +local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } +local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } + +local function msbyte(b: number): boolean + return b == 0 or b == 0xFF +end + +-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) +function Filters.x86(b: buffer, o: number, n: number, start: number) + if n <= 4 then + return + end + local size = n - 4 + local prevPos = -1 + local prevMask = 0 + local i = 0 + while i < size do + local c = readu8(b, o + i) + if band(c, 0xFE) ~= 0xE8 then + i += 1 + continue + end + local d = i - prevPos + if d > 3 then + prevMask = 0 + else + prevMask = band(lshift(prevMask, d - 1), 7) + if prevMask ~= 0 then + local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask]) + if not MASK_ALLOWED[prevMask] or msbyte(bb) then + prevPos = i + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + continue + end + end + end + prevPos = i + if msbyte(readu8(b, o + i + 4)) then + local src = readu32(b, o + i + 1) + local dest + while true do + dest = (src - (start + i + 5)) % TWO32 + if prevMask == 0 then + break + end + local j = MASK_BITNUM[prevMask] * 8 + local bb = band(rshift(dest, 24 - j), 0xFF) + if not msbyte(bb) then + break + end + src = bxor(dest, 2 ^ (32 - j) - 1) + end + dest = band(dest, 0x01FFFFFF) + if band(dest, 0x01000000) ~= 0 then + dest = bor(dest, 0xFF000000) + end + writeu32(b, o + i + 1, dest) + i += 5 + else + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + end + end +end + +function Filters.arm(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + if readu8(b, o + i + 3) == 0xEB then + local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536 + addr = (addr * 4 - (start + i + 8)) % TWO32 + addr = rshift(addr, 2) + writeu8(b, o + i, band(addr, 255)) + writeu8(b, o + i + 1, band(rshift(addr, 8), 255)) + writeu8(b, o + i + 2, band(rshift(addr, 16), 255)) + end + i += 4 + end +end + +function Filters.armthumb(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) + if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then + local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2) + addr = (addr * 2 - (start + i + 4)) % TWO32 + addr = rshift(addr, 1) + writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7))) + writeu8(b, o + i, band(rshift(addr, 11), 255)) + writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7))) + writeu8(b, o + i + 2, band(addr, 255)) + i += 4 + else + i += 2 + end + end +end + +function Filters.powerpc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + if band(instr, 0xFC000003) == 0x48000001 then + instr = band(instr, 0x03FFFFFC) + instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC) + instr = bor(instr, 0x48000001) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +function Filters.sparc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + local top = rshift(instr, 22) + if top == 0x100 or top == 0x1FF then + instr = (instr * 4) % TWO32 + instr = (instr - (start + i)) % TWO32 + instr = rshift(instr, 2) + instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF)) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +function Filters.arm64(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local pc = (start + i) % TWO32 + local instr = readu32(b, o + i) + if rshift(instr, 26) == 0x25 then + local src = instr + local p = (TWO32 - rshift(pc, 2)) % TWO32 + writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF))) + elseif band(instr, 0x9F000000) == 0x90000000 then + local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC)) + if band(src + 0x00020000, 0x001C0000) == 0 then + local p = (TWO32 - rshift(pc, 12)) % TWO32 + local dest = (src + p) % TWO32 + local v = band(instr, 0x9000001F) + v = bor(v, lshift(band(dest, 3), 29)) + v = bor(v, lshift(band(dest, 0x0003FFFC), 3)) + v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000)) + writeu32(b, o + i, v) + end + end + i += 4 + end +end + +-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +function Filters.delta(b: buffer, o: number, n: number, dist: number) + for i = dist, n - 1 do + writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) + end +end + +return Filters diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/Lzma/init.luau new file mode 100644 index 0000000..f6f2825 --- /dev/null +++ b/src/Formats/codecs/Lzma/init.luau @@ -0,0 +1,601 @@ +--!strict +-- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): +-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only. +-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification +-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain). +-- +-- local Lzma = require("@formats/codecs/Lzma") +-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string +-- -- or { lc, lp, pb, dictSize } +-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks +-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) +-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) +-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) +-- +-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default +-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types +-- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC, +-- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws. +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Decode = require("@formats/codecs/Lzma/Decode") +local Filters = require("@formats/codecs/Lzma/Filters") +local Crc64 = require("@formats/codecs/Lzma/Crc64") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Lzma = {} + +local DEFAULT_MAX = 2 ^ 30 + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) +} +export type Props = { lc: number, lp: number, pb: number, dictSize: number? } + +local function toBuffer(b: any): buffer? + if type(b) == "string" then + return buffer.fromstring(b) + end + if type(b) ~= "buffer" then + return nil + end + return b +end + +local function range(b: buffer, off: number?, len: number?): (number?, number) + local n = buffer.len(b) + local o = off or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, 0 + end + local l = len or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, 0 + end + if o + l > n then + l = n - o + end + return o, l +end + +local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) + local b = toBuffer(buf) + if not b then + return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf)) + end + local o, l = range(b, offset, length) + if not o then + return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) + end + return b, o, l, nil +end + +local function maxOf(opts: Options?): number + local m = opts and opts.maxBytes + return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX +end + +-- a decoder message -> Err +local function fail(msg: any, at: number?): Err.Err + local s = tostring(msg) + local code = Err.CORRUPT + if string.sub(s, 1, 5) == "limit" then + code = Err.LIMIT + elseif string.find(s, "truncated", 1, true) then + code = Err.TRUNCATED + end + return Err.new(code, s, at) +end + +-- props byte -> lc, lp, pb | nil +local function propsByte(d: number): (number?, number, number) + if d >= 225 then + return nil, 0, 0 + end + return d % 9, (d // 9) % 5, d // 45 +end +Lzma.propsByte = propsByte + +-- ------------------------------------------------------------------------------------------------ LZMA +-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) +local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?) + local ip, ierr = Decode.rcInit(st, b, o, e) + if not ip then + return nil, fail(ierr, o) + end + local target = if unpackSize then st.op + unpackSize else math.huge + if unpackSize and target > st.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize)) + end + if unpackSize and not Decode.ensure(st, target) then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + local status, res = Decode.run(st, b, ip, e, target) + if not status then + return nil, fail(res, o) + end + if unpackSize and st.op ~= target then + return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o) + end + return res :: number, nil +end + +-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) + if not b then + return nil, aerr + end + local lc, lp, pb + if type(props) == "table" then + lc, lp, pb = props.lc, props.lp, props.pb + else + local pbuf = toBuffer(props) + if not pbuf or buffer.len(pbuf) < 1 then + return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }") + end + lc, lp, pb = propsByte(readu8(pbuf, 0)) + if not lc then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte") + end + end + if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad props") + end + if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize") + end + local max = maxOf(opts) + local st = Decode.new(if unpackSize then unpackSize else l * 4, max) + local ok, perr = Decode.setProps(st, lc, lp, pb) + if not ok then + return nil, Err.new(Err.CORRUPT, tostring(perr)) + end + local consumed, err = decodeLzma(st, b, o, o + l, unpackSize) + if not consumed then + return nil, err + end + return Decode.finish(st), consumed +end + +-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.alone", buf, offset, length) + if not b then + return nil, aerr + end + if l < 13 then + return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o) + end + local lo, hi = readu32(b, o + 5), readu32(b, o + 9) + local size: number? = nil + if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then + if hi >= 2 ^ 21 then + return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5) + end + size = hi * 4294967296 + lo + end + return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) +end + +-- ------------------------------------------------------------------------------------------------ LZMA2 +-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte +local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + local p = o + local needDict, needProps = true, true + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p) + end + local c = readu8(b, p) + if c == 0 then + return p + 1, nil + end + if c == 1 or c == 2 then + if p + 3 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + if c == 1 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if p + 3 + n > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p) + end + local ok, cerr = Decode.copy(st, n, b, p + 3) + if not ok then + return nil, fail(cerr, p) + end + st.remLen = 0 + p += 3 + n + elseif c >= 0x80 then + if p + 5 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1 + local mode = (c // 32) % 4 + local q = p + 5 + if mode == 3 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if mode >= 2 then + if q >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q) + end + local lc, lp, pb = propsByte(readu8(b, q)) + if not lc or lc + lp > 4 then + return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q) + end + Decode.setProps(st, lc, lp, pb) + needProps = false + q += 1 + elseif needProps then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p) + elseif mode == 1 then + Decode.resetState(st) + end + if q + psize > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q) + end + local target = st.op + usize + if target > st.maxBytes then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + Decode.ensure(st, target) + local ip, ierr = Decode.rcInit(st, b, q, q + psize) + if not ip then + return nil, fail(ierr, q) + end + local status, res = Decode.run(st, b, ip, q + psize, target) + if not status then + return nil, fail(res, q) + end + if status ~= "full" or st.op ~= target then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p) + end + p = q + psize + else + return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p) + end + end +end + +-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) + if not b then + return nil, aerr + end + local max = maxOf(opts) + local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max) + local consumed, err = decodeLzma2(st, b, o, o + l) + if not consumed then + return nil, err + end + if type(unpackSize) == "number" and st.op ~= unpackSize then + return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize)) + end + return Decode.finish(st), consumed +end + +-- ------------------------------------------------------------------------------------------------ filters +-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) +Lzma.FILTER = table.freeze({ + delta = 0x03, + x86 = 0x04, + powerpc = 0x05, + ia64 = 0x06, + arm = 0x07, + armthumb = 0x08, + sparc = 0x09, + arm64 = 0x0A, + riscv = 0x0B, + lzma2 = 0x21, +}) +local BCJ: { [number]: (buffer, number, number, number) -> () } = { + [0x04] = Filters.x86, + [0x05] = Filters.powerpc, + [0x07] = Filters.arm, + [0x08] = Filters.armthumb, + [0x09] = Filters.sparc, + [0x0A] = Filters.arm64, +} + +-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the +-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?) + local pb = toBuffer(props) + local plen = if pb then buffer.len(pb) else 0 + if id == 0x03 then + if plen ~= 1 then + return nil, Err.new(Err.CORRUPT, "bad delta filter properties") + end + Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) + return true + end + local f = BCJ[id] + if not f then + return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id)) + end + local start = 0 + if plen == 4 then + start = readu32(pb :: buffer, 0) + elseif plen ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") + end + f(b, o, n, start) + return true +end + +-- ------------------------------------------------------------------------------------------------ xz +local XZ_MAGIC = "\253" .. "7zXZ\0" +local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } + +-- vli(b, p, e) -> value, next | nil +local function vli(b: buffer, p: number, e: number): (number?, number) + local v, mul = 0, 1 + for i = 0, 8 do + if p + i >= e then + return nil, p + end + local c = readu8(b, p + i) + v += (c % 128) * mul + if c < 128 then + if c == 0 and i > 0 then + return nil, p -- non-minimal encoding + end + return v, p + i + 1 + end + mul *= 128 + end + return nil, p +end +Lzma.vli = vli + +local function crc(b: buffer, o: number, n: number): number + return Crc32.raw(b, o, n) +end + +-- one xz stream at o -> next offset | nil, Err (blocks appended to st) +local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + if o + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) + end + if buffer.readstring(b, o, 6) ~= XZ_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad xz magic", o) + end + if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then + return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6) + end + if crc(b, o + 6, 2) ~= readu32(b, o + 8) then + return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8) + end + local check = readu8(b, o + 7) + local csize = CHECK_SIZE[check] + local p = o + 12 + local records: { { number } } = {} + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block", p) + end + local hs = readu8(b, p) + if hs == 0 then + break -- the index + end + local hsize = (hs + 1) * 4 + if p + hsize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p) + end + if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then + return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p) + end + local flags = readu8(b, p + 1) + if flags % 64 >= 4 then + return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1) + end + local nfilters = flags % 4 + 1 + local q = p + 2 + local he = p + hsize - 4 + local csz, usz: number? = nil, nil + if flags >= 128 or (flags // 64) % 2 == 1 then + if (flags // 64) % 2 == 1 then + local v + v, q = vli(b, q, he) + if not v or v == 0 then + return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q) + end + csz = v + end + if flags >= 128 then + local v + v, q = vli(b, q, he) + if not v then + return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q) + end + usz = v + end + end + local filters: { { id: number, props: buffer } } = {} + for _ = 1, nfilters do + local id, psz + id, q = vli(b, q, he) + if not id then + return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q) + end + psz, q = vli(b, q, he) + if not psz or q + psz > he then + return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q) + end + local pr = buffer.create(psz) + buffer.copy(pr, 0, b, q, psz) + q += psz + table.insert(filters, { id = id, props = pr }) + end + for k = q, he - 1 do + if readu8(b, k) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k) + end + end + local last = filters[nfilters] + if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p) + end + for k = 1, nfilters - 1 do + local id = filters[k].id + if id ~= 0x03 and not BCJ[id] then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p) + end + end + -- data + local dstart = p + hsize + local ostart = st.op + local dend = if csz then dstart + csz else e + if dend > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart) + end + local cend, derr = decodeLzma2(st, b, dstart, dend) + if not cend then + return nil, derr + end + if csz and cend ~= dend then + return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart) + end + local un = st.op - ostart + if usz and un ~= usz then + return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart) + end + for k = nfilters - 1, 1, -1 do + local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props) + if not ok then + return nil, ferr + end + end + local unpadded = hsize + (cend - dstart) + csize + local pe = cend + while (pe - p) % 4 ~= 0 do + if pe >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe) + end + if readu8(b, pe) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe) + end + pe += 1 + end + if pe + csize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe) + end + if check == 1 then + if crc(st.out, ostart, un) ~= readu32(b, pe) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe) + end + elseif check == 4 then + local hi, lo = Crc64.of(st.out, ostart, un) + if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe) + end + end + table.insert(records, { unpadded, un }) + p = pe + csize + end + -- index + local ip = p + local count, q = vli(b, p + 1, e) + if not count or count ~= #records then + return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p) + end + for i = 1, count do + local a, u + a, q = vli(b, q, e) + if not a then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + u, q = vli(b, q, e) + if not u then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if a ~= records[i][1] or u ~= records[i][2] then + return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q) + end + end + while (q - ip) % 4 ~= 0 do + if q >= e or readu8(b, q) ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad xz index padding", q) + end + q += 1 + end + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if crc(b, ip, q - ip) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q) + end + q += 4 + local isize = q - ip + -- footer + if q + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q) + end + if crc(b, q + 4, 6) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q) + end + if (readu32(b, q + 4) + 1) * 4 ~= isize then + return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4) + end + if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then + return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8) + end + return q + 12, nil +end + +-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range +function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.xz", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local st = Decode.new(l * 4, maxOf(opts)) + local p = o + local nstreams = 0 + while true do + local nxt, err = xzStream(st, b, p, e) + if not nxt then + return nil, err + end + nstreams += 1 + p = nxt + -- stream padding: zero bytes in multiples of 4 + local z = p + while z < e and readu8(b, z) == 0 do + z += 1 + end + if z == e then + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + break + end + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + end + return Decode.finish(st), p +end + +-- isXz(buf, offset?) -> true when the bytes start an xz stream +function Lzma.isXz(b: buffer, o: number?): boolean + local off = o or 0 + return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC +end + +return Lzma diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/Raster.luau new file mode 100644 index 0000000..953336e --- /dev/null +++ b/src/Formats/codecs/Raster.luau @@ -0,0 +1,744 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and +-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / +-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an +-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed +-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. +-- +-- local R = require("@formats/codecs/Raster") +-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: +-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, +-- { op = "close" } } -- (the Font:outline() format) +-- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } }) +-- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty +-- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over) +-- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients) +-- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero) +-- +-- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are +-- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to +-- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling. +-- +-- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the +-- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths. +local Raster = {} + +local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt +local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8 +local bcreate = buffer.create + +export type Cmd = { op: string, [number]: number } +export type Path = { Cmd } +export type Transform = { number } +export type Mask = { x: number, y: number, width: number, height: number, coverage: buffer } +export type Options = { + transform: Transform?, -- default identity + rule: ("nonzero" | "evenodd")?, -- default "nonzero" + clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image) + tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1) + maxPixels: number?, -- largest mask (default 2^26) + opacity: number?, -- fill: multiplies the coverage (0..1, default 1) +} + +local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken + +-- ------------------------------------------------------------------------------------------------ transforms +Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) + +-- multiply(m, n) -> m * n (apply n first, then m) +function Raster.multiply(m: Transform, n: Transform): Transform + return { + m[1] * n[1] + m[3] * n[2], + m[2] * n[1] + m[4] * n[2], + m[1] * n[3] + m[3] * n[4], + m[2] * n[3] + m[4] * n[4], + m[1] * n[5] + m[3] * n[6] + m[5], + m[2] * n[5] + m[4] * n[6] + m[6], + } +end +function Raster.translate(tx: number, ty: number): Transform + return { 1, 0, 0, 1, tx, ty } +end +function Raster.scale(sx: number, sy: number?): Transform + return { sx, 0, 0, sy or sx, 0, 0 } +end +function Raster.rotate(radians: number): Transform + local c, s = math.cos(radians), math.sin(radians) + return { c, s, -s, c, 0, 0 } +end +-- invert(m) -> m^-1 | nil (singular) +function Raster.invert(m: Transform): Transform? + local det = m[1] * m[4] - m[2] * m[3] + if det == 0 or det ~= det then + return nil + end + local id = 1 / det + local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id + return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } +end +-- apply(m, x, y) -> x', y' +function Raster.apply(m: Transform, x: number, y: number): (number, number) + return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] +end + +-- ------------------------------------------------------------------------------------------------ path builder +local Builder = {} +Builder.__index = Builder +export type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) + +-- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path +-- takes a builder too) +function Raster.path(): Builder + return setmetatable({ cmds = {} :: Path }, Builder) +end +function Builder.moveTo(self: Builder, x: number, y: number): Builder + table.insert(self.cmds, { op = "moveTo", x, y }) + return self +end +function Builder.lineTo(self: Builder, x: number, y: number): Builder + table.insert(self.cmds, { op = "lineTo", x, y }) + return self +end +function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder + table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) + return self +end +function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder + table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) + return self +end +function Builder.close(self: Builder): Builder + table.insert(self.cmds, { op = "close" }) + return self +end +-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths +function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder + return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() +end +function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder + local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle + self:moveTo(cx + rx, cy) + self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry) + self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy) + self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry) + self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy) + return self:close() +end + +local function commands(path: any): Path? + if type(path) ~= "table" then + return nil + end + if type(path.cmds) == "table" then + return path.cmds + end + return path +end + +-- n numeric operands of a command, or nil +local function operands(c: any, n: number): boolean + if type(c) ~= "table" then + return false + end + for i = 1, n do + local v = c[i] + if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ flattening +-- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath +-- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty) +local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) + local cmds = commands(path) + local polys: { { number } } = {} + if not cmds then + return polys + end + local m = transform or Raster.IDENTITY + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then + return polys + end + local tol = tolerance or 0.1 + if type(tol) ~= "number" or not (tol > 0.001) then + tol = 0.1 + end + local cur: { number }? = nil + local px, py = 0, 0 -- current point (device) + local sx, sy = 0, 0 -- subpath start (device) + local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge + local function point(x: number, y: number) + local poly = cur :: { number } + local n = #poly + poly[n + 1] = x + poly[n + 2] = y + if x < bx0 then + bx0 = x + end + if x > bx1 then + bx1 = x + end + if y < by0 then + by0 = y + end + if y > by1 then + by1 = y + end + end + local function start(x: number, y: number) + if cur and #cur >= minLen then + table.insert(polys, cur) + end + cur = {} + point(x, y) + sx, sy = x, y + px, py = x, y + end + for _, cmd in cmds do + local op = if type(cmd) == "table" then cmd.op else nil + if op == "moveTo" then + if operands(cmd, 2) then + start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f) + end + elseif op == "lineTo" then + if operands(cmd, 2) then + if not cur then + start(px, py) + end + px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + point(px, py) + end + elseif op == "quadTo" then + if operands(cmd, 4) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2 + local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol)) + n = if n ~= n then 1 else max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2) + end + point(x2, y2) + px, py = x2, y2 + end + elseif op == "cubicTo" then + if operands(cmd, 6) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f + local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2 + local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3 + local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy)) + local n = ceil(sqrt(dd * 0.75 / tol)) + n = if n ~= n then 1 else max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t + point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3) + end + point(x3, y3) + px, py = x3, y3 + end + elseif op == "close" then + if cur then + if #cur >= minLen then + table.insert(polys, cur) + end + cur = nil + px, py = sx, sy + end + end + end + if cur and #cur >= minLen then + table.insert(polys, cur) + end + if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then + return polys + end + return polys, bx0, by0, bx1, by1 +end + +function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?) + return flatten(path, transform, tolerance, 6) +end + +-- ------------------------------------------------------------------------------------------------ accumulation +-- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area +-- each pixel gains (font-rs's draw_line) +local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) + if y0 == y1 then + return + end + local W = S - 2 + local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside) + local dir = 1 + if y0 > y1 then + dir = -1 + x0, x1 = x1, x0 + y0, y1 = y1, y0 + end + if y1 <= 0 or y0 >= H then + return + end + local dxdy = (x1 - x0) / (y1 - y0) + local x = x0 + if y0 < 0 then + x -= y0 * dxdy + end + local ystart = max(0, floor(y0)) + local yend = min(H, ceil(y1)) - 1 + for y = ystart, yend do + local ls = y * S + local dy = min(y + 1, y1) - max(y, y0) + local xnext = x + dxdy * dy + if xnext < xl then + xnext = xl + elseif xnext > xr then + xnext = xr + end + if x < xl then + x = xl + elseif x > xr then + x = xr + end + local dd = dy * dir + local xa, xb = x, xnext + if xa > xb then + xa, xb = xb, xa + end + local xaf = floor(xa) + local xai = xaf + local xbc = ceil(xb) + local xbi = xbc + if xbi <= xai + 1 then + local xmf = 0.5 * (x + xnext) - xaf + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd - dd * xmf) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf) + else + local s = 1 / (xb - xa) + local x0f = xa - xaf + local a0 = 0.5 * s * (1 - x0f) * (1 - x0f) + local x1f = xb - xbc + 1 + local am = 0.5 * s * x1f * x1f + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd * a0) + if xbi == xai + 2 then + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am)) + else + local a1 = s * (1.5 - x0f) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0)) + local ds = dd * s + for xi = xai + 2, xbi - 2 do + local q = (ls + xi) * 4 + writef32(acc, q, readf32(acc, q) + ds) + end + local a2 = a1 + (xbi - xai - 3) * s + local q = (ls + xbi - 1) * 4 + writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am)) + end + local q = (ls + xbi) * 4 + writef32(acc, q, readf32(acc, q) + dd * am) + end + x = xnext + end +end + +-- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the +-- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still +-- applies to the row) +local function clampx(x: number, W: number): number + return if x < 0 then 0 elseif x > W then W else x +end +local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number) + if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then + return -- horizontal, or non-finite (NaN fails every comparison) + end + if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then + return + end + local dx = x1 - x0 + local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none) + if dx ~= 0 then + local t0 = (0 - x0) / dx + local tw = (W - x0) / dx + if t0 > 0 and t0 < 1 then + ta = t0 + end + if tw > 0 and tw < 1 then + tb = tw + end + if ta > tb then + ta, tb = tb, ta + end + end + local dy = y1 - y0 + local px, py = x0, y0 + if ta < 1 then + local qx, qy = x0 + dx * ta, y0 + dy * ta + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + if tb < 1 then + local qx, qy = x0 + dx * tb, y0 + dy * tb + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) +end + +-- ------------------------------------------------------------------------------------------------ masks +-- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit") +function Raster.mask(path: any, opts: Options?): (Mask?, string?) + local o: Options = opts or {} + local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) + if not bx0 then + return nil + end + if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then + return nil, "coordinates out of range" + end + local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number) + local clip = o.clip + if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then + Y0 = max(Y0, floor(clip[2])) + Y1 = min(Y1, ceil(clip[4])) + X1 = min(X1, ceil(clip[3])) + local cx0 = floor(clip[1]) + X0 = max(X0, cx0) + end + local W, H = X1 - X0, Y1 - Y0 + if W <= 0 or H <= 0 then + return nil + end + local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26 + if W * H > maxPixels then + return nil, "limit" + end + local S = W + 2 + local acc = bcreate(S * H * 4) + for _, poly in polys do + local n = #poly + local lx, ly = poly[n - 1] - X0, poly[n] - Y0 + for i = 1, n - 1, 2 do + local x, y = poly[i] - X0, poly[i + 1] - Y0 + edge(acc, S, W, H, lx, ly, x, y) + lx, ly = x, y + end + end + local cov = bcreate(W * H) + local evenodd = o.rule == "evenodd" + for y = 0, H - 1 do + local sum = 0 + local ls = y * S + local os = y * W + for x = 0, W - 1 do + sum += readf32(acc, (ls + x) * 4) + local v = abs(sum) + if evenodd then + v = v % 2 + if v > 1 then + v = 2 - v + end + elseif v > 1 then + v = 1 + end + writeu8(cov, os + x, floor(v * 255 + 0.5)) + end + end + return { x = X0, y = Y0, width = W, height = H, coverage = cov } +end + +-- ------------------------------------------------------------------------------------------------ filling +-- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an +-- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in +-- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the +-- image; opts.opacity scales the coverage. +function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return false, "fill: expected an rgba8 image" + end + local iw, ih = img.width, img.height + local px = img.pixels + if buffer.len(px) < iw * ih * 4 then + return false, "fill: image pixels too short" + end + local o: Options = table.clone(opts or {}) + local clip = o.clip + if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then + o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) } + else + o.clip = { 0, 0, iw, ih } + end + local m, why = Raster.mask(path, o) + if not m then + return why == nil, why + end + local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1 + local fn: any = nil + local cr, cg, cb, ca = 0, 0, 0, 255 + if type(paint) == "function" then + fn = paint + elseif type(paint) == "table" then + cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0 + ca = tonumber(paint[4]) or 255 + else + return false, "fill: paint must be a colour or a function" + end + local cov = m.coverage + local mw = m.width + for y = 0, m.height - 1 do + local iy = m.y + y + for x = 0, mw - 1 do + local cv = readu8(cov, y * mw + x) + if cv > 0 then + local ix = m.x + x + local r, g, b, a = cr, cg, cb, ca + if fn then + local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5) + if not ok then + return false, "fill: paint function failed" + end + r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255 + end + local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity + if sa > 0 then + local p = (iy * iw + ix) * 4 + local da = readu8(px, p + 3) / 255 + local oa = sa + da * (1 - sa) + local k = da * (1 - sa) + writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5)) + writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5)) + writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5)) + writeu8(px, p + 3, floor(oa * 255 + 0.5)) + end + end + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ stroking +export type StrokeOptions = { + width: number?, -- default 1 + join: ("miter" | "round" | "bevel")?, -- default "miter" + cap: ("butt" | "round" | "square")?, -- default "butt" + miterLimit: number?, -- default 4 (SVG) + tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes + closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close") +} + +-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up +-- under the nonzero rule +local function polygon(out: Path, pts: { number }) + local n = #pts + if n < 6 then + return + end + local area = 0 + for i = 1, n - 1, 2 do + local j = if i + 2 > n then 1 else i + 2 + area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1] + end + if area == 0 then + return + end + if area > 0 then + table.insert(out, { op = "moveTo", pts[1], pts[2] }) + for i = 3, n - 1, 2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + else + table.insert(out, { op = "moveTo", pts[n - 1], pts[n] }) + for i = n - 3, 1, -2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + end + table.insert(out, { op = "close" }) +end + +local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) + local da = a1 - a0 + local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1)) + local n = max(1, min(256, ceil(abs(da) / max(step, 0.01)))) + for i = 0, n do + local t = a0 + da * i / n + table.insert(pts, cx + r * math.cos(t)) + table.insert(pts, cy + r * math.sin(t)) + end +end + +-- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own +-- coordinate space: transform it like the path). Dashes are the caller's job (split the path first). +function Raster.stroke(path: any, opts: StrokeOptions?): Path + local o: StrokeOptions = opts or {} + local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2 + local join = o.join or "miter" + local cap = o.cap or "butt" + local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4 + local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1 + local out: Path = {} + local cmds = commands(path) + if not cmds then + return out + end + -- subpaths with their closed flag (flatten loses it, so split here) + local subs: { { cmds: Path, closed: boolean } } = {} + local cur: Path? = nil + local lx, ly = 0, 0 + for _, c in cmds do + local op = if type(c) == "table" then c.op else nil + if op == "moveTo" and operands(c, 2) then + cur = { c } + table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) + lx, ly = c[1], c[2] + elseif op == "close" then + if cur then + subs[#subs].closed = true + cur = nil + end + elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then + if not cur then + cur = { { op = "moveTo", lx, ly } } + table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) + end + table.insert(cur :: Path, c) + end + end + for _, sub in subs do + local polys = flatten(sub.cmds, nil, tol, 4) + local pts = polys[1] + if not pts then + -- a degenerate subpath (a single point): round / square caps draw a dot + local m = sub.cmds[1] + if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then + local d = {} + if cap == "round" then + arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d) + else + d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw } + end + polygon(out, d) + end + continue + end + -- drop repeated points + local p: { number } = { pts[1], pts[2] } + for i = 3, #pts - 1, 2 do + if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then + table.insert(p, pts[i]) + table.insert(p, pts[i + 1]) + end + end + local closed = sub.closed + if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then + table.remove(p) + table.remove(p) + end + local n = #p // 2 + if n < 2 then + continue + end + local segs = if closed then n else n - 1 + -- segment bodies + local dirs: { number } = {} + for s = 0, segs - 1 do + local i, j = s, (s + 1) % n + local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2] + local dx, dy = x1 - x0, y1 - y0 + local len = sqrt(dx * dx + dy * dy) + local ux, uy = dx / len, dy / len + dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy + local nx, ny = -uy * hw, ux * hw + polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) + end + -- joins + local function joinAt(k: number, s0: number, s1: number) + local x, y = p[2 * k + 1], p[2 * k + 2] + local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] + local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2] + local cross = ax * by - ay * bx + if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then + return + end + -- the outer side: left normals when turning right (cross < 0) + local sgn = if cross < 0 then 1 else -1 + local n0x, n0y = -ay * hw * sgn, ax * hw * sgn + local n1x, n1y = -by * hw * sgn, bx * hw * sgn + if join == "round" then + local d = { x, y } + local a0 = math.atan2(n0y, n0x) + local a1 = math.atan2(n1y, n1x) + local da = a1 - a0 + while da > math.pi do + da -= 2 * math.pi + end + while da < -math.pi do + da += 2 * math.pi + end + arcPoints(x, y, hw, a0, a0 + da, tol, d) + polygon(out, d) + else + local cosT = ax * bx + ay * by -- angle between directions + local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge + if join == "miter" and miter <= miterLimit then + local mx, my = n0x + n1x, n0y + n1y + local ml = sqrt(mx * mx + my * my) + if ml > 1e-12 then + local scale = hw * miter / ml + polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y }) + return + end + end + polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y }) + end + end + if closed then + for k = 0, n - 1 do + joinAt(k, (k - 1) % n, k) + end + else + for k = 1, n - 2 do + joinAt(k, k - 1, k) + end + -- caps + if cap ~= "butt" then + for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do + local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] + local x, y = p[2 * k + 1], p[2 * k + 2] + local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards + local nx, ny = -uy * hw, ux * hw + if cap == "square" then + polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny }) + else + local d = {} + local a0 = math.atan2(ny, nx) + arcPoints(x, y, hw, a0, a0 - math.pi, tol, d) + polygon(out, d) + end + end + end + end + end + return out +end + +return Raster diff --git a/src/Formats/codecs/TrueType/Glyf.luau b/src/Formats/codecs/TrueType/Glyf.luau new file mode 100644 index 0000000..65392f6 --- /dev/null +++ b/src/Formats/codecs/TrueType/Glyf.luau @@ -0,0 +1,403 @@ +--!strict +-- codecs/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and +-- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / +-- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 +-- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point +-- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the +-- spec do not). No hinting. +-- +-- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +local Glyf = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 +local blen = buffer.len +local band = bit32.band + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b: buffer, o: number): number + if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b: buffer, o: number): number + local v = u16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function u32(b: buffer, o: number): number + return u16(b, o) * 65536 + u16(b, o + 2) +end + +export type Face = { + buf: buffer, + glyf: number, -- absolute offset of the glyf table + glyfLen: number, + loca: number, + locaLen: number, + longLoca: boolean, + numGlyphs: number, + [string]: any, +} + +-- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index +function Glyf.range(f: Face, g: number): (number?, number) + if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then + return nil, 0 + end + local a, z + if f.longLoca then + if (g + 2) * 4 > f.locaLen then + return nil, 0 + end + a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) + else + if (g + 2) * 2 > f.locaLen then + return nil, 0 + end + a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2 + end + if z <= a or z > f.glyfLen then + return nil, 0 + end + return f.glyf + a, z - a +end + +-- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) +function Glyf.bounds(f: Face, g: number): (number?, number, number, number) + local o, n = Glyf.range(f, g) + if not o or n < 10 then + return nil, 0, 0, 0 + end + local b = f.buf + return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) +end + +-- contours: { { xs, ys, on } } point lists in font units +type Contour = { x: { number }, y: { number }, on: { boolean } } + +local MAX_POINTS = 65536 + +local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?) + local e = o + len + local ends = table.create(nc) + local p = o + 10 + if p + nc * 2 + 2 > e then + return nil, "glyph header past the end" + end + local last = -1 + for i = 1, nc do + local v = u16(b, p) + if v < last then + return nil, "contour end points out of order" + end + ends[i] = v + last = v + p += 2 + end + local n = last + 1 + if n > MAX_POINTS then + return nil, "too many points" + end + local ins = u16(b, p) + p += 2 + ins + if p > e then + return nil, "instructions past the end" + end + -- flags + local flags = table.create(n, 0) + local i = 1 + while i <= n do + if p >= e then + return nil, "flags past the end" + end + local fl = readu8(b, p) + p += 1 + flags[i] = fl + i += 1 + if band(fl, 8) ~= 0 then + if p >= e then + return nil, "flags past the end" + end + local rep = readu8(b, p) + p += 1 + for _ = 1, rep do + if i > n then + break + end + flags[i] = fl + i += 1 + end + end + end + -- coordinates + local xs = table.create(n, 0) + local x = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 2) ~= 0 then + if p >= e then + return nil, "x coordinates past the end" + end + local d = readu8(b, p) + p += 1 + x += if band(fl, 16) ~= 0 then d else -d + elseif band(fl, 16) == 0 then + if p + 2 > e then + return nil, "x coordinates past the end" + end + x += i16(b, p) + p += 2 + end + xs[k] = x + end + local ys = table.create(n, 0) + local y = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 4) ~= 0 then + if p >= e then + return nil, "y coordinates past the end" + end + local d = readu8(b, p) + p += 1 + y += if band(fl, 32) ~= 0 then d else -d + elseif band(fl, 32) == 0 then + if p + 2 > e then + return nil, "y coordinates past the end" + end + y += i16(b, p) + p += 2 + end + ys[k] = y + end + local out: { Contour } = table.create(nc) + local s = 1 + for c = 1, nc do + local z = ends[c] + 1 + local cx, cy, con = {}, {}, {} + for k = s, z do + table.insert(cx, xs[k]) + table.insert(cy, ys[k]) + table.insert(con, band(flags[k], 1) ~= 0) + end + out[c] = { x = cx, y = cy, on = con } + s = z + 1 + end + return out, nil +end + +local contours: (f: Face, g: number, depth: number) -> ({ Contour }?, string?) + +local function composite(f: Face, o: number, len: number, depth: number): ({ Contour }?, string?) + local b = f.buf + local e = o + len + local p = o + 10 + local out: { Contour } = {} + local total = 0 + while true do + if p + 4 > e then + return nil, "component past the end" + end + local flags = u16(b, p) + local gi = u16(b, p + 2) + p += 4 + local a1, a2 + if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS + if p + 4 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = i16(b, p), i16(b, p + 2) + else + a1, a2 = u16(b, p), u16(b, p + 2) + end + p += 4 + else + if p + 2 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = readi8(b, p), readi8(b, p + 1) + else + a1, a2 = readu8(b, p), readu8(b, p + 1) + end + p += 2 + end + local m1, m2, m3, m4 = 1, 0, 0, 1 + if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE + m1 = i16(b, p) / 16384 + m4 = m1 + p += 2 + elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE + m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384 + p += 4 + elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO + m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384 + p += 8 + end + if p > e then + return nil, "component past the end" + end + local child, err = contours(f, gi, depth + 1) + if not child then + return nil, err + end + -- transform the child's points + local tc: { Contour } = table.create(#child) + for i, c in child do + local nx, ny = table.create(#c.x), table.create(#c.x) + for k = 1, #c.x do + local x, y = c.x[k], c.y[k] + nx[k] = m1 * x + m3 * y + ny[k] = m2 * x + m4 * y + end + tc[i] = { x = nx, y = ny, on = c.on } + end + local dx, dy + if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES + dx, dy = a1, a2 + if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET + dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2 + end + else + -- point matching: parent point a1 (in what is composed so far) meets child point a2 + local function pt(list: { Contour }, idx: number): (number?, number) + local k = idx + for _, c in list do + local n = #c.x + if k < n then + return c.x[k + 1], c.y[k + 1] + end + k -= n + end + return nil, 0 + end + local px, py = pt(out, a1) + local cx, cy = pt(tc, a2) + if not px or not cx then + return nil, "component point index out of range" + end + dx, dy = px - cx, py - (cy :: number) + end + for _, c in tc do + for k = 1, #c.x do + c.x[k] += dx + c.y[k] += dy + end + total += #c.x + table.insert(out, c) + end + if total > MAX_POINTS then + return nil, "too many points" + end + if band(flags, 0x20) == 0 then -- MORE_COMPONENTS + break + end + end + return out, nil +end + +contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) + if depth > 8 then + return nil, "composite glyphs nested too deep" + end + local o, len = Glyf.range(f, g) + if not o then + return {}, nil -- empty glyph (space) + end + if len < 10 then + return nil, "glyph header past the end" + end + local nc = i16(f.buf, o) + if nc >= 0 then + return simple(f.buf, o, len, nc) + end + return composite(f, o, len, depth) +end + +-- outline(f, g) -> path commands (codecs/Raster format, font units, y up) | nil, message +function Glyf.outline(f: Face, g: number): ({ any }?, string?) + local cs, err = contours(f, g, 0) + if not cs then + return nil, err + end + local cmds = {} + for _, c in cs do + local n = #c.x + if n < 2 then + continue + end + local xs, ys, on = c.x, c.y, c.on + -- the start: the first on-curve point, or the midpoint of the first two off-curve points + local s = 0 + for k = 1, n do + if on[k] then + s = k + break + end + end + local sx, sy + if s == 0 then + sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2 + s = 1 + -- all off-curve: start at the implied midpoint between the last and the first, then walk from 1 + table.insert(cmds, { op = "moveTo", sx, sy }) + local cx, cy = xs[1], ys[1] + for k = 2, n do + local x, y = xs[k], ys[k] + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + cx, cy = x, y + end + table.insert(cmds, { op = "quadTo", cx, cy, sx, sy }) + table.insert(cmds, { op = "close" }) + continue + end + sx, sy = xs[s], ys[s] + table.insert(cmds, { op = "moveTo", sx, sy }) + local off = false + local cx, cy = 0, 0 + for i = 1, n do + local k = (s + i - 1) % n + 1 + local x, y, isOn = xs[k], ys[k], on[k] + if i == n then + x, y, isOn = sx, sy, true -- back to the start + end + if isOn then + if off then + table.insert(cmds, { op = "quadTo", cx, cy, x, y }) + elseif i < n then + table.insert(cmds, { op = "lineTo", x, y }) + end + off = false + else + if off then + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + end + cx, cy = x, y + off = true + end + end + table.insert(cmds, { op = "close" }) + end + return cmds, nil +end + +-- points(f, g) -> the number of points and contours (for tests) +function Glyf.counts(f: Face, g: number): (number, number) + local cs = contours(f, g, 0) + if not cs then + return 0, 0 + end + local n = 0 + for _, c in cs do + n += #c.x + end + return n, #cs +end + +return Glyf diff --git a/src/Formats/codecs/TrueType/Tables.luau b/src/Formats/codecs/TrueType/Tables.luau new file mode 100644 index 0000000..87e5833 --- /dev/null +++ b/src/Formats/codecs/TrueType/Tables.luau @@ -0,0 +1,535 @@ +--!strict +-- codecs/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode +-- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair +-- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), +-- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public +-- domain / MIT) as a reference for cmap 4 and the GPOS walk. +-- +-- Never throws: every read is range-checked (out of range reads as 0). +local Tables = {} + +local readu8 = buffer.readu8 +local blen = buffer.len +local band = bit32.band + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b: buffer, o: number): number + if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b: buffer, o: number): number + local v = u16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function u32(b: buffer, o: number): number + return u16(b, o) * 65536 + u16(b, o + 2) +end +Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 + +-- ------------------------------------------------------------------------------------------------ cmap +export type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } + +-- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac +function Tables.cmap(b: buffer, o: number, n: number): Cmap? + local count = u16(b, o + 2) + local best, bestRank, symbol = -1, 0, false + for i = 0, count - 1 do + local r = o + 4 + i * 8 + if r + 8 > o + n then + break + end + local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4) + local at = o + off + if off >= n then + continue + end + local fmt = u16(b, at) + local rank = 0 + if pid == 3 and eid == 10 then + rank = 6 + elseif pid == 0 and (eid == 4 or eid == 6) then + rank = 5 + elseif pid == 3 and eid == 1 then + rank = 4 + elseif pid == 0 and fmt ~= 14 then + rank = 3 + elseif pid == 3 and eid == 0 then + rank = 2 + elseif pid == 1 and eid == 0 then + rank = 1 + end + if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then + rank = 0 + end + if rank > bestRank then + best, bestRank, symbol = at, rank, pid == 3 and eid == 0 + end + end + if best < 0 then + return nil + end + return { buf = b, at = best, format = u16(b, best), symbol = symbol } +end + +local function lookup(c: Cmap, cp: number): number + local b, t, fmt = c.buf, c.at, c.format + if fmt == 0 then + return if cp < 256 then u8(b, t + 6 + cp) else 0 + elseif fmt == 6 then + local first, count = u16(b, t + 6), u16(b, t + 8) + if cp >= first and cp < first + count then + return u16(b, t + 10 + (cp - first) * 2) + end + return 0 + elseif fmt == 10 then + local first, count = u32(b, t + 12), u32(b, t + 16) + if cp >= first and cp < first + count then + return u16(b, t + 20 + (cp - first) * 2) + end + return 0 + elseif fmt == 4 then + if cp > 0xFFFF then + return 0 + end + local segX2 = u16(b, t + 6) + local segs = segX2 // 2 + local ends = t + 14 + -- binary search for the first segment whose end >= cp + local lo, hi = 0, segs - 1 + while lo < hi do + local mid = (lo + hi) // 2 + if u16(b, ends + mid * 2) < cp then + lo = mid + 1 + else + hi = mid + end + end + if segs == 0 or u16(b, ends + lo * 2) < cp then + return 0 + end + local starts = ends + segX2 + 2 + local start = u16(b, starts + lo * 2) + if cp < start then + return 0 + end + local deltaAt = starts + segX2 + lo * 2 + local delta = u16(b, deltaAt) + local rangeAt = deltaAt + segX2 + local ro = u16(b, rangeAt) + if ro == 0 then + return (cp + delta) % 65536 + end + local g = u16(b, rangeAt + ro + (cp - start) * 2) + if g == 0 then + return 0 + end + return (g + delta) % 65536 + elseif fmt == 12 or fmt == 13 then + local n = u32(b, t + 12) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local g = t + 16 + mid * 12 + local s, e = u32(b, g), u32(b, g + 4) + if cp < s then + hi = mid - 1 + elseif cp > e then + lo = mid + 1 + else + local gid = u32(b, g + 8) + return if fmt == 12 then gid + cp - s else gid + end + end + return 0 + end + return 0 +end + +-- glyph(cmap, codepoint) -> glyph index (0 = .notdef) +function Tables.glyph(c: Cmap?, cp: number): number + if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then + return 0 + end + local g = lookup(c, cp) + if g == 0 and c.symbol and cp < 256 then + g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes + end + return g +end + +-- ------------------------------------------------------------------------------------------------ kern +-- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } +function Tables.kern(b: buffer, o: number, n: number): { [number]: number } + local pairs: { [number]: number } = {} + local e = o + n + local apple = u32(b, o) == 0x00010000 + local count = if apple then u32(b, o + 4) else u16(b, o + 2) + local p = if apple then o + 8 else o + 4 + for _ = 1, math.min(count, 64) do + if p + 6 > e then + break + end + local len, fmt, horizontal, cross, minimum, hdr + if apple then + len = u32(b, p) + local cov = u16(b, p + 4) + fmt = band(cov, 0xFF) + horizontal = band(cov, 0x8000) == 0 + cross = band(cov, 0x4000) ~= 0 + minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable + hdr = 8 + else + len = u16(b, p + 2) + local cov = u16(b, p + 4) + fmt = cov // 256 + horizontal = band(cov, 1) ~= 0 + minimum = band(cov, 2) ~= 0 + cross = band(cov, 4) ~= 0 + hdr = 6 + end + if fmt == 0 and horizontal and not cross and not minimum then + local np = u16(b, p + hdr) + local q = p + hdr + 8 + for k = 0, np - 1 do + local r = q + k * 6 + if r + 6 > e then + break + end + local key = u16(b, r) * 65536 + u16(b, r + 2) + pairs[key] = (pairs[key] or 0) + i16(b, r + 4) + end + end + if len < hdr then + break + end + -- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then + if not apple and len < hdr + 8 then + break + end + p += len + end + return pairs +end + +-- ------------------------------------------------------------------------------------------------ GPOS +local function popcount(v: number): number + local c = 0 + while v ~= 0 do + c += band(v, 1) + v = bit32.rshift(v, 1) + end + return c +end + +-- coverage index of glyph g in the Coverage table at t, or -1 +local function coverage(b: buffer, t: number, g: number): number + local fmt = u16(b, t) + if fmt == 1 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local v = u16(b, t + 4 + mid * 2) + if g < v then + hi = mid - 1 + elseif g > v then + lo = mid + 1 + else + return mid + end + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + g - s + end + end + end + return -1 +end + +local function classOf(b: buffer, t: number, g: number): number + local fmt = u16(b, t) + if fmt == 1 then + local s, n = u16(b, t + 2), u16(b, t + 4) + if g >= s and g < s + n then + return u16(b, t + 6 + (g - s) * 2) + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + end + end + end + return 0 +end + +-- the x advance adjustment in a value record with format vf at r +local function xAdvance(b: buffer, r: number, vf: number): number + if band(vf, 4) == 0 then + return 0 + end + return i16(b, r + 2 * popcount(band(vf, 3))) +end + +-- one PairPos subtable: (applies, value) +local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number) + local fmt = u16(b, t) + local ci = coverage(b, t + u16(b, t + 2), l) + if ci < 0 then + return false, 0 + end + local vf1, vf2 = u16(b, t + 4), u16(b, t + 6) + local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF)) + if fmt == 1 then + local count = u16(b, t + 8) + if ci >= count then + return false, 0 + end + local ps = t + u16(b, t + 10 + ci * 2) + local n = u16(b, ps) + local rec = 2 + s1 + s2 + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local q = ps + 2 + mid * rec + local g = u16(b, q) + if r < g then + hi = mid - 1 + elseif r > g then + lo = mid + 1 + else + return true, xAdvance(b, q + 2, vf1) + end + end + return false, 0 + elseif fmt == 2 then + local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10) + local n1, n2 = u16(b, t + 12), u16(b, t + 14) + local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r) + if c1 >= n1 or c2 >= n2 then + return false, 0 + end + local q = t + 16 + (c1 * n2 + c2) * (s1 + s2) + return true, xAdvance(b, q, vf1) + end + return false, 0 +end + +export type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets + +-- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) +function Tables.gpos(b: buffer, o: number, n: number): Gpos? + if n < 10 or u16(b, o) ~= 1 then + return nil + end + local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8) + local want: { [number]: boolean } = {} + local any = false + local nf = u16(b, fl) + for i = 0, nf - 1 do + local r = fl + 2 + i * 6 + if u32(b, r) == 0x6B65726E then -- "kern" + local f = fl + u16(b, r + 4) + for k = 0, u16(b, f + 2) - 1 do + want[u16(b, f + 4 + k * 2)] = true + any = true + end + end + end + if not any then + return nil + end + local lookups: { { number } } = {} + local nl = u16(b, ll) + for i = 0, nl - 1 do + if want[i] then + local lt = ll + u16(b, ll + 2 + i * 2) + local ty = u16(b, lt) + local subs: { number } = {} + for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do + local st = lt + u16(b, lt + 6 + k * 2) + local sty = ty + if ty == 9 and u16(b, st) == 1 then -- extension + sty = u16(b, st + 2) + st += u32(b, st + 4) + end + if sty == 2 then + table.insert(subs, st) + end + end + if #subs > 0 then + table.insert(lookups, subs) + end + end + end + if #lookups == 0 then + return nil + end + return { buf = b, subtables = lookups } +end + +-- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) +function Tables.gposKern(g: Gpos, l: number, r: number): number + local total = 0 + for _, subs in g.subtables do + for _, st in subs do + local applies, v = pairPos(g.buf, st, l, r) + if applies then + total += v + break + end + end + end + return total +end + +-- ------------------------------------------------------------------------------------------------ name, OS/2 +local MAC_ROMAN_HIGH = { + 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, + 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, + 0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8, + 0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8, + 0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, + 0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7, +} + +local function utf16be(b: buffer, o: number, n: number): string + local out = {} + local k = 0 + while k + 1 < n do + local c = u16(b, o + k) + k += 2 + if c >= 0xD800 and c < 0xDC00 and k + 1 < n then + local lo = u16(b, o + k) + if lo >= 0xDC00 and lo < 0xE000 then + c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00) + k += 2 + end + end + if c >= 0xD800 and c < 0xE000 then + c = 0xFFFD + end + table.insert(out, utf8.char(c)) + end + return table.concat(out) +end + +local function macRoman(b: buffer, o: number, n: number): string + local out = {} + for k = 0, n - 1 do + local c = u8(b, o + k) + table.insert(out, utf8.char(if c < 128 then c else MAC_ROMAN_HIGH[c - 127])) + end + return table.concat(out) +end + +local NAME_IDS = { + [0] = "copyright", + [1] = "family", + [2] = "style", + [3] = "uniqueId", + [4] = "fullName", + [5] = "version", + [6] = "postScriptName", + [7] = "trademark", + [8] = "manufacturer", + [9] = "designer", + [10] = "description", + [11] = "vendorUrl", + [12] = "designerUrl", + [13] = "license", + [14] = "licenseUrl", + [16] = "typographicFamily", + [17] = "typographicStyle", +} + +-- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) +function Tables.names(b: buffer, o: number, n: number): { [string]: string } + local out: { [string]: string } = {} + local rank: { [string]: number } = {} + local count, strings = u16(b, o + 2), o + u16(b, o + 4) + for i = 0, math.min(count, 4096) - 1 do + local r = o + 6 + i * 12 + if r + 12 > o + n then + break + end + local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6) + local len, off = u16(b, r + 8), u16(b, r + 10) + local key = NAME_IDS[nid] + if key and strings + off + len <= o + n then + local rk, s = 0, nil + if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then + rk = if lang == 0x409 then 4 else 2 + s = utf16be(b, strings + off, len) + elseif pid == 0 then + rk = 3 + s = utf16be(b, strings + off, len) + elseif pid == 1 and eid == 0 then + rk = if lang == 0 then 1 else 0.5 + s = macRoman(b, strings + off, len) + end + if s and rk > (rank[key] or 0) then + out[key] = s + rank[key] = rk + end + end + end + return out +end + +-- os2(OS/2 table) -> the commonly used fields +function Tables.os2(b: buffer, o: number, n: number): { [string]: number } + local t: { [string]: number } = { + version = u16(b, o), + xAvgCharWidth = i16(b, o + 2), + weightClass = u16(b, o + 4), + widthClass = u16(b, o + 6), + fsType = u16(b, o + 8), + } + if n >= 78 then + t.fsSelection = u16(b, o + 62) + t.firstChar = u16(b, o + 64) + t.lastChar = u16(b, o + 66) + t.typoAscender = i16(b, o + 68) + t.typoDescender = i16(b, o + 70) + t.typoLineGap = i16(b, o + 72) + t.winAscent = u16(b, o + 74) + t.winDescent = u16(b, o + 76) + end + if n >= 96 and t.version >= 2 then + t.xHeight = i16(b, o + 86) + t.capHeight = i16(b, o + 88) + end + return t +end + +return Tables diff --git a/src/Formats/codecs/TrueType/init.luau b/src/Formats/codecs/TrueType/init.luau new file mode 100644 index 0000000..4e7948d --- /dev/null +++ b/src/Formats/codecs/TrueType/init.luau @@ -0,0 +1,338 @@ +--!strict +-- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +-- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines +-- (codecs/TrueType/Glyf for glyf, codecs/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), +-- names, and rasterize(glyph, px) through codecs/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all +-- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean +-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/Raster instead of stb's. +-- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), +-- colour layers (COLR), GSUB substitutions. +-- +-- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err +-- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units +-- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo +-- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) +-- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) +-- +-- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Raster = require("@formats/codecs/Raster") +local Cff = require("@formats/codecs/Cff") +local Glyf = require("@formats/codecs/TrueType/Glyf") +local Tables = require("@formats/codecs/TrueType/Tables") + +local TrueType = {} + +local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32 + +local function tag(b: buffer, o: number): string + if o < 0 or o + 4 > buffer.len(b) then + return "" + end + return buffer.readstring(b, o, 4) +end + +-- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) +function TrueType.count(b: buffer, offset: number?): number + local o = offset or 0 + local t = tag(b, o) + if t == "ttcf" then + return u32(b, o + 8) + end + if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then + return 1 + end + return 0 +end + +-- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir +function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?) + local n = u16(b, dir + 4) + if dir + 12 + n * 16 > limit then + return nil, "table directory past the end" + end + local out: { [string]: { number } } = {} + for i = 0, n - 1 do + local r = dir + 12 + i * 16 + local t = tag(b, r) + local off, len = u32(b, r + 8), u32(b, r + 12) + if file + off + len <= limit then + out[t] = { file + off, len } + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ the Font value +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return Tables.glyph(self._cmap, cp) +end + +function Face.advance(self: any, g: number): number + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh = self._numHMetrics + if nh == 0 then + return 0 + end + local h = self._hmtx + return u16(self._buf, h + 4 * math.min(g, nh - 1)) +end + +function Face.leftSideBearing(self: any, g: number): number + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh, h = self._numHMetrics, self._hmtx + if g < nh then + return i16(self._buf, h + 4 * g + 2) + end + return i16(self._buf, h + 4 * nh + 2 * (g - nh)) +end + +function Face.kern(self: any, a: number, b: number): number + if type(a) ~= "number" or type(b) ~= "number" then + return 0 + end + local key = a * 65536 + b + local cache = self._kernCache + local v = cache[key] + if v then + return v + end + v = 0 + if self._gpos then + v = Tables.gposKern(self._gpos, a, b) + end + if v == 0 and self._kern then + v = self._kern[key] or 0 + end + cache[key] = v + return v +end + +-- kernCodepoints(a, b) -> kern between two code points +function Face.kernCodepoints(self: any, a: number, b: number): number + return self:kern(self:glyphIndex(a), self:glyphIndex(b)) +end + +function Face.outline(self: any, g: number): { any }? + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then + return nil + end + local ok, cmds, err = pcall(function() + if self._cff then + return Cff.outline(self._cff, g) + end + return Glyf.outline(self._glyf, g) + end) + if not ok then + self.meta.lastError = tostring(cmds) + return nil + end + if not cmds then + self.meta.lastError = err + end + return cmds +end + +-- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph +function Face.bounds(self: any, g: number): (number?, number, number, number) + local cmds = self:outline(g) + if not cmds then + return nil, 0, 0, 0 + end + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, c in cmds do + for i = 1, #c - 1, 2 do + local x, y = c[i], c[i + 1] + x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y) + end + end + if x0 > x1 then + return nil, 0, 0, 0 + end + return x0, y0, x1, y1 +end + +-- scale(px) -> pixels per font unit for an em of px pixels +function Face.scale(self: any, px: number): number + return px / self.unitsPerEm +end + +export type RasterOptions = { + scaleX: number?, -- pixels per font unit (default px / unitsPerEm); scaleY likewise + scaleY: number?, + shiftX: number?, -- subpixel shift (pixels) + shiftY: number?, +} + +-- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; +-- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty +-- glyphs give a 0 x 0 image. +function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image? + if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local cmds = self:outline(g) + if not cmds then + return nil + end + local o = opts or {} + local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm + local sy = if type(o.scaleY) == "number" then o.scaleY else sx + local tx, ty = o.shiftX or 0, o.shiftY or 0 + local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left = 0 + img.meta.top = 0 + end + img.meta.advance = self:advance(g) * sx + img.meta.glyph = g + return img +end + +-- ------------------------------------------------------------------------------------------------ parsing +export type Options = { index: number? } -- the font in a collection (default 0) + +-- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err +function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) + local b = buf + local file = offset or 0 + local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file))) + if limit - file < 12 then + return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file) + end + local dir = file + local index = (opts and opts.index) or 0 + local count = TrueType.count(b, file) + if tag(b, file) == "ttcf" then + if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count)) + end + dir = file + u32(b, file + 12 + index * 4) + if dir + 12 > limit then + return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file) + end + elseif count == 0 then + return nil, Err.new(Err.CORRUPT, "not an sfnt font", file) + end + local sfntTag = tag(b, dir) + if sfntTag == "typ1" then + return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir) + end + local t, terr = TrueType.tables(b, file, dir, limit) + if not t then + return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir) + end + for _, need in { "head", "hhea", "maxp", "hmtx" } do + if not t[need] then + return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir) + end + end + local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1] + if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then + return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir) + end + local upem = u16(b, head + 18) + if upem < 16 or upem > 16384 then + return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18) + end + local numGlyphs = u16(b, maxp + 4) + local nh = math.min(u16(b, hhea + 34), numGlyphs) + if nh * 4 > t.hmtx[2] then + nh = t.hmtx[2] // 4 + end + local font: any = setmetatable({ + kind = "font", + info = {}, + unitsPerEm = upem, + ascent = i16(b, hhea + 4), + descent = i16(b, hhea + 6), + lineGap = i16(b, hhea + 8), + numGlyphs = numGlyphs, + bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) }, + pages = nil, + meta = {}, + _buf = b, + _hmtx = hmtx, + _numHMetrics = nh, + _kernCache = {}, + }, Face) + -- outlines + if t.glyf and t.loca then + font._glyf = { + buf = b, + glyf = t.glyf[1], + glyfLen = t.glyf[2], + loca = t.loca[1], + locaLen = t.loca[2], + longLoca = i16(b, head + 50) ~= 0, + numGlyphs = numGlyphs, + } + font.meta.outlines = "truetype" + elseif t["CFF "] then + local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2]) + if not cff then + local code = if cerr and string.find(cerr, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT + return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1]) + end + font._cff = cff + font.meta.outlines = "cff" + elseif t.CFF2 then + return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir) + else + return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) + end + -- cmap, kerning, names, OS/2, post + if t.cmap then + font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) + end + if t.kern then + font._kern = Tables.kern(b, t.kern[1], t.kern[2]) + end + if t.GPOS then + font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2]) + end + if t.name then + local names = Tables.names(b, t.name[1], t.name[2]) + for k, v in names do + font.info[k] = v + end + font.info.family = names.typographicFamily or names.family + font.info.style = names.typographicStyle or names.style + end + if t["OS/2"] and t["OS/2"][2] >= 10 then + font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2]) + end + if t.post and t.post[2] >= 16 then + local p = t.post[1] + font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536 + font.meta.underlinePosition = i16(b, p + 8) + font.meta.underlineThickness = i16(b, p + 10) + font.meta.fixedPitch = u32(b, p + 12) ~= 0 + end + local tags = {} + for k in t do + table.insert(tags, k) + end + table.sort(tags) + font.meta.tables = tags + font.meta.sfnt = if sfntTag == "OTTO" then "OTTO" else "TrueType" + font.meta.collection = if count > 1 or tag(b, file) == "ttcf" then { index = index, count = count } else nil + return font, nil +end + +return TrueType diff --git a/src/Formats/codecs/Zstd/Decode.luau b/src/Formats/codecs/Zstd/Decode.luau new file mode 100644 index 0000000..7ad77d5 --- /dev/null +++ b/src/Formats/codecs/Zstd/Decode.luau @@ -0,0 +1,980 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the +-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks, +-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed / +-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID). +-- +-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's +-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at +-- byte (o - n) / 8, bits before the stream start read as zeros. +-- +-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset. +local Xxh64 = require("@formats/codecs/Zstd/Xxh64") + +local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local MAGIC = 0xFD2FB528 +local BLOCK_MAX = 131072 + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ tables +-- literal length / match length codes: baseline, extra bits (index = code + 1) +local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } +local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } +local ML_BASE = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539, +} +local ML_BITS = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 } +local ML_DEFAULT = { + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, +} +local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } + +-- highest set bit of 1..2048 +local HB = table.create(2048, 0) +do + local v = 0 + for i = 1, 2048 do + if i >= lshift(2, v) then + v += 1 + end + HB[i] = v + end +end + +-- ------------------------------------------------------------------------------------------------ bit readers +-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros +local function peek(b: buffer, s: number, o: number, n: number): number + if n <= 0 then + return 0 + end + local lo = o - n + if lo >= 0 then + local byte = s + rshift(lo, 3) + local bl = blen(b) + if byte + 4 <= bl then + return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1) + end + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < bl then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(lo, 7)), lshift(1, n) - 1) + end + if o <= 0 then + return 0 + end + return lshift(peek(b, s, o, o), -lo) +end + +-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty +local function streamBits(b: buffer, s: number, e: number): number + if e <= s then + return -1 + end + local last = readu8(b, e - 1) + if last == 0 then + return -1 + end + return (e - 1 - s) * 8 + HB[last] +end + +-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros +local function getF(b: buffer, p: number, e: number, bp: number, n: number): number + local byte = p + rshift(bp, 3) + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < e then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ FSE +-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 +local symTmp = bcreate(512) + +-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) + local size = lshift(1, al) + local high = size - 1 + local next = table.create(nsym, 0) + for s = 0, nsym - 1 do + local c = norm[s + 1] + if c == -1 then + if high < 0 then + return nil, "bad FSE distribution" + end + writeu8(symTmp, high, s) + high -= 1 + next[s + 1] = 1 + else + next[s + 1] = c + end + end + local pos = 0 + local step = rshift(size, 1) + rshift(size, 3) + 3 + local mask = size - 1 + for s = 0, nsym - 1 do + local c = norm[s + 1] + for _ = 1, c do + writeu8(symTmp, pos, s) + local guard = 0 + repeat + pos = band(pos + step, mask) + guard += 1 + until pos <= high or guard > size + if guard > size then + return nil, "bad FSE distribution" + end + end + end + if pos ~= 0 then + return nil, "bad FSE distribution" + end + for u = 0, size - 1 do + local s = readu8(symTmp, u) + local ns = next[s + 1] + if ns < 1 or ns > 2048 then + return nil, "bad FSE distribution" + end + next[s + 1] = ns + 1 + local nb = al - HB[ns] + if nb < 0 then + return nil, "bad FSE distribution" + end + writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536) + end + return true, nil +end + +-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description +local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) + if p >= e then + return nil, "truncated FSE table" + end + local al = getF(b, p, e, 0, 4) + 5 + if al > maxAL then + return nil, "FSE accuracy log too large" + end + local bp = 4 + local remaining = lshift(1, al) + 1 + local threshold = lshift(1, al) + local nbBits = al + 1 + local sym = 0 + local prev0 = false + while remaining > 1 and sym <= maxSym do + if prev0 then + local n0 = sym + while true do + local v = getF(b, p, e, bp, 2) + bp += 2 + if v == 3 then + n0 += 3 + if n0 > maxSym or bp > (e - p) * 8 then + return nil, "bad FSE table" + end + else + n0 += v + break + end + end + if n0 > maxSym then + return nil, "bad FSE table" + end + while sym < n0 do + norm[sym + 1] = 0 + sym += 1 + end + end + local max = 2 * threshold - 1 - remaining + local count + local low = getF(b, p, e, bp, nbBits - 1) + if low < max then + count = low + bp += nbBits - 1 + else + count = getF(b, p, e, bp, nbBits) + if count >= threshold then + count -= max + end + bp += nbBits + end + count -= 1 + remaining -= if count < 0 then -count else count + if remaining < 1 then + return nil, "bad FSE table" + end + norm[sym + 1] = count + sym += 1 + prev0 = count == 0 + while remaining < threshold do + nbBits -= 1 + threshold = rshift(threshold, 1) + end + end + if remaining ~= 1 then + return nil, "bad FSE table" + end + local used = rshift(bp + 7, 3) + if p + used > e then + return nil, "truncated FSE table" + end + for s = sym, maxSym do + norm[s + 1] = 0 + end + return al, used, sym +end + +local function predefined(dist: { number }, al: number): buffer + local t = bcreate(lshift(1, al) * 4) + buildFse(dist, #dist, al, t) + return t +end +local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) + +-- ------------------------------------------------------------------------------------------------ Huffman +-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +local weights = bcreate(256) +local wfse = bcreate(64 * 4) +local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) + if p >= e then + return nil, "truncated Huffman table" + end + local hdr = readu8(b, p) + local n = 0 + local used + if hdr >= 128 then + n = hdr - 127 + used = 1 + rshift(n + 1, 1) + if p + used > e then + return nil, "truncated Huffman table" + end + for i = 0, n - 1 do + local byte = readu8(b, p + 1 + rshift(i, 1)) + writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15)) + end + else + used = 1 + hdr + if p + used > e then + return nil, "truncated Huffman table" + end + local q, qe = p + 1, p + 1 + hdr + local norm = st.norm + local al, nb = ncount(b, q, qe, 255, 6, norm) + if not al then + return nil, nb + end + local ok, msg = buildFse(norm, 256, al, wfse) + if not ok then + return nil, msg + end + local ss = q + nb + local off = streamBits(b, ss, qe) + if off < 0 then + return nil, "bad Huffman weight stream" + end + local s1 = peek(b, ss, off, al) + off -= al + local s2 = peek(b, ss, off, al) + off -= al + while true do + if n > 254 then + return nil, "too many Huffman weights" + end + local e1 = readu32(wfse, s1 * 4) + writeu8(weights, n, band(e1, 255)) + n += 1 + local k = band(rshift(e1, 8), 255) + s1 = rshift(e1, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) + n += 1 + break + end + local e2 = readu32(wfse, s2 * 4) + writeu8(weights, n, band(e2, 255)) + n += 1 + k = band(rshift(e2, 8), 255) + s2 = rshift(e2, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) + n += 1 + break + end + end + end + -- the last weight is implied: the total must reach the next power of two + local total = 0 + for i = 0, n - 1 do + local w = readu8(weights, i) + if w > 11 then + return nil, "bad Huffman weight" + end + if w > 0 then + total += lshift(1, w - 1) + end + end + if total == 0 or total >= 2048 then + return nil, "bad Huffman weights" + end + local maxBits = HB[total] + 1 + local rest = lshift(1, maxBits) - total + if band(rest, rest - 1) ~= 0 then + return nil, "bad Huffman weights" + end + writeu8(weights, n, HB[rest] + 1) + local nsym = n + 1 + -- codes: the longest first, in symbol order within a length + local rankCount = table.create(13, 0) + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + rankCount[bits + 1] += 1 + end + end + local rankIdx = table.create(13, 0) + rankIdx[maxBits + 1] = 0 + for i = maxBits, 1, -1 do + rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i) + end + if rankIdx[1] ~= lshift(1, maxBits) then + return nil, "bad Huffman weights" + end + local t = st.huf + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + local code = rankIdx[bits + 1] + local len = lshift(1, maxBits - bits) + local v = i + bits * 256 + for k = code, code + len - 1 do + writeu16(t, k * 2, v) + end + rankIdx[bits + 1] = code + len + end + end + st.hufBits = maxBits + return used, nil +end + +-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message +local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? + local off = streamBits(b, s, e) + if off < 0 then + return "bad Huffman stream" + end + local mmask = lshift(1, mb) - 1 + local fastEnd = blen(b) - 4 + for k = dp, dp + cnt - 1 do + local lo = off - mb + local idx + if lo >= 0 then + local byte = s + rshift(lo, 3) + if byte <= fastEnd then + idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask) + else + idx = peek(b, s, off, mb) + end + else + idx = peek(b, s, off, mb) + end + local v = readu16(t, idx * 2) + writeu8(lit, k, v) + off -= rshift(v, 8) + end + if off ~= 0 then + return "Huffman stream size mismatch" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ frames +-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) +local function grow(st: any, need: number): boolean + if need > st.maxBytes then + return false + end + local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536)) + local nb = bcreate(cap) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + return true +end + +-- a compressed block [p, e): nil (ok) | code, message +local function block(b: buffer, p: number, e: number, st: any): (string?, string?) + -- literals section + local b0 = readu8(b, p) + local ltype = band(b0, 3) + local sf = band(rshift(b0, 2), 3) + local regen + local litSrc, litPos + local lit = st.lit + if ltype <= 1 then + if sf == 0 or sf == 2 then + regen = rshift(b0, 3) + p += 1 + elseif sf == 1 then + if p + 2 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + p += 2 + else + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096 + p += 3 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if ltype == 0 then + if p + regen > e then + return "TRUNCATED", "truncated raw literals" + end + litSrc, litPos = b, p + p += regen + else + if p + 1 > e then + return "TRUNCATED", "truncated RLE literals" + end + bfill(lit, 0, readu8(b, p), regen) + litSrc, litPos = lit, 0 + p += 1 + end + else + local csize + if sf <= 1 then + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536 + regen = band(rshift(v, 4), 0x3FF) + csize = band(rshift(v, 14), 0x3FF) + p += 3 + elseif sf == 2 then + if p + 4 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFF) + csize = rshift(v, 18) + p += 4 + else + if p + 5 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFFF) + csize = rshift(v, 22) + readu8(b, p + 4) * 1024 + p += 5 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if p + csize > e then + return "TRUNCATED", "truncated compressed literals" + end + local hs, he = p, p + csize + p = he + if ltype == 2 then + local used, herr = hufTable(b, hs, he, st) + if not used then + return "CORRUPT", herr + end + hs += used + elseif not st.hufBits then + return "CORRUPT", "treeless literals without a previous Huffman table" + end + local t, mb = st.huf, st.hufBits + if sf == 0 then + local herr = hufStream(b, hs, he, t, mb, lit, 0, regen) + if herr then + return "CORRUPT", herr + end + else + if hs + 6 > he then + return "CORRUPT", "truncated jump table" + end + local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4) + local s1 = hs + 6 + local s2 = s1 + l1 + local s3 = s2 + l2 + local s4 = s3 + l3 + if s4 > he then + return "CORRUPT", "bad jump table" + end + local seg = rshift(regen + 3, 2) + local last = regen - 3 * seg + if last < 0 then + return "CORRUPT", "bad 4-stream literals size" + end + local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg) + or hufStream(b, s2, s3, t, mb, lit, seg, seg) + or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg) + or hufStream(b, s4, he, t, mb, lit, 3 * seg, last) + if herr then + return "CORRUPT", herr + end + end + litSrc, litPos = lit, 0 + end + + -- sequences section header + if p >= e then + return "TRUNCATED", "missing sequences header" + end + local nbSeq = readu8(b, p) + p += 1 + if nbSeq >= 128 then + if nbSeq == 255 then + if p + 2 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = readu16(b, p) + 0x7F00 + p += 2 + else + if p + 1 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = (nbSeq - 128) * 256 + readu8(b, p) + p += 1 + end + end + local op = st.op + if nbSeq == 0 then + if p ~= e then + return "CORRUPT", "data after an empty sequences section" + end + if op + regen > blen(st.out) then + if not grow(st, op + regen) then + return "LIMIT", "output over the size limit" + end + end + bcopy(st.out, op, litSrc, litPos, regen) + st.op = op + regen + return nil, nil + end + if p >= e then + return "TRUNCATED", "missing compression modes" + end + local modes = readu8(b, p) + p += 1 + if band(modes, 3) ~= 0 then + return "CORRUPT", "reserved bits set in compression modes" + end + -- the three tables, in the order LL, OF, ML + local tabs = st.tabs + for k = 1, 3 do + local mode = band(rshift(modes, 8 - 2 * k), 3) + local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52 + local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9 + if mode == 0 then + tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE + tabs[k + 3] = if k == 2 then 5 else 6 + elseif mode == 1 then + if p >= e then + return "TRUNCATED", "truncated RLE table" + end + local sym = readu8(b, p) + p += 1 + if sym > maxSym then + return "CORRUPT", "bad RLE symbol" + end + local t = st.rle[k] + writeu32(t, 0, sym) + tabs[k] = t + tabs[k + 3] = 0 + elseif mode == 2 then + local norm = st.norm + local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm) + if not al then + return "CORRUPT", used + end + p += used + local t = st.dyn[k] + local ok, msg = buildFse(norm, nsym :: number, al, t) + if not ok then + return "CORRUPT", msg + end + tabs[k] = t + tabs[k + 3] = al + else + if not tabs[k] then + return "CORRUPT", "repeated table without a previous one" + end + end + end + local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer + local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number + + -- the sequences bitstream + local s = p + local off = streamBits(b, s, e) + if off < 0 then + return "CORRUPT", "bad sequences bitstream" + end + local llS = peek(b, s, off, llAL) + off -= llAL + local ofS = peek(b, s, off, ofAL) + off -= ofAL + local mlS = peek(b, s, off, mlAL) + off -= mlAL + local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3 + local out = st.out + local cap = blen(out) + local frameStart = st.frameStart + local lp, litEnd = litPos, litPos + regen + local fastEnd = blen(b) - 4 + for i = 1, nbSeq do + local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4) + local ofCode = band(ofE, 255) + local mlCode = band(mlE, 255) + 1 + local llCode = band(llE, 255) + 1 + -- offset bits, then match length bits, then literal length bits + local ofv + if ofCode > 24 then + local hiN = ofCode - 24 + local hi = peek(b, s, off, hiN) + off -= hiN + ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) + off -= 24 + elseif ofCode > 0 then + local lo = off - ofCode + local v + if lo >= 0 and s + rshift(lo, 3) <= fastEnd then + v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1) + else + v = peek(b, s, off, ofCode) + end + off = lo + ofv = lshift(1, ofCode) + v + else + ofv = 1 + end + local ml = ML_BASE[mlCode] + local nb = ML_BITS[mlCode] + if nb > 0 then + ml += peek(b, s, off, nb) + off -= nb + end + local ll = LL_BASE[llCode] + nb = LL_BITS[llCode] + if nb > 0 then + ll += peek(b, s, off, nb) + off -= nb + end + -- repeat offsets + local offset + if ofv > 3 then + offset = ofv - 3 + rep3 = rep2 + rep2 = rep1 + rep1 = offset + else + local idx = ofv - 1 + if ll == 0 then + idx += 1 + end + if idx == 0 then + offset = rep1 + else + if idx == 1 then + offset = rep2 + elseif idx == 2 then + offset = rep3 + else + offset = rep1 - 1 + end + if idx > 1 then + rep3 = rep2 + end + rep2 = rep1 + rep1 = offset + end + end + -- state updates (not after the last sequence): LL, ML, OF + if i < nbSeq then + nb = band(rshift(llE, 8), 255) + llS = rshift(llE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(mlE, 8), 255) + mlS = rshift(mlE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(ofE, 8), 255) + ofS = rshift(ofE, 16) + peek(b, s, off, nb) + off -= nb + end + -- execute + if lp + ll > litEnd then + return "CORRUPT", "literal length past the literals" + end + local need = op + ll + ml + if need > cap then + st.op = op + if not grow(st, need) then + return "LIMIT", "output over the size limit" + end + out = st.out + cap = blen(out) + end + if ll > 0 then + bcopy(out, op, litSrc, lp, ll) + op += ll + lp += ll + end + if offset > op - frameStart or offset < 1 then + return "CORRUPT", "match offset before the frame start" + end + local from = op - offset + if offset >= ml then + bcopy(out, op, out, from, ml) + op += ml + elseif offset == 1 then + bfill(out, op, readu8(out, from), ml) + op += ml + else + -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) + local left = ml + while left > 0 do + local n = if left < offset then left else offset + bcopy(out, op, out, from, n) + op += n + from += n + left -= n + end + end + end + if off ~= 0 then + return "CORRUPT", "sequences bitstream size mismatch" + end + local rest = litEnd - lp + if rest > 0 then + if op + rest > cap then + st.op = op + if not grow(st, op + rest) then + return "LIMIT", "output over the size limit" + end + out = st.out + end + bcopy(out, op, litSrc, lp, rest) + op += rest + end + st.op = op + st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 + return nil, nil +end + +-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset +function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) + local st: any = { + out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), + op = 0, + maxBytes = maxBytes, + lit = bcreate(BLOCK_MAX + 64), + huf = bcreate(2048 * 2), + hufBits = nil, + norm = table.create(256, 0), + tabs = {}, + rle = { bcreate(4), bcreate(4), bcreate(4) }, + dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) }, + frameStart = 0, + rep1 = 1, + rep2 = 4, + rep3 = 8, + } + local pos = start + local frames = 0 + if stop - start < 4 then + return nil, "TRUNCATED", "not a zstd stream (too short)", start + end + while pos < stop do + if pos + 4 > stop then + return nil, "TRUNCATED", "truncated frame magic", pos + end + local magic = readu32(b, pos) + if band(magic, 0xFFFFFFF0) == 0x184D2A50 then + if pos + 8 > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + local size = readu32(b, pos + 4) + if pos + 8 + size > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + pos += 8 + size + frames += 1 + continue + end + if magic ~= MAGIC then + return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos + end + pos += 4 + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local fhd = readu8(b, pos) + pos += 1 + local fcsFlag = rshift(fhd, 6) + local single = band(fhd, 0x20) ~= 0 + if band(fhd, 8) ~= 0 then + return nil, "CORRUPT", "reserved frame header bit set", pos - 1 + end + local checksum = band(fhd, 4) ~= 0 + local didFlag = band(fhd, 3) + local didSize = if didFlag == 3 then 4 else didFlag + local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag) + local hsize = (if single then 0 else 1) + didSize + fcsSize + if pos + hsize > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local windowSize = 0 + if not single then + local wd = readu8(b, pos) + pos += 1 + local wlog = 10 + rshift(wd, 3) + if wlog > 41 then + return nil, "CORRUPT", "bad window size", pos - 1 + end + local base = 2 ^ wlog + windowSize = base + base / 8 * band(wd, 7) + end + local did = 0 + if didSize == 1 then + did = readu8(b, pos) + elseif didSize == 2 then + did = readu16(b, pos) + elseif didSize == 4 then + did = readu32(b, pos) + end + pos += didSize + if did ~= 0 then + return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize + end + local fcs = -1 + if fcsSize == 1 then + fcs = readu8(b, pos) + elseif fcsSize == 2 then + fcs = readu16(b, pos) + 256 + elseif fcsSize == 4 then + fcs = readu32(b, pos) + elseif fcsSize == 8 then + fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296 + end + pos += fcsSize + if single then + windowSize = fcs + end + local blockMax = math.min(windowSize, BLOCK_MAX) + local frameStart = st.op + if fcs >= 0 then + if frameStart + fcs > st.maxBytes then + return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos + end + if frameStart + fcs > blen(st.out) then + grow(st, frameStart + fcs) + end + end + st.frameStart = frameStart + st.rep1, st.rep2, st.rep3 = 1, 4, 8 + st.hufBits = nil + table.clear(st.tabs) + -- blocks + local last = false + repeat + if pos + 3 > stop then + return nil, "TRUNCATED", "truncated block header", pos + end + local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536 + last = band(bh, 1) ~= 0 + local btype = band(rshift(bh, 1), 3) + local bsize = rshift(bh, 3) + pos += 3 + if bsize > blockMax then + return nil, "CORRUPT", "block larger than the maximum block size", pos - 3 + end + if btype == 0 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated raw block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bcopy(st.out, st.op, b, pos, bsize) + st.op += bsize + pos += bsize + elseif btype == 1 then + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated RLE block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bfill(st.out, st.op, readu8(b, pos), bsize) + st.op += bsize + pos += 1 + elseif btype == 2 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated compressed block", pos + end + if bsize == 0 then + return nil, "CORRUPT", "empty compressed block", pos + end + local code, msg = block(b, pos, pos + bsize, st) + if code then + return nil, code, msg, pos + end + pos += bsize + else + return nil, "CORRUPT", "reserved block type", pos - 3 + end + until last + local size = st.op - frameStart + if fcs >= 0 and size ~= fcs then + return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos + end + if checksum then + if pos + 4 > stop then + return nil, "TRUNCATED", "missing content checksum", pos + end + if verify then + local _, lo = Xxh64.hash(st.out, frameStart, size) + local want = readu32(b, pos) + if lo ~= want then + return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos + end + end + pos += 4 + end + frames += 1 + end + return st.out, st.op, pos +end + +Decode.hash = Xxh64.hash + +return Decode diff --git a/src/Formats/codecs/Zstd/Xxh64.luau b/src/Formats/codecs/Zstd/Xxh64.luau new file mode 100644 index 0000000..5aa48e8 --- /dev/null +++ b/src/Formats/codecs/Zstd/Xxh64.luau @@ -0,0 +1,155 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have +-- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is +-- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits +-- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice). +local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 + +local P1H, P1L = 0x9E3779B1, 0x85EBCA87 +local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F +local P3H, P3L = 0x165667B1, 0x9E3779F9 +local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 +local P5H, P5L = 0x27D4EB2F, 0x165667C5 + +-- (ah, al) * (bh, bl) mod 2^64 +local function mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0 = al % 65536 + local a1 = (al - a0) / 65536 + local b0 = bl % 65536 + local b1 = (bl - b0) / 65536 + local mid = a1 * b0 + a0 * b1 + local mid0 = mid % 65536 + local lo = a0 * b0 + mid0 * 65536 + local lo32 = lo % T32 + local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32 + hi += (a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) + return hi % T32, lo32 +end + +local function add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local h = ah + bh + if l >= T32 then + l -= T32 + h += 1 + end + return h % T32, l +end + +-- rotl by r in 1..31 +local function rotl(h: number, l: number, r: number): (number, number) + return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) +end + +local P1L0, P1L1 = P1L % 65536, P1L // 65536 +local P2L0, P2L1 = P2L % 65536, P2L // 65536 + +-- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +local function round(ah: number, al: number, ih: number, il: number): (number, number) + local a0 = il % 65536 + local a1 = (il - a0) / 65536 + local mid = a1 * P2L0 + a0 * P2L1 + local mid0 = mid % 65536 + local lo = a0 * P2L0 + mid0 * 65536 + local ml = lo % T32 + local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536 + local l = al + ml + local h = ah + mh + if l >= T32 then + l -= T32 + h += 1 + end + h %= T32 + -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT) + local hb, lb = h % 2, l % 2 + local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2 + a0 = rl % 65536 + a1 = (rl - a0) / 65536 + mid = a1 * P1L0 + a0 * P1L1 + mid0 = mid % 65536 + lo = a0 * P1L0 + mid0 * 65536 + ml = lo % T32 + mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536 + return mh % T32, ml +end + +local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) + local rh, rl = round(0, 0, vh, vl) + hh, hl = bxor(hh, rh), bxor(hl, rl) + hh, hl = mul(hh, hl, P1H, P1L) + return add(hh, hl, P4H, P4L) +end + +local Xxh64 = {} + +-- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) +function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) + local p = offset + local e = offset + length + local hh, hl = 0, 0 + if length >= 32 then + local v1h, v1l = add(P1H, P1L, P2H, P2L) + local v2h, v2l = P2H, P2L + local v3h, v3l = 0, 0 + local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement) + local limit = e - 32 + while p <= limit do + v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p)) + v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8)) + v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16)) + v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24)) + p += 32 + end + local ah, al = rotl(v1h, v1l, 1) + local bh, bl = rotl(v2h, v2l, 7) + hh, hl = add(ah, al, bh, bl) + bh, bl = rotl(v3h, v3l, 12) + hh, hl = add(hh, hl, bh, bl) + bh, bl = rotl(v4h, v4l, 18) + hh, hl = add(hh, hl, bh, bl) + hh, hl = merge(hh, hl, v1h, v1l) + hh, hl = merge(hh, hl, v2h, v2l) + hh, hl = merge(hh, hl, v3h, v3l) + hh, hl = merge(hh, hl, v4h, v4l) + else + hh, hl = P5H, P5L + end + hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32) + while p + 8 <= e do + local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p)) + hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = rotl(hh, hl, 27) + hh, hl = mul(hh, hl, P1H, P1L) + hh, hl = add(hh, hl, P4H, P4L) + p += 8 + end + if p + 4 <= e then + local kh, kl = mul(0, readu32(b, p), P1H, P1L) + hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = rotl(hh, hl, 23) + hh, hl = mul(hh, hl, P2H, P2L) + hh, hl = add(hh, hl, P3H, P3L) + p += 4 + end + while p < e do + local kh, kl = mul(0, readu8(b, p), P5H, P5L) + hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = rotl(hh, hl, 11) + hh, hl = mul(hh, hl, P1H, P1L) + p += 1 + end + -- avalanche + hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33 + hh, hl = mul(hh, hl, P2H, P2L) + hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) -- h ^= h >> 29 + hh, hl = mul(hh, hl, P3H, P3L) + hl = bxor(hl, hh) -- h ^= h >> 32 + return hh, hl +end + +return Xxh64 diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/Zstd/init.luau new file mode 100644 index 0000000..c48de03 --- /dev/null +++ b/src/Formats/codecs/Zstd/init.luau @@ -0,0 +1,89 @@ +--!strict +-- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd +-- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses: +-- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables), +-- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified). +-- Not supported: dictionaries (Err.UNSUPPORTED), compression. +-- +-- local Zstd = require("@formats/codecs/Zstd") +-- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err +-- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false }) +-- +-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). +local Err = require("@formats/core/Err") +local Decode = require("@formats/codecs/Zstd/Decode") + +local Zstd = {} + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + verify: boolean?, -- check the content checksum when a frame has one (default true) +} + +local CODES: { [string]: string } = { + TRUNCATED = Err.TRUNCATED, + CORRUPT = Err.CORRUPT, + CHECKSUM = Err.CHECKSUM, + UNSUPPORTED = Err.UNSUPPORTED, + LIMIT = Err.LIMIT, +} + +-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) +Zstd.MAGIC = "\40\181\47\253" + +-- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there +function Zstd.isFrame(buf: buffer, offset: number?): boolean + local o = offset or 0 + if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then + return false + end + local m = buffer.readu32(buf, o) + return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 +end + +-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded +-- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does). +function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b: buffer + if type(buf) == "string" then + b = buffer.fromstring(buf) + elseif type(buf) == "buffer" then + b = buf + else + return nil, Err.new(Err.ARG, "Zstd.decompress: expected a buffer or a string, got " .. typeof(buf)) + end + local n = buffer.len(b) + local o = offset or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad offset " .. tostring(offset)) + end + local l = length or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad length " .. tostring(length)) + end + l = math.min(l, n - o) + local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 + if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes)) + end + local verify = not (opts and opts.verify == false) + local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify) + if not out then + return nil, Err.new(CODES[len] or Err.CORRUPT, tostring(consumed), at) + end + if buffer.len(out) ~= len then + local r = buffer.create(len) + buffer.copy(r, 0, out, 0, len) + out = r + end + return out, consumed +end + +-- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves +function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number) + local o = math.clamp(offset or 0, 0, buffer.len(buf)) + local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) + return Decode.hash(buf, o, l) +end + +return Zstd diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau new file mode 100644 index 0000000..1cdd84c --- /dev/null +++ b/src/Formats/containers/Archive.luau @@ -0,0 +1,176 @@ +--!strict +-- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data +-- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder +-- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be +-- encoded by any writable archive format through its list() / read(). +-- +-- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err +-- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 }) +-- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end }) +-- a:list() a:read("a.txt") a:add("c.txt", "text") a:write() +-- +-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them +-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") + +local Archive = {} + +-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source +export type Entry = { + name: string, + size: number, + compressedSize: number?, + method: string?, + mtime: number?, + dir: boolean, + data: buffer?, + load: (() -> (buffer?, Err.Err?))?, + [string]: any, +} +export type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?) + +local Methods = {} +Methods.__index = Methods + +-- the public fields of an entry (no data / loader) +local function public(e: Entry): Types.ArchiveEntry + local out: any = {} + for k, v in e :: any do + if k ~= "data" and k ~= "load" then + out[k] = v + end + end + return out +end + +function Methods.list(self: any): { Types.ArchiveEntry } + local out = table.create(#self._entries) + for i, e in self._entries do + out[i] = public(e) + end + return out +end + +-- read(name) -> buffer | nil, Err (directories read as an empty buffer) +function Methods.read(self: any, name: string): (buffer?, Err.Err?) + local e: Entry? = self._byName[name] + if not e then + return nil, Err.new(Err.ARG, "no entry named " .. tostring(name)) + end + if e.data then + return e.data + end + if e.load then + local ok, b, err = pcall(e.load) + if not ok then + return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b)) + end + if not b then + return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed") + end + return b + end + return buffer.create(0) +end + +-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name +function Methods.add(self: any, name: string, data: buffer | string, opts: any?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + local o = opts or {} + local e: Entry = { + name = name, + size = buffer.len(b), + dir = o.dir == true, + mtime = o.mtime, + mode = o.mode, + data = b, + } + Archive.put(self, e) +end + +-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api) +function Methods.write(self: any, opts: any?): (buffer?, Err.Err?) + local enc = self._encode + if not enc then + return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only") + end + return enc(self, opts) +end + +-- new(format, encode?) -> an empty Archive +function Archive.new(format: string, encode: Encoder?): any + return setmetatable({ + kind = "archive", + format = format, + meta = {}, + _entries = {} :: { Entry }, + _byName = {} :: { [string]: Entry }, + _encode = encode, + }, Methods) +end + +-- put(archive, entry): append (or replace by name) an entry +function Archive.put(a: any, e: Entry) + local old = a._byName[e.name] + if old then + local i = table.find(a._entries, old) + if i then + a._entries[i] = e + end + else + table.insert(a._entries, e) + end + a._byName[e.name] = e +end + +-- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another +-- format's): what encoders iterate. nil when the value is not an archive. +function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }? + if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then + return nil + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" then + return nil + end + local out = {} + for _, e in list do + if type(e) == "table" and type(e.name) == "string" then + table.insert(out, { + entry = e, + read = function(): (buffer?, Err.Err?) + local rok, b, err = pcall(value.read, value, e.name) + if not rok then + return nil, Err.new(Err.CORRUPT, tostring(b)) + end + return b, err + end, + }) + end + end + return out +end + +-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension +-- (".tgz" -> ".tar"), else "data" +function Archive.streamName(opts: any?, exts: { string }): string + local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil + if not name then + return "data" + end + local base = string.match(name, "([^/\\]+)$") or name + local stem, ext = string.match(base, "^(.+)%.([%w]+)$") + if stem and ext then + local e = string.lower(ext) + if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then + return stem .. ".tar" + end + if table.find(exts, e) then + return stem + end + end + return base +end + +return Archive diff --git a/src/Formats/containers/Tar.luau b/src/Formats/containers/Tar.luau new file mode 100644 index 0000000..5627311 --- /dev/null +++ b/src/Formats/containers/Tar.luau @@ -0,0 +1,426 @@ +--!strict +-- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles +-- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path, +-- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields, +-- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar +-- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more, +-- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX +-- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi- +-- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes). +-- +-- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } } +-- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts) +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local Tar = {} + +export type Entry = { + name: string, + size: number, + type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ... + dir: boolean, + mode: number, + uid: number, + gid: number, + mtime: number, + link: string?, + uname: string?, + gname: string?, + offset: number, -- absolute offset of the data in the buffer + pax: { [string]: string }?, +} + +local BLOCK = 512 + +local function zeros(b: buffer, o: number): boolean + for i = 0, BLOCK - 1, 4 do + if buffer.readu32(b, o + i) ~= 0 then + return false + end + end + return true +end + +-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte) +local function number(b: buffer, o: number, n: number): number? + local first = buffer.readu8(b, o) + if first >= 0x80 then + local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative + for i = 1, n - 1 do + v = v * 256 + buffer.readu8(b, o + i) + end + return v + end + local s = buffer.readstring(b, o, n) + s = string.match(s, "^[ %z]*([0-7]*)") or "" + if s == "" then + return 0 + end + return tonumber(s, 8) +end + +local function str(b: buffer, o: number, n: number): string + local s = buffer.readstring(b, o, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function checksum(b: buffer, o: number): (number, number) + local u, s = 0, 0 + for i = 0, BLOCK - 1 do + local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i) + u += v + s += if v >= 128 then v - 256 else v + end + return u, s +end + +-- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum +function Tar.valid(b: buffer, o: number): boolean + if o + BLOCK > buffer.len(b) or zeros(b, o) then + return false + end + local want = number(b, o + 148, 8) + local u, s = checksum(b, o) + return want == u or want == s +end + +-- pax records "len key=value\n" -> { key = value } +local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean + local s = buffer.readstring(b, o, n) + local p = 1 + while p <= #s do + if string.byte(s, p) == 0 then + break + end + local len = string.match(s, "^(%d+) ", p) + if not len then + return false + end + local l = tonumber(len) :: number + if l < #len + 3 or p + l - 1 > #s then + return false + end + local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline + local eq = string.find(rec, "=", 1, true) + if not eq then + return false + end + into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1) + p += l + end + return true +end + +export type ReadOptions = { maxEntries: number? } -- default 1e6 + +-- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err +function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?) + local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local out: { Entry } = {} + local global: { [string]: string } = {} + local nextPax: { [string]: string }? = nil + local longName: string? = nil + local longLink: string? = nil + local p = o + while true do + if p + BLOCK > e then + if p == e then + break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning) + end + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if zeros(b, p) then + break -- end of archive (one or two zero blocks; what follows is padding) + end + local want = number(b, p + 148, 8) + local u, s = checksum(b, p) + if want ~= u and want ~= s then + return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148) + end + local typ = buffer.readstring(b, p + 156, 1) + if typ == "\0" then + typ = "0" + end + local size = number(b, p + 124, 12) + if not size or size < 0 then + return nil, Err.new(Err.CORRUPT, "bad size field", p + 124) + end + local data = p + BLOCK + local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK + local ustar = buffer.readstring(b, p + 257, 5) == "ustar" + -- meta records: pax / GNU long names + if typ == "x" or typ == "g" or typ == "L" or typ == "K" then + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "extended header past the end", data) + end + if typ == "x" or typ == "g" then + local into = if typ == "g" then global else (nextPax or {}) + if not pax(b, data, size, into) then + return nil, Err.new(Err.CORRUPT, "bad pax record", data) + end + if typ == "x" then + nextPax = into + end + elseif typ == "L" then + longName = str(b, data, size) + else + longLink = str(b, data, size) + end + p = nextHeader + continue + end + local name = str(b, p, 100) + if ustar then + local prefix = str(b, p + 345, 155) + if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times) + name = prefix .. "/" .. name + end + end + local entry: Entry = { + name = name, + size = size, + type = typ, + dir = typ == "5", + mode = number(b, p + 100, 8) or 0, + uid = number(b, p + 108, 8) or 0, + gid = number(b, p + 116, 8) or 0, + mtime = number(b, p + 136, 12) or 0, + link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil, + uname = if ustar then str(b, p + 265, 32) else nil, + gname = if ustar then str(b, p + 297, 32) else nil, + offset = data, + pax = nil, + } + if longName then + entry.name = longName + end + if longLink then + entry.link = longLink + end + local px = nextPax + for _, rec in { global, px } do + if rec then + if rec.path then + entry.name = rec.path + end + if rec.linkpath then + entry.link = rec.linkpath + end + if rec.size then + local sz = tonumber(rec.size) + if not sz or sz < 0 or sz % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad pax size", p) + end + entry.size = sz + end + if rec.mtime then + entry.mtime = tonumber(rec.mtime) or entry.mtime + end + if rec.uid then + entry.uid = tonumber(rec.uid) or entry.uid + end + if rec.gid then + entry.gid = tonumber(rec.gid) or entry.gid + end + if rec.uname then + entry.uname = rec.uname + end + if rec.gname then + entry.gname = rec.gname + end + end + end + if px then + entry.pax = px + end + if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then + entry.dir = true + end + -- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir) + local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size + if typ == "5" or typ == "1" or typ == "2" then + entry.size = 0 + end + nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK + if typ ~= "5" and data + dataSize > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + nextPax, longName, longLink = nil, nil, nil + p = nextHeader + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ writing +export type WriteEntry = { + name: string, + data: buffer?, + dir: boolean?, + type: string?, -- default "0" ("5" for dir) + link: string?, + mode: number?, -- default 0o644 (0o755 for directories) + uid: number?, + gid: number?, + uname: string?, + gname: string?, + mtime: number?, -- unix seconds (default 0) +} +export type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed) + +local function octal(w: buffer, o: number, n: number, v: number): boolean + -- n - 1 octal digits and a NUL; false when it does not fit + local s = string.format("%o", v) + if v < 0 or v % 1 ~= 0 or #s > n - 1 then + return false + end + buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s) + buffer.writeu8(w, o + n - 1, 0) + return true +end + +local function field(w: buffer, o: number, n: number, s: string) + buffer.writestring(w, o, string.sub(s, 1, n)) +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function paxRecord(key: string, value: string): string + local body = " " .. key .. "=" .. value .. "\n" + local n = #body + 1 + while #tostring(n) + #body ~= n do + n = #tostring(n) + #body + end + return tostring(n) .. body +end + +-- one header block (the checksum filled in) +local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer + local h = buffer.create(BLOCK) + field(h, 0, 100, name) + local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4) + octal(h, 100, 8, mode % 0x200000) + octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF)) + octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF)) + octal(h, 124, 12, size) + octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1)) + field(h, 148, 8, " ") + field(h, 156, 1, typ) + field(h, 157, 100, link) + field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000") + field(h, 265, 32, e.uname or "") + field(h, 297, 32, e.gname or "") + field(h, 345, 155, prefix) + local u = checksum(h, 0) + field(h, 148, 8, string.format("%06o", u) .. "\0 ") + return h +end + +-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil +local function split(path: string): (string?, string?) + if #path <= 100 then + return "", path + end + for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile + if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then + return string.sub(path, 1, i - 1), string.sub(path, i + 1) + end + end + return nil, nil +end + +-- write(entries, opts?) -> buffer | nil, Err +function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) + local fmt = (opts and opts.format) or "pax" + local w = Bytes.writer(BLOCK * (2 * #entries + 2)) + for i, e in entries do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local data = e.data or buffer.create(0) + local typ = e.type or (if e.dir then "5" else "0") + local name = e.name + if typ == "5" and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local size = if typ == "0" or typ == "7" then buffer.len(data) else 0 + local link = e.link or "" + -- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole + local prefix, short + if fmt == "ustar" then + prefix, short = split(name) + elseif #name <= 100 then + prefix, short = "", name + end + local paxRecs: { string } = {} + -- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII + local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name)) + local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link)) + if needName or needLink then + if fmt == "ustar" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar") + elseif fmt == "gnu" then + if needName then + local ln = buffer.fromstring(name .. "\0") + w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true)) + w:bytes(ln) + w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK) + end + if needLink then + local ll = buffer.fromstring(link .. "\0") + w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true)) + w:bytes(ll) + w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK) + end + else + if needName then + table.insert(paxRecs, paxRecord("path", name)) + end + if needLink then + table.insert(paxRecs, paxRecord("linkpath", link)) + end + end + end + if size >= 8 ^ 11 then + if fmt ~= "pax" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax") + end + table.insert(paxRecs, paxRecord("size", tostring(size))) + end + local mt = e.mtime or 0 + if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then + table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", ""))) + end + if #paxRecs > 0 then + local body = buffer.fromstring(table.concat(paxRecs)) + w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false)) + w:bytes(body) + w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK) + end + if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then + -- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile) + local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?") + prefix, short = "", string.sub(stand, 1, 100) + end + w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu")) + if size > 0 then + w:bytes(data) + w:fill(0, (BLOCK - size % BLOCK) % BLOCK) + end + end + w:fill(0, BLOCK * 2) + return w:finish(), nil +end + +return Tar diff --git a/src/Formats/font/bmfont/Parse.luau b/src/Formats/font/bmfont/Parse.luau new file mode 100644 index 0000000..13c8314 --- /dev/null +++ b/src/Formats/font/bmfont/Parse.luau @@ -0,0 +1,457 @@ +--!strict +-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one +-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation +-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the +-- descriptor has no nesting that matters, no text content). +-- +-- Never throws on bad input: parse functions return nil, message. +local Bytes = require("@formats/core/Bytes") + +local Parse = {} + +export type Char = { + id: number, + x: number, + y: number, + width: number, + height: number, + xoffset: number, + yoffset: number, + xadvance: number, + page: number, + chnl: number, +} +export type Desc = { + info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline + common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl + pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1]) + chars: { Char }, + kernings: { { number } }, -- { first, second, amount } +} + +local LIMIT = 1000000 -- chars / kernings + +local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } +local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } +local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } + +local function list(s: string?, n: number): { number } + local out = table.create(n, 0) + if s then + local i = 1 + for v in string.gmatch(s, "-?%d+") do + if i > n then + break + end + out[i] = tonumber(v) or 0 + i += 1 + end + end + return out +end + +local function new(): Desc + return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } +end + +-- one tag's attributes (already split into key -> string) into the description +local function apply(d: Desc, tag: string, a: { [string]: string }): string? + if tag == "info" then + d.info.face = a.face or "" + d.info.charset = a.charset or "" + for _, k in INFO_NUM do + d.info[k] = tonumber(a[k]) or 0 + end + d.info.padding = list(a.padding, 4) + d.info.spacing = list(a.spacing, 2) + elseif tag == "common" then + for _, k in COMMON_NUM do + d.common[k] = tonumber(a[k]) or 0 + end + elseif tag == "page" then + local id = tonumber(a.id) + if not id or id < 0 or id > 4096 or id % 1 ~= 0 then + return "bad page id" + end + d.pages[id + 1] = a.file or "" + elseif tag == "char" then + if #d.chars >= LIMIT then + return "too many chars" + end + local c: any = {} + for _, k in CHAR_NUM do + c[k] = tonumber(a[k]) or 0 + end + table.insert(d.chars, c) + elseif tag == "kerning" then + if #d.kernings >= LIMIT then + return "too many kerning pairs" + end + table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 }) + end + return nil +end + +local function fill(d: Desc) + for i = 1, #d.pages do + d.pages[i] = d.pages[i] or "" + end +end + +-- ------------------------------------------------------------------------------------------------ text +function Parse.text(s: string): (Desc?, string?) + local d = new() + for line in string.gmatch(s, "[^\r\n]+") do + local tag, rest = string.match(line, "^%s*(%a+)(.*)$") + if tag then + local a: { [string]: string } = {} + -- key=value, key="quoted value" + local i = 1 + while i <= #rest do + local k, q, e = string.match(rest, '^%s*([%w_]+)="([^"]*)"()', i) + if k then + a[k] = q + i = e + else + local k2, v2, e2 = string.match(rest, "^%s*([%w_]+)=(%S*)()", i) + if not k2 then + break + end + a[k2] = v2 + i = e2 + end + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + end + if not d.common.lineHeight then + return nil, "no common line" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ XML +local ENTITIES = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" } +local function unescape(s: string): string + return ( + string.gsub(s, "&(#?x?%w+);", function(e: string): string? + if ENTITIES[e] then + return ENTITIES[e] + end + local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil + if n and n >= 0 and n <= 0x10FFFF then + return utf8.char(n) + end + return nil + end) + ) +end + +function Parse.xml(s: string): (Desc?, string?) + local d = new() + local seenFont = false + for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do + if tag == "font" then + seenFont = true + end + local a: { [string]: string } = {} + for k, q, v in string.gmatch(attrs, "([%w_]+)%s*=%s*([\"'])(.-)%2") do + a[k] = unescape(v) + local _ = q + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + if not seenFont or not d.common.lineHeight then + return nil, "not a BMFont XML descriptor" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ binary +function Parse.binary(r: Bytes.Reader): (Desc?, string?) + if not r:match("BMF") then + return nil, "bad signature" + end + local version = r:u8() + if version ~= 3 then + return nil, "unsupported binary version " .. version + end + local d = new() + while not r:eof() do + local kind = r:u8() + local size = r:u32le() + if r.err then + return nil, "truncated block header" + end + local b = r:slice(size) + if r.err then + return nil, "block past the end" + end + if kind == 1 then + d.info.size = b:i16le() + local bits = b:u8() + d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0 + d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0 + d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0 + d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0 + d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0 + d.info.charsetId = b:u8() + d.info.charset = "" + d.info.stretchH = b:u16le() + d.info.aa = b:u8() + d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() } + d.info.spacing = { b:u8(), b:u8() } + d.info.outline = b:u8() + d.info.face = b:cstring() + elseif kind == 2 then + d.common.lineHeight = b:u16le() + d.common.base = b:u16le() + d.common.scaleW = b:u16le() + d.common.scaleH = b:u16le() + d.common.pages = b:u16le() + d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0 + d.common.alphaChnl = b:u8() + d.common.redChnl = b:u8() + d.common.greenChnl = b:u8() + d.common.blueChnl = b:u8() + elseif kind == 3 then + while not b:eof() and #d.pages < 4096 do + table.insert(d.pages, b:cstring()) + end + elseif kind == 4 then + local n = size // 20 + if n > LIMIT then + return nil, "too many chars" + end + for _ = 1, n do + table.insert(d.chars, { + id = b:u32le(), + x = b:u16le(), + y = b:u16le(), + width = b:u16le(), + height = b:u16le(), + xoffset = b:i16le(), + yoffset = b:i16le(), + xadvance = b:i16le(), + page = b:u8(), + chnl = b:u8(), + }) + end + elseif kind == 5 then + local n = size // 10 + if n > LIMIT then + return nil, "too many kerning pairs" + end + for _ = 1, n do + table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() }) + end + end + if b.err then + return nil, "truncated block " .. kind + end + end + if not d.common.lineHeight then + return nil, "no common block" + end + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ writers +local function num(v: any): string + return string.format("%d", math.floor(tonumber(v) or 0)) +end + +local function textLines(d: Desc, quote: (string) -> string): { { any } } + local i, c = d.info, d.common + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + local lines: { { any } } = { + { + "info", + { + { "face", quote(i.face or "") }, + { "size", num(i.size) }, + { "bold", num(i.bold) }, + { "italic", num(i.italic) }, + { "charset", quote(i.charset or "") }, + { "unicode", num(i.unicode) }, + { "stretchH", num(i.stretchH or 100) }, + { "smooth", num(i.smooth) }, + { "aa", num(i.aa) }, + { "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") }, + { "spacing", num(sp[1]) .. "," .. num(sp[2]) }, + { "outline", num(i.outline) }, + }, + }, + } + local cf = {} + for _, k in COMMON_NUM do + table.insert(cf, { k, num(c[k]) }) + end + table.insert(lines, { "common", cf }) + return lines +end + +function Parse.writeText(d: Desc): string + local out = {} + local function q(s: string): string + return '"' .. string.gsub(s, '"', "") .. '"' + end + for _, l in textLines(d, q) do + local parts = { l[1] } + for _, kv in l[2] do + table.insert(parts, kv[1] .. "=" .. kv[2]) + end + table.insert(out, table.concat(parts, " ")) + end + for id, file in d.pages do + table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', "")))) + end + table.insert(out, "chars count=" .. #d.chars) + for _, c in d.chars do + local parts = { "char" } + for _, k in CHAR_NUM do + table.insert(parts, k .. "=" .. num((c :: any)[k])) + end + table.insert(out, table.concat(parts, " ")) + end + if #d.kernings > 0 then + table.insert(out, "kernings count=" .. #d.kernings) + for _, k in d.kernings do + table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3]))) + end + end + return table.concat(out, "\n") .. "\n" +end + +local function esc(s: string): string + return (string.gsub(s, '[&<>"]', { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """ })) +end + +function Parse.writeXml(d: Desc): string + local out = { '', "" } + for _, l in textLines(d, function(s: string): string + return s + end) do + local parts = { " <" .. l[1] } + for _, kv in l[2] do + table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"') + end + table.insert(out, table.concat(parts, " ") .. "/>") + end + table.insert(out, " ") + for id, file in d.pages do + table.insert(out, string.format(' ', id - 1, esc(file))) + end + table.insert(out, " ") + table.insert(out, string.format(' ', #d.chars)) + for _, c in d.chars do + local parts = { " ") + end + table.insert(out, " ") + if #d.kernings > 0 then + table.insert(out, string.format(' ', #d.kernings)) + for _, k in d.kernings do + table.insert(out, string.format(' ', num(k[1]), num(k[2]), num(k[3]))) + end + table.insert(out, " ") + end + table.insert(out, "") + return table.concat(out, "\n") .. "\n" +end + +function Parse.writeBinary(d: Desc): buffer + local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10) + w:string("BMF") + w:u8(3) + local i, c = d.info, d.common + local face = i.face or "" + w:u8(1) + w:u32le(14 + #face + 1) + w:u16le((tonumber(i.size) or 0) % 65536) + local bits = 0 + if (tonumber(i.smooth) or 0) ~= 0 then + bits += 0x80 + end + if (tonumber(i.unicode) or 0) ~= 0 then + bits += 0x40 + end + if (tonumber(i.italic) or 0) ~= 0 then + bits += 0x20 + end + if (tonumber(i.bold) or 0) ~= 0 then + bits += 0x10 + end + if (tonumber(i.fixedHeight) or 0) ~= 0 then + bits += 0x08 + end + w:u8(bits) + w:u8(tonumber(i.charsetId) or 0) + w:u16le(tonumber(i.stretchH) or 100) + w:u8(tonumber(i.aa) or 1) + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + for k = 1, 4 do + w:u8(pad[k] or 0) + end + w:u8(sp[1] or 0) + w:u8(sp[2] or 0) + w:u8(tonumber(i.outline) or 0) + w:cstring(face) + w:u8(2) + w:u32le(15) + for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do + w:u16le((tonumber(c[k]) or 0) % 65536) + end + w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0) + for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do + w:u8(tonumber(c[k]) or 0) + end + if #d.pages > 0 then + local len = 0 + for _, p in d.pages do + len += #p + 1 + end + w:u8(3) + w:u32le(len) + for _, p in d.pages do + w:cstring(p) + end + end + w:u8(4) + w:u32le(#d.chars * 20) + for _, ch in d.chars do + w:u32le(ch.id) + w:u16le(ch.x) + w:u16le(ch.y) + w:u16le(ch.width) + w:u16le(ch.height) + w:u16le(ch.xoffset % 65536) + w:u16le(ch.yoffset % 65536) + w:u16le(ch.xadvance % 65536) + w:u8(ch.page) + w:u8(ch.chnl) + end + if #d.kernings > 0 then + w:u8(5) + w:u32le(#d.kernings * 10) + for _, k in d.kernings do + w:u32le(k[1]) + w:u32le(k[2]) + w:u16le(k[3] % 65536) + end + end + return w:finish() +end + +return Parse diff --git a/src/Formats/font/bmfont/init.luau b/src/Formats/font/bmfont/init.luau new file mode 100644 index 0000000..e40aa7e --- /dev/null +++ b/src/Formats/font/bmfont/init.luau @@ -0,0 +1,408 @@ +--!strict +-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and +-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize +-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are +-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the +-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / +-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. +-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Parse = require("@formats/font/bmfont/Parse") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmfont = { + name = "bmfont", + category = "font", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" } }, +} + +export type DecodeOptions = { + pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first) + loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one) +} +export type EncodeOptions = { + variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" + px: number?, -- fonts without a BMFont description are baked first (see bake) + chars: (string | { number })?, +} +export type BakeOptions = { + px: number?, -- pixels per em (default 32) + chars: (string | { number })?, -- code points to include (default printable ASCII 32..126) + pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096) + padding: number?, -- empty pixels around each glyph (default 1) + file: string?, -- page file name prefix (default "font"): pages are _.png +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmfont.sniff(r: Bytes.Reader): number + local head = r:peek(64) + if string.sub(head, 1, 4) == "BMF\3" then + return 1 + end + if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then + return 0.9 + end + if string.find(head, "", 1, true) or (string.find(head, "", 1, true)) then + return if string.find(r:peek(512), " true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil +function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) + local load = loader or self.meta.pageLoader + if type(load) ~= "function" then + return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))") + end + local pages = {} + for i, file in self.meta.pageFiles do + local ok, img, err = pcall(load, file, i - 1) + if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img)) + end + pages[i] = img + end + self.pages = pages + return true +end + +local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 + +-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; +-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. +function Face.rasterize(self: any, g: number, px: number?): Types.Image? + local c = self._chars[g] + if not c then + return nil + end + if not self.pages and self.meta.pageLoader then + self:loadPages() + end + local page = self.pages and self.pages[c.page + 1] + local img = Types.Image.new(c.width, c.height, "alpha8") + img.meta.left = c.xoffset + img.meta.top = (self.meta.base or 0) - c.yoffset + img.meta.advance = c.xadvance + img.meta.glyph = g + img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1 + if not page then + return nil + end + local pw, ph = page.width, page.height + local bpp = Types.Image.bpp(page.format) or 4 + local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0 + if page.format == "graya8" then + ch = 1 + end + for y = 0, c.height - 1 do + local sy = c.y + y + for x = 0, c.width - 1 do + local sx = c.x + x + if sx >= 0 and sy >= 0 and sx < pw and sy < ph then + buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1))) + end + end + end + return img +end + +-- the Font value of a description +local function face(d: Parse.Desc, variant: string): any + local f: any = setmetatable({ + kind = "font", + info = { + family = d.info.face, + style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular", + fullName = d.info.face, + }, + unitsPerEm = math.abs(d.info.size or 0), + ascent = d.common.base or 0, + descent = (d.common.base or 0) - (d.common.lineHeight or 0), + lineGap = 0, + numGlyphs = #d.chars + 1, + pages = nil, + meta = { + bmfont = d, + variant = variant, + pageFiles = d.pages, + lineHeight = d.common.lineHeight, + base = d.common.base, + source = { format = "bmfont", variant = variant }, + }, + _chars = {}, + _index = {}, + _kern = {}, + }, Face) + for i, c in d.chars do + f._chars[i] = c + if f._index[c.id] == nil then + f._index[c.id] = i + end + end + for _, k in d.kernings do + f._kern[k[1] * 2097152 + k[2]] = k[3] + end + return f +end + +function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local d, err, variant + if r:peek(3) == "BMF" then + d, err = Parse.binary(r:sub(0)) + variant = "binary" + else + local s = r:peek(r:size()) + if string.find(string.sub(s, 1, 512), " 255 or c.chnl < 0 or c.chnl > 255 then + return false + end + end + for _, k in d.kernings do + if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then + return false + end + end + for _, p in d.pages do + if type(p) ~= "string" then + return false + end + end + return true +end + +function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + local d = type(font.meta) == "table" and font.meta.bmfont or nil + if d == nil then + local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars }) + if not baked then + return nil, err + end + d = baked.meta.bmfont + end + if not validDesc(d) then + return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") + end + local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text" + if variant == "text" then + return buffer.fromstring(Parse.writeText(d)), nil + elseif variant == "xml" then + return buffer.fromstring(Parse.writeXml(d)), nil + elseif variant == "binary" then + return Parse.writeBinary(d), nil + end + return nil, Err.new(Err.ARG, "variant must be text, xml or binary") +end + +-- ------------------------------------------------------------------------------------------------ extras +local function codepoints(chars: any): { number } + local out = {} + if type(chars) == "string" then + for _, c in utf8.codes(chars) do + table.insert(out, c) + end + elseif type(chars) == "table" then + for _, c in chars do + if type(c) == "number" then + table.insert(out, c) + end + end + else + for c = 32, 126 do + table.insert(out, c) + end + end + return out +end + +-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are +-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are +-- kept (rounded to pixels). +function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) + if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "bake: expected an outline Font") + end + local o = opts or {} + local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32 + local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1 + local scale = px / font.unitsPerEm + local glyphs = {} + local area = 0 + local seen = {} + for _, cp in codepoints(o.chars) do + local g = font:glyphIndex(cp) + if (g ~= 0 or cp == 0) and not seen[cp] then + seen[cp] = true + local img = font:rasterize(g, px) + if img then + table.insert(glyphs, { cp = cp, g = g, img = img }) + area += (img.width + pad) * (img.height + pad) + end + end + end + local size = o.pageSize + if type(size) ~= "number" then + size = 64 + while size * size < area * 1.3 and size < 4096 do + size *= 2 + end + end + local order = table.clone(glyphs) + table.sort(order, function(a: any, b: any): boolean + if a.img.height ~= b.img.height then + return a.img.height > b.img.height + end + return a.cp < b.cp + end) + local ascent = math.ceil(font.ascent * scale) + local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale) + local prefix = o.file or "font" + local d: Parse.Desc = { + info = { + face = font.info and font.info.family or "font", + size = px, + bold = 0, + italic = 0, + charset = "", + unicode = 1, + stretchH = 100, + smooth = 1, + aa = 1, + padding = { 0, 0, 0, 0 }, + spacing = { pad, pad }, + outline = 0, + }, + common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 }, + pages = {}, + chars = {}, + kernings = {}, + } + local pages: { Types.Image } = {} + local page: Types.Image? = nil + local x, y, rowH = pad, pad, 0 + local placed: { [number]: Parse.Char } = {} + for _, gl in order do + local w, h = gl.img.width, gl.img.height + if w + 2 * pad > size or h + 2 * pad > size then + return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page") + end + if x + w + pad > size then + x, y, rowH = pad, y + rowH + pad, 0 + end + if not page or y + h + pad > size then + page = Types.Image.new(size, size) + table.insert(pages, page :: Types.Image) + table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1)) + x, y, rowH = pad, pad, 0 + end + local pg = page :: Types.Image + for yy = 0, h - 1 do + for xx = 0, w - 1 do + local a = buffer.readu8(gl.img.pixels, yy * w + xx) + buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216) + end + end + local c: Parse.Char = { + id = gl.cp, + x = x, + y = y, + width = w, + height = h, + xoffset = gl.img.meta.left, + yoffset = ascent - gl.img.meta.top, + xadvance = math.floor(gl.img.meta.advance + 0.5), + page = #pages - 1, + chnl = 15, + } + placed[gl.cp] = c + x += w + pad + rowH = math.max(rowH, h) + end + for _, gl in glyphs do + table.insert(d.chars, placed[gl.cp]) + end + d.common.pages = #pages + if type(font.kern) == "function" then + for _, a in glyphs do + for _, b in glyphs do + local k = font:kern(a.g, b.g) + if k ~= 0 then + local v = math.floor(k * scale + 0.5) + if v ~= 0 then + table.insert(d.kernings, { a.cp, b.cp, v }) + end + end + end + end + end + local f = face(d, "text") + f.pages = pages + return f, nil +end + +return Bmfont diff --git a/src/Formats/font/ttf/init.luau b/src/Formats/font/ttf/init.luau new file mode 100644 index 0000000..2e81f06 --- /dev/null +++ b/src/Formats/font/ttf/init.luau @@ -0,0 +1,52 @@ +--!strict +-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the +-- standard Font (Types.Font) by codecs/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, +-- GPOS pair kerning) and rasterize(glyph, px) through codecs/Raster. Ported from stb_truetype 1.26 (public domain / +-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/TrueType. opts.index picks the font of a collection. +-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local TrueType = require("@formats/codecs/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Ttf = { + name = "ttf", + category = "font", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, +} + +export type DecodeOptions = { + index: number?, -- the font of a collection (default 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ttf.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts) + if not font then + return nil, err + end + font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- count(r) -> the number of fonts in the file (1 unless a collection) +function Ttf.count(r: Bytes.Reader): number + return TrueType.count(r.buf, r.base) +end + +return Ttf 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/src/Formats/init.luau b/src/Formats/init.luau index 29090f1..9379330 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -164,6 +164,73 @@ end -- ------------------------------------------------------------------------------------------------ API export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options +local load: (src: any, opts: Options?) -> (any, Err.Err?) + +-- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer +-- | string, else the files next to the descriptor on hosts with a file system +local function pageLoader(value: any, name: string?, o: Options) + if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then + return + end + local user = o.loadPage + if value.pages or (value.meta.pageLoader and type(user) ~= "function") then + return + end + local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil + if type(user) ~= "function" and not (dir and host.hasFiles) then + return + end + value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?) + local src: any + if type(user) == "function" then + src = user(file, page) + else + src = (dir :: string) .. file + end + if type(src) == "table" then + return src -- already an Image + end + if src == nil then + return nil, Err.new(Err.IO, "no data for page " .. file) + end + return load(src, { category = "image", name = file, path = type(user) ~= "function" }) + end +end + +-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a +-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer +-- one; an explicit opts.format also does. +local function unwrap(value: any, formatName: string, o: Options): any + if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then + return value + end + if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" or not value.meta.stream then + return value + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" or #list ~= 1 then + return value + end + local rok, inner = pcall(value.read, value, list[1].name) + if not rok or type(inner) ~= "buffer" then + return value + end + local e = detect(inner, nil, "archive", nil) + if not e then + return value + end + local io = table.clone(o) + io.category = "archive" + io.name = list[1].name + io._depth = (o._depth or 0) + 1 + local v = load(inner, io) + if type(v) ~= "table" or type(v.meta) ~= "table" then + return value + end + v.meta.compression = formatName + return v +end + -- load(src, opts?) -> value | nil, Err function F.load(src: any, opts: Options?): (any, Err.Err?) local o = opts or {} @@ -171,6 +238,10 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) if not buf then return nil, ierr end + if name and o.name == nil then + o = table.clone(o) + o.name = name -- formats may use the file name (single-stream archives name their entry after it) + end local entry, derr = detect(buf, name, o.category, o.format) if not entry then return nil, derr @@ -202,8 +273,10 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name) end tag(value, entry.name) - return value + pageLoader(value, name, o) + return unwrap(value, entry.name, o) end +load = F.load -- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err function F.open(src: any, opts: Options?): (any, Err.Err?) diff --git a/tests/archive/7z.luau b/tests/archive/7z.luau new file mode 100644 index 0000000..c10d3b0 --- /dev/null +++ b/tests/archive/7z.luau @@ -0,0 +1,115 @@ +-- archive/7z tests: the contract and sniff; every archive 7-Zip wrote in tools/fixtures/7z.py (LZMA / LZMA2 / copy / +-- Deflate, solid and not, BCJ / ARM64 / ARM / PPC + SPARC / delta chains, plain and encoded headers) lists exactly the +-- source tree (names incl. UTF-16 surrogates, directories, empty files, mtimes) and reads every file back; unsupported +-- methods (PPMd, BCJ2, AES) list but fail on read with Err.UNSUPPORTED naming the method; corrupt CRCs; F.load; +-- the fuzz no-throw pass. +local T = require("@tests/T") +local SevenZip = require("@formats/archive/7z") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/7z") + +local t = T.suite("7z") + +t:eq(SevenZip.name, "7z", "name") +t:eq(SevenZip.category, "archive", "category") +t:check(SevenZip.caps.decode and not SevenZip.caps.encode, "caps") + +local function decode(data: string, opts: any?): (any, any) + return SevenZip.decode(Bytes.reader(buffer.fromstring(data)), opts) +end + +local want: { [string]: any } = {} +for _, f in Fx.files do + want[f.name] = f +end + +local nfiles = 0 +for _, c in Fx.cases do + t:eq(SevenZip.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + local a, err = decode(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + if c.empty then + t:eq(#list, 0, c.name .. ": no entries") + continue + end + local seen = {} + for _, e in list do + local w = want[e.name] + t:check(w ~= nil, c.name .. ": unexpected entry " .. e.name) + seen[e.name] = true + t:eq(e.dir, w.dir, c.name .. ": " .. e.name .. ": dir") + t:eq(e.mtime, w.mtime, c.name .. ": " .. e.name .. ": mtime") + if not w.dir then + t:eq(e.size, #w.data, c.name .. ": " .. e.name .. ": size") + local b, rerr = a:read(e.name) + if c.unsupported and #w.data > 0 then + t:check(b == nil and rerr and rerr.code == Err.UNSUPPORTED and string.find(rerr.message, c.unsupported, 1, true) ~= nil, + c.name .. ": " .. e.name .. ": unsupported: " .. tostring(rerr)) + else + t:check(b and buffer.tostring(b) == w.data, c.name .. ": " .. e.name .. ": data: " .. tostring(rerr)) + nfiles += 1 + end + end + end + for name in want do + t:check(seen[name], c.name .. ": missing " .. name) + end +end +t:note("%d archives, %d files read", #Fx.cases, nfiles) + +-- corrupt data: a flipped byte in a stored file is a CRC error on read; a flipped header byte a header CRC error +do + local c + for _, x in Fx.cases do + if x.name == "copy" then + c = x + end + end + local s = c.data + local at = string.find(s, "deep\ndeep", 1, true) :: number + local bad = string.sub(s, 1, at - 1) .. "D" .. string.sub(s, at + 1) + local a = decode(bad) + t:check(a, "copy archive with a flipped data byte still lists") + local b, e = a:read("a/b/c/deep.txt") + t:check(b == nil and e and e.code == Err.CHECKSUM, "data CRC: " .. tostring(e)) + local _, e2 = decode(string.sub(s, 1, #s - 3) .. "\0\0\0") + t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "header CRC: " .. tostring(e2)) + local _, e3 = decode(string.sub(s, 1, 20)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) + local a4 = decode(bad, { checkCrc = false }) + t:check(a4 and a4:read("a/b/c/deep.txt"), "checkCrc = false") +end + +-- through the api +do + local c = Fx.cases[2] + local a, err = F.load(c.data) + t:check(a and a.format == "7z", "F.load: " .. tostring(err)) + t:eq(F.detect(c.data), "7z", "F.detect") + local r = a:read("readme.txt") + t:check(r and buffer.tostring(r) == want["readme.txt"].data, "F.load read") +end + +-- fuzz: decode + read every entry +do + local samples = {} + for _, c in Fx.cases do + if #c.data < 60000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local a = SevenZip.decode(Bytes.reader(b), { maxBytes = 2 ^ 21 }) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a + end, samples, { mutations = 12, garbage = 300 }) +end + +t:done() diff --git a/tests/archive/br.luau b/tests/archive/br.luau new file mode 100644 index 0000000..ee1acdb --- /dev/null +++ b/tests/archive/br.luau @@ -0,0 +1,97 @@ +-- archive/br tests: the contract; fixture streams (tools/fixtures/brotli.py) load as a one-entry stream archive named +-- after the file; detection through F.load (sniff + extension); sniff rejects garbage and other formats; errors as +-- Err values; the fuzz no-throw pass. +local T = require("@tests/T") +local Br = require("@formats/archive/br") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/brotli") + +local t = T.suite("br") + +-- 1. the contract +t:eq(Br.name, "br", "name") +t:eq(Br.category, "archive", "category") +t:check(Br.caps.decode and not Br.caps.encode, "caps") + +-- 2. fixtures +local n = 0 +for i, c in Fx.cases do + if i % 4 == 0 then + local a, err = Br.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/file.txt.br" }) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.kind == "archive" and a.format == "br" and a.meta.stream, c.name .. ": a stream archive") + local list = a:list() + t:eq(#list, 1, c.name .. ": one entry") + t:eq(list[1].name, "file.txt", c.name .. ": entry name") + t:eq(list[1].size, #Fx.corpora[c.corpus], c.name .. ": entry size") + t:eq(list[1].compressedSize, #c.data, c.name .. ": compressed size") + local data = a:read("file.txt") + t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], c.name .. ": entry data") + n += 1 + end +end +t:note("%d streams", n) + +-- default entry name +do + local a = Br.decode(Bytes.reader(buffer.fromstring(Fx.cases[5].data))) + t:eq(a:list()[1].name, "data", "default entry name") +end + +-- 3. through the api: by sniff (with and without the extension) and by format name +do + local c = Fx.cases[40] + local a, err = F.load(c.data, { name = "x.br" }) + t:check(a and a.format == "br", "F.load by sniff + extension: " .. tostring(err)) + t:eq(a:list()[1].name, "x", "F.load names the entry") + local a2 = F.load(c.data) + t:check(a2 and a2.format == "br", "F.load by sniff alone") + local a3 = F.archive.load(c.data, { format = "br" }) + t:check(a3 and a3.format == "br", "F.archive.load with format") + t:eq(F.detect(c.data, { name = "x.br" }), "br", "F.detect") + local _, e = F.save(a3, nil, { format = "br" }) + t:check(e and e.code == Err.UNSUPPORTED, "no encoder: " .. tostring(e)) +end + +-- 4. sniff: garbage and plain text are rejected +do + local rand = T.rng(99) + local hits = 0 + for _ = 1, 300 do + local len = 16 + rand(400) + local b = buffer.create(len) + for k = 0, len - 1 do + buffer.writeu8(b, k, rand(256)) + end + if Br.sniff(Bytes.reader(b)) > 0 then + hits += 1 + end + end + t:note("sniff accepted %d of 300 random buffers", hits) + t:check(hits <= 3, "sniff rejects random data") + t:eq(Br.sniff(Bytes.reader(buffer.fromstring("Hello, world! This is plain text.\n"))), 0, "sniff rejects text") + t:eq(Br.sniff(Bytes.reader(buffer.create(0))), 0, "sniff of nothing") + t:check(Br.sniff(Bytes.reader(buffer.fromstring(Fx.cases[40].data))) > 0, "sniff accepts a stream") + local _, e = Br.decode(Bytes.reader(buffer.fromstring("\x1b\xff\xff"))) + t:check(e and Err.is(e) and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad data: " .. tostring(e)) +end + +-- 5. fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 23 == 0 and #c.data > 8 then + table.insert(samples, if #c.data > 8000 then string.sub(c.data, 1, 8000) else c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Br.decode(Bytes.reader(b)) + end, samples, { mutations = 4, garbage = 500 }) + t:fuzz("sniff", function(b: buffer) + return Br.sniff(Bytes.reader(b)) + end, samples, { mutations = 2, garbage = 300 }) +end + +t:done() diff --git a/tests/archive/bz2.luau b/tests/archive/bz2.luau new file mode 100644 index 0000000..506b155 --- /dev/null +++ b/tests/archive/bz2.luau @@ -0,0 +1,65 @@ +-- archive/bz2 tests: the contract, sniff, a .bz2 as a one-entry single-stream archive (entry named after the file), +-- the api path (F.load by sniff, .tar.bz2 unwrap is the api's: covered once tar exists), errors, the fuzz pass. +-- Fixtures: tools/fixtures/bzip2.py. +local T = require("@tests/T") +local Bz2 = require("@formats/archive/bz2") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Fx = require("@tests/gen/bzip2") + +local t = T.suite("bz2") + +t:eq(Bz2.name, "bz2", "name") +t:eq(Bz2.category, "archive", "category") +t:check(Bz2.caps.decode and not Bz2.caps.encode, "caps") + +for _, c in Fx.cases do + t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") +end +t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("BZh9hello"))), 0, "sniff: no block magic") +t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("\x1f\x8b\x08\x00"))), 0, "sniff: gzip") + +do + local c = Fx.cases[1] + for _, x in Fx.cases do + if x.name == "text/l9" then + c = x + end + end + local a, err = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.bz2" }) + t:check(a, "decode: " .. tostring(err)) + t:check(a.kind == "archive" and a.format == "bz2" and a.meta.stream, "a single-stream archive") + local list = a:list() + t:eq(#list, 1, "one entry") + t:eq(list[1].name, "notes.txt", "entry named after the file") + t:eq(list[1].size, #Fx.corpora.text, "entry size") + t:eq(list[1].compressedSize, #c.data, "compressed size") + t:check(buffer.tostring((a:read("notes.txt"))) == Fx.corpora.text, "read") + local _, re = a:read("nope") + t:check(re and re.code == Err.ARG, "read of a missing entry") + local _, we = a:write() + t:check(we and we.code == Err.UNSUPPORTED, "read-only") + local a2 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "x.tbz2" }) + t:eq(a2:list()[1].name, "x.tar", ".tbz2 -> .tar") + local a3 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data))) + t:eq(a3:list()[1].name, "data", "no name -> data") + -- through the api + local v, ferr = F.load(c.data) + t:check(v and v.kind == "archive" and v.format == "bz2", "F.load sniffs bz2: " .. tostring(ferr)) + t:eq(F.detect(c.data), "bz2", "F.detect") + local _, de = Bz2.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 100)))) + t:check(de and de.code == Err.TRUNCATED, "truncated: " .. tostring(de)) +end + +local samples = {} +for i, c in Fx.cases do + if i % 6 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Bz2.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 300 }) + +t:done() diff --git a/tests/archive/gzip.luau b/tests/archive/gzip.luau new file mode 100644 index 0000000..ff51f40 --- /dev/null +++ b/tests/archive/gzip.luau @@ -0,0 +1,93 @@ +-- archive/gzip tests: members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members) decode +-- to one entry with the right name / mtime / data; the writer round-trips (buffer, string, one-entry archive, several +-- entries as a .tar.gz) and keeps FNAME / MTIME; the api; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py. +local T = require("@tests/T") +local F = require("@formats") +local Gzip = require("@formats/archive/gzip") +local Deflate = require("@formats/codecs/Deflate") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/tar") + +local t = T.suite("gzip") +t:eq(Gzip.name, "gzip", "name") + +for _, c in Fx.gzips do + local a, err = Gzip.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.meta.stream, c.name .. ": single stream") + local l = a:list() + t:eq(#l, 1, c.name .. ": one entry") + t:eq(l[1].name, c.entry, c.name .. ": entry name") + t:eq(l[1].mtime, if c.mtime > 0 then c.mtime else nil, c.name .. ": mtime") + t:eq(l[1].size, c.size, c.name .. ": size") + t:eq(Crc32.of((a:read(l[1].name))), c.crc, c.name .. ": data") + t:eq(F.detect(c.data), "gzip", c.name .. ": F.detect") +end + +-- the file name names the entry when there is no FNAME +do + local a = F.load(Fx.gzips[2].data, { name = "dir/notes.txt.gz" }) + t:eq(a:list()[1].name, "notes.txt", "entry named after the file") + local b = F.load(Fx.gzips[2].data, { name = "x.tgz" }) + t:eq(b:list()[1].name, "x.tar", ".tgz entry is a .tar") +end + +-- writing +do + local text = string.rep("gzip round trip ", 500) + for _, level in { 0, 1, 6, 9 } do + local z = Gzip.encode(text, { level = level }) :: buffer + t:eq(buffer.tostring((Deflate.gunzip(z))), text, "string level " .. level) + end + local one = Gzip.new(text, "notes.txt") + one._byName["notes.txt"].mtime = 1600000000 + local z = one:write() + local back = Gzip.decode(Bytes.reader(z :: buffer)) + t:eq(back:list()[1].name, "notes.txt", "FNAME written") + t:eq(back:list()[1].mtime, 1600000000, "MTIME written") + t:eq(buffer.tostring((back:read("notes.txt"))), text, "one-entry archive round trip") + -- a decoded gzip saves back as gzip (its source format) + local g = F.load(Fx.gzips[1].data) + local again = F.load(F.save(g)) + t:eq(again:list()[1].name, "story.txt", "F.save(gzip) keeps the name") + -- several entries: a .tar.gz, which the api unwraps + local multi = Gzip.new() + multi:add("a.txt", "A") + multi:add("b.txt", "BB") + local tgz = multi:write() + local tar = F.load(tgz) + t:eq(tar.format, "tar", "several entries write a .tar.gz") + t:eq(tar.meta.compression, "gzip", "unwrapped") + t:eq(buffer.tostring((tar:read("b.txt"))), "BB", ".tar.gz entry") + -- any archive converts: tar -> gzip -> tar + local tb = F.convert(Fx.tars[1].data, "gzip") + local t2 = F.load(tb) + t:eq(#t2:list(), #Fx.tars[1].entries, "tar -> tar.gz -> tar") + local _, e = Gzip.encode(text, { level = 12 }) + t:check(e and e.code == Err.ARG, "bad level") + local _, e2 = Gzip.encode({ kind = "image" }) + t:check(e2 and e2.code == Err.ARG, "not an archive") +end + +-- errors +do + local d = Fx.gzips[1].data + local _, e1 = Gzip.decode(Bytes.reader(buffer.fromstring(string.sub(d, 1, 20)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local b = buffer.fromstring(d) + buffer.writeu8(b, #d - 6, bit32.bxor(buffer.readu8(b, #d - 6), 1)) + local _, e2 = Gzip.decode(Bytes.reader(b)) + t:check(e2 and e2.code == Err.CHECKSUM, "crc: " .. tostring(e2)) +end + +local samples = {} +for _, c in Fx.gzips do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Gzip.decode(Bytes.reader(b)) +end, samples, { mutations = 20 }) + +t:done() diff --git a/tests/archive/tar.luau b/tests/archive/tar.luau new file mode 100644 index 0000000..0ed363d --- /dev/null +++ b/tests/archive/tar.luau @@ -0,0 +1,156 @@ +-- archive/tar tests: archives from Python's tarfile (ustar / GNU / pax) and GNU tar (ustar / gnu / posix / v7) list +-- the same entries as tarfile reads (names, types, sizes, links, mtimes, modes, data CRCs); the writer produces the same +-- bytes as tarfile for the same entries in all three formats and round-trips; Archive values (add / read / write, +-- conversion of a gzip / any archive to tar); .tar.gz / .tgz / .tar.bz2 / .tar.xz / .tar.zst / .tar.br load through the +-- api as the tar inside; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py. +local T = require("@tests/T") +local F = require("@formats") +local TarF = require("@formats/archive/tar") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/tar") + +local t = T.suite("tar") +t:eq(TarF.name, "tar", "name") + +local function check(a: any, want: any, label: string) + local list = a:list() + t:eq(#list, #want, label .. ": entry count") + local by = {} + for _, e in list do + by[e.name] = e + end + for _, w in want do + local e = by[w.name] + t:check(e, label .. ": has " .. w.name) + t:eq(e.type, w.type, label .. ": " .. w.name .. " type") + t:eq(e.size, w.size, label .. ": " .. w.name .. " size") + t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime") + t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode") + t:eq(e.link, w.link, label .. ": " .. w.name .. " link") + t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir") + if w.crc then + local b, err = a:read(w.name) + t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err)) + t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data") + end + end +end + +-- 1. reading +for _, c in Fx.tars do + local a, err = TarF.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + check(a, c.entries, c.name) + t:eq(F.detect(c.data), "tar", c.name .. ": F.detect") + t:note("%-18s %2d entries", c.name, #c.entries) +end + +-- 2. writing: byte-identical to Python's tarfile (which pads to 10240-byte records) +for _, w in Fx.writes do + local list = {} + for _, e in w.entries do + table.insert(list, { + name = e.name, + data = if e.data then buffer.fromstring(e.data) else nil, + dir = e.dir, + type = e.type, + link = e.link, + mode = e.mode or (if e.dir then 0x1ED else 0x1A4), + mtime = 1700000000, + uname = "user", + gname = "group", + }) + end + local a = TarF.new() + for _, e in list do + a:add(e.name, e.data or "", { dir = e.dir, mtime = e.mtime, mode = e.mode }) + local ent = a._byName[e.name] + ent.type, ent.link, ent.uname, ent.gname = e.type, e.link, e.uname, e.gname + end + local out, err = a:write({ format = w.format }) + t:check(out, w.format .. ": write: " .. tostring(err)) + local s = buffer.tostring(out :: buffer) + local ref = w.data + t:check(#s <= #ref and string.sub(ref, 1, #s) == s and not string.find(string.sub(ref, #s + 1), "[^%z]"), w.format .. ": bytes identical to tarfile") + local back = TarF.decode(Bytes.reader(out :: buffer)) + t:eq(#back:list(), #list, w.format .. ": round trip count") + for _, e in w.entries do + if e.data then + t:eq(buffer.tostring((back:read(e.name))), e.data, w.format .. ": round trip " .. e.name) + end + end +end + +-- 3. Archive values: add / read / write, other archives to tar +do + local a = TarF.new() + a:add("a.txt", "alpha", { mtime = 5 }) + a:add("b/", "", { dir = true }) + a:add("b/c.bin", buffer.fromstring("\0\1\2")) + a:add("a.txt", "replaced") + t:eq(#a:list(), 3, "add replaces by name") + local buf = F.save(a) + t:check(buf, "F.save(tar archive) uses the source format") + local back = F.load(buf) + t:eq(buffer.tostring(back:read("a.txt")), "replaced", "read back") + t:check(back:list()[2].dir, "directory entry") + local _, e = back:read("missing") + t:check(e and e.code == Err.ARG, "missing entry") + -- a gzip (single-stream archive) converts to a tar holding its one entry + local g = F.load(Fx.gzips[1].data) + local tb = F.save(g, nil, { format = "tar" }) + local ta = F.load(tb) + t:eq(ta:list()[1].name, "story.txt", "gzip -> tar entry name") + t:eq(ta:list()[1].size, Fx.gzips[1].size, "gzip -> tar entry size") +end + +-- 4. compressed tars through the api +for _, w in Fx.wrapped do + local a, err = F.load(w.data, { name = w.name }) + t:check(a, w.name .. ": " .. tostring(err)) + t:eq(a.format, "tar", w.name .. ": unwrapped to the tar") + t:eq(a.meta.compression, w.outer, w.name .. ": meta.compression") + check(a, Fx.innerEntries, w.name) + local outer = F.load(w.data, { name = w.name, unwrap = false }) + t:eq(outer.format, w.outer, w.name .. ": unwrap = false keeps the outer archive") + t:eq(outer:list()[1].name, "a.tar", w.name .. ": inner entry named after the file") +end + +-- 5. errors +do + local good = Fx.tars[1].data + local b = buffer.fromstring(good) + buffer.writeu8(b, 10, buffer.readu8(b, 10) + 1) + local _, e1 = TarF.decode(Bytes.reader(b)) + t:check(e1 and e1.code == Err.CORRUPT, "first header checksum: " .. tostring(e1)) + local _, e2 = TarF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 700)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated data: " .. tostring(e2)) + local _, e3 = TarF.encode({ kind = "image" }) + t:check(e3 and e3.code == Err.ARG, "encode a non-archive") + local u = TarF.new() + u:add(string.rep("y", 120), "x") + local _, e4 = u:write({ format = "ustar" }) + t:check(e4 and e4.code == Err.ARG, "ustar cannot hold a 120-byte name without a slash") + t:eq(TarF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 1024)))), 0, "zeros are not a tar") +end + +local samples = {} +for _, c in Fx.tars do + if #c.data <= 30000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + local a = TarF.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 30, keepHeader = 0 }) + +t:done() diff --git a/tests/archive/xz.luau b/tests/archive/xz.luau new file mode 100644 index 0000000..6dc0468 --- /dev/null +++ b/tests/archive/xz.luau @@ -0,0 +1,78 @@ +-- archive/xz tests: the contract, sniffing (.xz magic, conservative .lzma), every xz / .lzma fixture of +-- tools/fixtures/lzma.py read as a one-entry archive (entry names from opts.name), F.load through the registry, errors, +-- and the fuzz no-throw pass. +local T = require("@tests/T") +local Xz = require("@formats/archive/xz") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lzma") + +local t = T.suite("xz") + +t:eq(Xz.name, "xz", "name") +t:eq(Xz.category, "archive", "category") +t:check(Xz.caps.decode and not Xz.caps.encode, "caps") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +local n = 0 +for _, c in Fx.cases do + if c.kind == "xz" or c.kind == "alone" then + local want = Fx.corpora[c.corpus] + t:check(Xz.sniff(reader(c.data)) > 0, c.name .. ": sniff") + local a, err = Xz.decode(reader(c.data), { name = "dir/file.txt." .. (if c.kind == "xz" then "xz" else "lzma") }) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, 1, c.name .. ": one entry") + t:eq(list[1].name, "file.txt", c.name .. ": entry name") + t:eq(list[1].size, #want, c.name .. ": size") + t:check(a.meta.stream == true, c.name .. ": meta.stream") + local b = a:read("file.txt") + t:check(b and buffer.tostring(b) == want, c.name .. ": data") + n += 1 + end +end +t:note("%d xz / lzma files", n) + +-- sniff: not xz +t:eq(Xz.sniff(reader("PK\3\4 hello")), 0, "zip is not xz") +t:eq(Xz.sniff(reader("")), 0, "empty") +t:eq(Xz.sniff(reader(string.rep("\0", 40))), 0, "zeros are not .lzma") + +-- through the api +do + local c = Fx.cases[1] + for _, x in Fx.cases do + if x.name == "text/xz-6" then + c = x + end + end + local a, err = F.load(c.data, { name = "notes.txz" }) + t:check(a and a.kind == "archive" and a.format == "xz", "F.load: " .. tostring(err)) + t:eq(a:list()[1].name, "notes.tar", "txz -> tar entry name") + t:eq(F.detect(c.data), "xz", "F.detect") + local a2 = F.archive.load(c.data) + t:eq(a2:list()[1].name, "data", "unnamed entry") + local _, e2 = F.save(a2, nil, { format = "xz" }) + t:check(e2 and e2.code == Err.UNSUPPORTED, "xz is read-only: " .. tostring(e2)) + local _, e3 = F.load(string.sub(c.data, 1, 100), { format = "xz" }) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if (c.kind == "xz" or c.kind == "alone") and i % 5 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Xz.decode(Bytes.reader(b), { maxBytes = 2 ^ 20 }) + end, samples, { mutations = 6, garbage = 400 }) +end + +t:done() diff --git a/tests/archive/zst.luau b/tests/archive/zst.luau new file mode 100644 index 0000000..4908393 --- /dev/null +++ b/tests/archive/zst.luau @@ -0,0 +1,90 @@ +-- archive/zst tests: the contract, sniff (zstd and skippable-frame magic), decode of zstd CLI output into a one-entry +-- single-stream archive (entry name from opts.name, size, read), F.load detection by content, read-only errors, and +-- the fuzz no-throw pass. Fixtures: tools/fixtures/zstd.py (shared with tests/codecs/zstd.luau). +local T = require("@tests/T") +local F = require("@formats") +local Zst = require("@formats/archive/zst") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/zstd") + +local t = T.suite("zst") + +-- contract +t:eq(Zst.name, "zst", "name") +t:eq(Zst.category, "archive", "category") +t:check(Zst.caps.decode and not Zst.caps.encode, "caps") + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- sniff +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("text/l3").data))), 1, "sniff zstd") +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("skipfirst/frames").data))), 0.5, "sniff skippable frame") +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff other") +t:eq(Zst.sniff(Bytes.reader(buffer.create(0))), 0, "sniff empty") + +-- decode: one entry, named after the file +for _, name in { "text/l3", "runs/ultra22", "multi/frames", "empty/l3", "big/l19" } do + local c = case(name) + local a, err = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.zst" }) + t:check(a, name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, 1, name .. ": one entry") + t:eq(list[1].name, "notes.txt", name .. ": entry name") + t:eq(list[1].size, #Fx.corpora[c.corpus], name .. ": size") + t:eq(list[1].compressedSize, #c.data, name .. ": compressedSize") + t:check(a.meta.stream == true and a.kind == "archive" and a.format == "zst", name .. ": archive fields") + local data = a:read(list[1].name) + t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], name .. ": read") +end +do + local c = case("short/l3") + local a = Zst.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:eq(a:list()[1].name, "data", "no name -> data") + local a2 = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "backup.tzst" }) :: any + t:eq(a2:list()[1].name, "backup.tar", ".tzst -> .tar") + local _, e = a:read("nope") + t:check(e and e.code == Err.ARG, "missing entry") + local _, we = a:write() + t:check(we and we.code == Err.UNSUPPORTED, "read-only: " .. tostring(we)) + -- inside a bigger buffer (the reader's range) + local big = buffer.create(#c.data + 10) + buffer.writestring(big, 5, c.data) + local a3 = Zst.decode(Bytes.reader(big, 5, #c.data)) :: any + t:check(a3 and buffer.tostring(a3:read("data")) == Fx.corpora.short, "reader range") +end + +-- the api: detection by content, the name from opts +do + local c = case("text/l5") + local a, err = F.load(c.data, { name = "x/readme.md.zst" }) + t:check(a and a.format == "zst", "F.load detects zst: " .. tostring(err)) + t:eq(a:list()[1].name, "readme.md", "F.load entry name") + t:eq(F.detect(c.data), "zst", "F.detect") + local _, e = F.load(string.sub(c.data, 1, 30), { format = "zst" }) + t:check(e and e.code == Err.TRUNCATED, "truncated through the api: " .. tostring(e)) + local _, se = F.save(a, nil, { format = "zst" }) + t:check(se and se.code == Err.UNSUPPORTED, "no encoder") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 11 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Zst.decode(Bytes.reader(b), { maxBytes = 1e6 }) + end, samples, { mutations = 10, garbage = 500 }) +end + +t:done() diff --git a/tests/codecs/brotli.luau b/tests/codecs/brotli.luau new file mode 100644 index 0000000..8a9df45 --- /dev/null +++ b/tests/codecs/brotli.luau @@ -0,0 +1,126 @@ +-- codecs/Brotli tests: every fixture stream (reference encoder: qualities 0..11, windows 10..24, text / font / generic +-- modes, large windows) decodes to its corpus; consumedEnd; offsets inside a bigger buffer; the static dictionary; +-- hand-made streams (empty, metadata, uncompressed); maxBytes; truncated / corrupted / random input returns nil, Err +-- and never throws. Fixtures: tools/fixtures/brotli.py. +local T = require("@tests/T") +local Brotli = require("@formats/codecs/Brotli") +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/brotli") + +local t = T.suite("brotli") + +-- the static dictionary +do + local d = Brotli.dictionary() + t:check(d and buffer.len(d) == 122784, "dictionary size") + t:eq(buffer.readstring(d :: buffer, 0, 8), "timedown", "dictionary starts with the length-4 words") +end + +-- every case +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local out, e = Brotli.decompress(c.data) + t:check(out ~= nil, c.name .. ": " .. tostring(e)) + if buffer.tostring(out :: buffer) ~= want then + t:check(false, c.name .. ": output differs (" .. buffer.len(out :: buffer) .. " bytes, want " .. #want .. ")") + end + t:eq(e, #c.data, c.name .. ": consumed") + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +-- at an offset inside a bigger buffer, with trailing bytes +do + local c = Fx.cases[30] + local big = buffer.create(#c.data + 13) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 5, c.data) + local out, e = Brotli.decompress(big, 5, #c.data + 8) + t:check(out and buffer.tostring(out) == Fx.corpora[c.corpus] and e == 5 + #c.data, "at an offset") +end + +-- hand-made streams +do + local bytes = T.bytes + -- WBITS 16 (bit 0), ISLAST, ISLASTEMPTY: 0b110 = 6 + local o, e = Brotli.decompress(bytes({ 6 })) + t:check(o and buffer.len(o) == 0 and e == 1, "empty stream: " .. tostring(e)) + -- 0x3b: python brotli's empty stream (WBITS 22) + local o2 = Brotli.decompress(bytes({ 0x3b })) + t:check(o2 and buffer.len(o2) == 0, "empty stream (WBITS 22)") + local _, e0 = Brotli.decompress(bytes({})) + t:check(e0 and e0.code == Err.TRUNCATED, "empty input is TRUNCATED") + -- an uncompressed meta-block "hi": WBITS 16 [0], ISLAST 0, MNIBBLES 4 [00], MLEN-1 = 1 [1000 0000 0000 0000], + -- ISUNCOMPRESSED 1, pad, "hi", then ISLAST 1 ISLASTEMPTY 1 + -- bits LSB first: 0 | 0 | 00 | 1000 | 0000 0000 0000 | 1 -> byte0 = 0b00010000 = 0x10 (bits 0..7: 0,0,0,0,1,0,0,0) + -- byte1 = 0, byte2 = bits 16..23: 0,0,0,0 (rest of nibbles) 1 (ISUNCOMPRESSED) + pad 000 = 0x10 + local o3 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68, 0x69, 0x03 })) + t:check(o3 and buffer.tostring(o3) == "hi", "uncompressed meta-block") + local _, e3 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68 })) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated uncompressed block: " .. tostring(e3)) + -- nonzero padding at the end + local _, e4 = Brotli.decompress(bytes({ 0x10, 0x00, 0x10, 0x68, 0x69, 0x0b })) + t:check(e4 and e4.code == Err.CORRUPT, "nonzero padding: " .. tostring(e4)) + -- a metadata block (MNIBBLES 3, 1 byte length, 2 bytes skipped) before the last empty one + -- bits: WBITS 0 | ISLAST 0 | MNIBBLES 11 | reserved 0 | MSKIPBYTES 01 | len-1 = 1 (8 bits) | pad | 2 bytes | 11 + -- 0,0,1,1,0,1,0, then 8 bits of 1: 1,0,0,0,0,0,0,0, pad to 16 -> byte0 = 0b0 1 0 1 1 0 0 = bits0..7: 0,0,1,1,0,1,0,1 + local o5 = Brotli.decompress(bytes({ 0xAC, 0x00, 0xEE, 0xEE, 0x03 })) + t:check(o5 and buffer.len(o5) == 0, "metadata block skipped") + local ok, r1, r2 = pcall(Brotli.decompress, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") +end + +-- maxBytes +do + local c + for _, x in Fx.cases do + if x.corpus == "english" then + c = x + break + end + end + local _, e = Brotli.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e)) + local big + for _, x in Fx.cases do + if string.find(x.name, "large", 1, true) then + big = x + break + end + end + local _, e2 = Brotli.decompress(big.data, nil, nil, { largeWindow = false }) + t:check(e2 and e2.code == Err.UNSUPPORTED, "largeWindow = false: " .. tostring(e2)) +end + +-- a corrupted stream reports CORRUPT or TRUNCATED, never a wrong success with the right CRC +do + local bad = 0 + for i, c in Fx.cases do + if i % 17 == 0 and #c.data > 20 then + local b = buffer.fromstring(c.data) + buffer.writeu8(b, #c.data // 2, bit32.bxor(buffer.readu8(b, #c.data // 2), 0x5A)) + local out = Brotli.decompress(b) + if out and Crc32.of(out) == Crc32.of(buffer.fromstring(Fx.corpora[c.corpus])) then + bad += 1 + end + end + end + t:eq(bad, 0, "corrupted streams never decode to the original") +end + +-- truncation, corruption and garbage never throw +do + local samples = {} + for i, c in Fx.cases do + if i % 11 == 0 and #c.data > 8 then + table.insert(samples, if #c.data > 20000 then string.sub(c.data, 1, 20000) else c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Brotli.decompress(b) + end, samples, { mutations = 6, garbage = 3000 }) +end + +t:done() diff --git a/tests/codecs/bzip2.luau b/tests/codecs/bzip2.luau new file mode 100644 index 0000000..71a872d --- /dev/null +++ b/tests/codecs/bzip2.luau @@ -0,0 +1,103 @@ +-- codecs/Bzip2 tests: every fixture stream (Python bz2 = libbzip2, block sizes 1..9, RLE1 run edges, block-boundary +-- runs, random / skewed data, concatenated streams with trailing garbage) decodes exactly; offsets / consumedEnd; +-- maxBytes; CRC mismatches are Err.CHECKSUM; truncations are Err.TRUNCATED; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/bzip2.py. +local T = require("@tests/T") +local Bzip2 = require("@formats/codecs/Bzip2") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/bzip2") + +local t = T.suite("bzip2") + +t:eq(Bzip2.crc(buffer.fromstring("123456789")), 0xFC891918, "CRC-32/BZIP2 check value") + +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local out, consumed = Bzip2.decompress(c.data) + t:check(out ~= nil, c.name .. ": " .. tostring(consumed)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + if c.name ~= "multi/trailing" then + t:eq(consumed, #c.data, c.name .. ": consumedEnd") + end + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- inside a bigger buffer, at an offset +do + local c = case("text/l9") + local big = buffer.create(#c.data + 20) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 7, c.data) + local out, consumed = Bzip2.decompress(big, 7, #c.data + 5) + t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset") + t:eq(consumed, 7 + #c.data, "consumedEnd at an offset") +end + +-- maxBytes +do + local c = case("zeros/l9") + local _, e = Bzip2.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e)) + local ok = Bzip2.decompress(c.data, nil, nil, { maxBytes = 250000 }) + t:check(ok ~= nil, "maxBytes = exact size") +end + +-- block CRC / stream CRC mismatches +do + local c = case("text/l9") + local b = buffer.fromstring(c.data) + -- block CRC sits at bytes 10..13 (after "BZh9" + 6 magic bytes) + buffer.writeu8(b, 11, bit32.bxor(buffer.readu8(b, 11), 0x10)) + local _, e = Bzip2.decompress(b) + t:check(e and e.code == Err.CHECKSUM, "block CRC mismatch: " .. tostring(e)) + local s = case("one/l9") + local b2 = buffer.fromstring(s.data) + local n = buffer.len(b2) + buffer.writeu8(b2, n - 2, bit32.bxor(buffer.readu8(b2, n - 2), 0x01)) + local _, e2 = Bzip2.decompress(b2) + t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "stream CRC mismatch: " .. tostring(e2)) +end + +-- truncation -> TRUNCATED, bad magic -> CORRUPT, bad args -> ARG +do + local c = case("text/l1") + for _, cut in { 3, 10, 40, #c.data // 2, #c.data - 3 } do + local _, e = Bzip2.decompress(string.sub(c.data, 1, cut)) + t:check(e and e.code == Err.TRUNCATED, "truncated at " .. cut .. ": " .. tostring(e)) + end + local _, e = Bzip2.decompress("BZx9abcdefgh") + t:check(e and e.code == Err.CORRUPT, "bad magic") + local _, e2 = Bzip2.decompress(5 :: any) + t:check(e2 and e2.code == Err.ARG, "non-buffer") + local _, e3 = Bzip2.decompress("BZh9", -1) + t:check(e3 and e3.code == Err.ARG, "bad offset") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 4 == 0 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Bzip2.decompress(b) + end, samples, { mutations = 12, garbage = 1000, keepHeader = 4 }) + t:fuzz("decompress (no header kept)", function(b: buffer) + return Bzip2.decompress(b) + end, samples, { mutations = 4, garbage = 200 }) +end + +t:done() diff --git a/tests/codecs/lzma.luau b/tests/codecs/lzma.luau new file mode 100644 index 0000000..669b265 --- /dev/null +++ b/tests/codecs/lzma.luau @@ -0,0 +1,142 @@ +-- codecs/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp / +-- pb variants, raw LZMA1 / LZMA2, .lzma files, xz with every check type, BCJ and delta filters, multiple blocks, +-- multiple streams and stream padding) decodes to its corpus; consumed offsets; checksum / size / truncation errors; +-- maxBytes; the fuzz no-throw pass. Fixtures: tools/fixtures/lzma.py. +local T = require("@tests/T") +local Lzma = require("@formats/codecs/Lzma") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lzma") + +local t = T.suite("lzma") + +local function decode(c: any, b: buffer, opts: any?): (buffer?, any) + if c.kind == "raw" then + return Lzma.lzma(b, 0, nil, c.props, c.size, opts) + elseif c.kind == "raw2" then + return Lzma.lzma2(b, 0, nil, nil, nil, opts) + elseif c.kind == "alone" then + return Lzma.alone(b, 0, nil, opts) + end + return Lzma.xz(b, 0, nil, opts) +end + +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local b = buffer.fromstring(c.data) + local out, res = decode(c, b) + t:check(out ~= nil, c.name .. ": " .. tostring(res)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + if c.kind ~= "raw" then + t:eq(res, #c.data, c.name .. ": consumed") + end + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +-- at an offset inside a bigger buffer, with trailing bytes +do + for _, c in Fx.cases do + if c.kind == "xz" and c.name == "text/xz-6" then + local big = buffer.create(#c.data + 11) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 3, c.data) + local out, res = Lzma.xz(big, 3, #c.data) + t:check(out and buffer.tostring(out) == Fx.corpora.text and res == 3 + #c.data, "xz at an offset") + end + end +end + +-- errors +do + local xz, xzc + for _, c in Fx.cases do + if c.name == "text/xz-check-crc32" then + xz = c + elseif c.name == "text/xz-6" then + xzc = c + end + end + -- the check field: the last bytes before the index; flip a data bit near the end of the block instead + local b = buffer.fromstring(xzc.data) + local n = buffer.len(b) + -- footer magic + buffer.writeu8(b, n - 1, 0) + local _, e1 = Lzma.xz(b) + t:check(e1 and (e1.code == Err.CORRUPT or e1.code == Err.CHECKSUM), "bad footer: " .. tostring(e1)) + -- the stream header CRC + local b2 = buffer.fromstring(xz.data) + buffer.writeu8(b2, 8, bit32.bxor(buffer.readu8(b2, 8), 1)) + local _, e2 = Lzma.xz(b2) + t:check(e2 and e2.code == Err.CHECKSUM, "header crc: " .. tostring(e2)) + -- the block check (CRC-32 / CRC-64): flip a byte of the check field (found from the index: the 4 / 8 bytes before + -- the index indicator, which follows the block padding) + for _, c in { xz, xzc } do + local b3 = buffer.fromstring(c.data) + local n3 = buffer.len(b3) + local backward = (buffer.readu32(b3, n3 - 8) + 1) * 4 + local indexAt = n3 - 12 - backward + buffer.writeu8(b3, indexAt - 1, bit32.bxor(buffer.readu8(b3, indexAt - 1), 0x10)) + local _, e3 = Lzma.xz(b3) + t:check(e3 and e3.code == Err.CHECKSUM, c.name .. ": block check: " .. tostring(e3)) + end + -- truncations are TRUNCATED or CORRUPT, never a throw + local _, e4 = Lzma.xz(buffer.fromstring(string.sub(xzc.data, 1, #xzc.data // 2))) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated xz: " .. tostring(e4)) + -- maxBytes + local _, e5 = Lzma.xz(xzc.data, nil, nil, { maxBytes = 1000 }) + t:check(e5 and e5.code == Err.LIMIT, "maxBytes: " .. tostring(e5)) + local ok, r1, r2 = pcall(Lzma.xz, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e6 = Lzma.lzma("\0\0\0\0\0", 0, nil, "\255") + t:check(e6 and e6.code == Err.CORRUPT, "bad props byte: " .. tostring(e6)) +end + +-- raw LZMA with the size known: decoding stops at the size even without an end marker +do + for _, c in Fx.cases do + if c.kind == "raw" and #Fx.corpora[c.corpus] > 1000 then + local want = Fx.corpora[c.corpus] + local out = Lzma.lzma(c.data, 0, nil, { lc = 3, lp = 0, pb = 2 }, nil) + if c.name == c.corpus .. "/raw-lc3-lp0-pb2" then + t:check(out and buffer.tostring(out) == want, c.name .. ": table props, end marker") + end + local part = Lzma.lzma(c.data, 0, nil, c.props, 500) + t:check(part and buffer.tostring(part) == string.sub(want, 1, 500), c.name .. ": a prefix by size") + end + end +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 7 == 0 and #c.data > 16 and #c.data < 40000 then + table.insert(samples, c) + end + end + local xs, as, rs = {}, {}, {} + for _, c in samples do + if c.kind == "xz" then + table.insert(xs, c.data) + elseif c.kind == "alone" then + table.insert(as, c.data) + else + table.insert(rs, c.data) + end + end + t:fuzz("xz", function(b: buffer) + return Lzma.xz(b, 0, nil, { maxBytes = 1 * 2 ^ 20 }) + end, xs, { mutations = 6, garbage = 300 }) + t:fuzz("alone", function(b: buffer) + return Lzma.alone(b, 0, nil, { maxBytes = 1 * 2 ^ 20 }) + end, as, { mutations = 6, garbage = 300 }) + t:fuzz("lzma2", function(b: buffer) + return Lzma.lzma2(b, 0, nil, nil, nil, { maxBytes = 1 * 2 ^ 20 }) + end, rs, { mutations = 4, garbage = 1000 }) + t:fuzz("lzma", function(b: buffer) + return Lzma.lzma(b, 0, nil, "\93", nil, { maxBytes = 1 * 2 ^ 20 }) + end, rs, { mutations = 2, garbage = 1000 }) +end + +t:done() diff --git a/tests/codecs/raster.luau b/tests/codecs/raster.luau new file mode 100644 index 0000000..8103a25 --- /dev/null +++ b/tests/codecs/raster.luau @@ -0,0 +1,259 @@ +-- codecs/Raster tests: exact coverage of axis-aligned rectangles at fractional positions; areas of circles; random +-- polygons and curves under random transforms against an independent 12 x 12 supersampled winding-number reference +-- (both fill rules); clipping, the stroker (width, caps, joins against analytic areas), fill() compositing and paint +-- functions; malformed paths never throw. Glyph rendering against FreeType is in tests/font/ttf.luau. +local T = require("@tests/T") +local R = require("@formats/codecs/Raster") +local Types = require("@formats/Types") + +local t = T.suite("raster") + +local function sum(m: any): number + if not m then + return 0 + end + local s = 0 + for i = 0, m.width * m.height - 1 do + s += buffer.readu8(m.coverage, i) + end + return s / 255 +end + +local function at(m: any, x: number, y: number): number + local i, j = x - m.x, y - m.y + if i < 0 or j < 0 or i >= m.width or j >= m.height then + return 0 + end + return buffer.readu8(m.coverage, j * m.width + i) +end + +-- 1. rectangles: exact per-pixel coverage +do + local p = R.path():rect(1.25, 2.5, 3.5, 2) + local m = R.mask(p) :: any + t:check(m, "rect mask") + t:eq(m.x, 1, "rect x") + t:eq(m.y, 2, "rect y") + t:eq(m.width, 4, "rect width") + t:eq(m.height, 3, "rect height") + -- row 2 covers y 2.5..3 (half), columns: 1 covers 0.75, 2-3 full, 4 covers 0.75 + t:eq(at(m, 1, 2), math.floor(0.75 * 0.5 * 255 + 0.5), "corner pixel") + t:eq(at(m, 2, 2), math.floor(0.5 * 255 + 0.5), "top edge pixel") + t:eq(at(m, 2, 3), 255, "interior pixel") + t:eq(at(m, 4, 3), math.floor(0.75 * 255 + 0.5), "right edge pixel") + t:check(math.abs(sum(m) - 7) < 0.02, "rect area 7: " .. sum(m)) + -- reversed orientation gives the same coverage + local q = R.path():moveTo(1.25, 2.5):lineTo(1.25, 4.5):lineTo(4.75, 4.5):lineTo(4.75, 2.5):close() + t:check(math.abs(sum(R.mask(q)) - 7) < 0.02, "reversed rect") +end + +-- 2. circles: area pi r^2 (cubic approximation error ~ 2.7e-4 r) +for _, r in { 3, 10.5, 40 } do + local m = R.mask(R.path():ellipse(50.3, 50.7, r, r)) + local a = sum(m) + t:check(math.abs(a - math.pi * r * r) < 0.01 * math.pi * r * r + 1, string.format("circle r=%g area %.2f", r, a)) +end + +-- 3. random paths against a supersampled winding reference +local function wind(polys: { { number } }, px: number, py: number): number + local w = 0 + for _, poly in polys do + local n = #poly + local x0, y0 = poly[n - 1], poly[n] + for i = 1, n - 1, 2 do + local x1, y1 = poly[i], poly[i + 1] + if y0 <= py then + if y1 > py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) > 0 then + w += 1 + end + elseif y1 <= py and (x1 - x0) * (py - y0) - (px - x0) * (y1 - y0) < 0 then + w -= 1 + end + x0, y0 = x1, y1 + end + end + return w +end + +local rand = T.rng(7) +local function rf(a: number, b: number): number + return a + (b - a) * rand(100000) / 100000 +end + +local worst, total, count = 0, 0, 0 +for case = 1, 24 do + local p = R.path() + for _ = 1, 1 + rand(3) do + p:moveTo(rf(0, 28), rf(0, 28)) + for _ = 1, 2 + rand(5) do + local k = rand(3) + if k == 0 then + p:lineTo(rf(0, 28), rf(0, 28)) + elseif k == 1 then + p:quadTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28)) + else + p:cubicTo(rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28), rf(0, 28)) + end + end + p:close() + end + local ang = rf(0, 6.28) + local tr = R.multiply(R.translate(rf(-5, 5), rf(-5, 5)), R.multiply(R.rotate(ang), R.scale(rf(0.5, 1.2), rf(0.5, 1.2)))) + local rule = if case % 2 == 0 then "evenodd" else "nonzero" + local clip = { 0, 0, 32, 32 } + local m = R.mask(p, { transform = tr, rule = rule :: any, clip = clip, tolerance = 0.05 }) + local polys = R.flatten(p, tr, 0.01) + local err, n, mx = 0, 0, 0 + for y = 0, 31 do + for x = 0, 31 do + local inside = 0 + for sy = 0, 11 do + for sx = 0, 11 do + local w = wind(polys, x + (sx + 0.5) / 12, y + (sy + 0.5) / 12) + if (rule == "nonzero" and w ~= 0) or (rule == "evenodd" and w % 2 == 1) then + inside += 1 + end + end + end + local want = inside / 144 + local got = if m then at(m, x, y) / 255 else 0 + local d = math.abs(got - want) + err += d + n += 1 + if d > mx then + mx = d + end + end + end + total += err + count += n + worst = math.max(worst, err / n) + -- the area rules approximate where edges of opposite winding meet inside one pixel; on average they agree + t:check(err / n < 0.015, string.format("case %d (%s): mean abs error %.4f (max %.3f)", case, rule, err / n, mx)) +end +t:note("random paths: mean abs coverage error %.4f (worst case mean %.4f) vs 12x12 supersampling", total / count, worst) + +-- 4. even-odd vs nonzero on two nested squares of the same orientation +do + local p = R.path():rect(0, 0, 10, 10):rect(3, 3, 4, 4) + t:check(math.abs(sum(R.mask(p)) - 100) < 0.01, "nonzero fills the hole") + t:check(math.abs(sum(R.mask(p, { rule = "evenodd" })) - 84) < 0.01, "evenodd leaves the hole") + -- opposite orientation: a hole under both rules + local q = R.path():rect(0, 0, 10, 10):moveTo(3, 3):lineTo(3, 7):lineTo(7, 7):lineTo(7, 3):close() + t:check(math.abs(sum(R.mask(q)) - 84) < 0.01, "nonzero hole with opposite winding") +end + +-- 5. clipping: a shape larger than the clip, partly outside on every side +do + local m = R.mask(R.path():rect(-20.5, -3.25, 100, 50), { clip = { 0, 0, 16, 8 } }) :: any + t:check(m and m.x == 0 and m.y == 0 and m.width == 16 and m.height == 8, "clipped bounds") + t:check(math.abs(sum(m) - 128) < 0.01, "clipped area " .. sum(m)) + local m2 = R.mask(R.path():moveTo(-50, 4):lineTo(60, 4.5):lineTo(60, 6):lineTo(-50, 5):close(), { clip = { 0, 0, 10, 10 } }) + t:check(m2 ~= nil, "a sliver crossing the clip") + t:check(R.mask(R.path():rect(20, 20, 5, 5), { clip = { 0, 0, 10, 10 } }) == nil, "outside the clip is empty") +end + +-- 6. strokes: a line of length L and width w covers L*w (butt), L*w + w^2 (square), L*w + pi w^2/4 (round) +do + local line = R.path():moveTo(5, 10):lineTo(35, 10) + local a = sum(R.mask(R.stroke(line, { width = 4 }))) + t:check(math.abs(a - 120) < 0.05, "butt stroke area " .. a) + a = sum(R.mask(R.stroke(line, { width = 4, cap = "square" }))) + t:check(math.abs(a - 136) < 0.05, "square cap area " .. a) + a = sum(R.mask(R.stroke(line, { width = 4, cap = "round", tolerance = 0.01 }))) + t:check(math.abs(a - (120 + math.pi * 4)) < 0.3, "round cap area " .. a) + -- a closed square outline of side 20, width 2, miter joins: outer 22^2 - inner 18^2 + local sq = R.path():rect(10, 10, 20, 20) + a = sum(R.mask(R.stroke(sq, { width = 2 }))) + t:check(math.abs(a - (484 - 324)) < 0.1, "mitered square outline " .. a) + a = sum(R.mask(R.stroke(sq, { width = 2, join = "bevel" }))) + t:check(math.abs(a - (160 - 4 * 0.5)) < 0.1, "bevelled square outline " .. a) + a = sum(R.mask(R.stroke(sq, { width = 2, join = "round", tolerance = 0.01 }))) + t:check(math.abs(a - (160 - 4 * (1 - math.pi / 4))) < 0.15, "rounded square outline " .. a) + -- a sharp zig-zag past the miter limit falls back to bevels; still covered without holes + local zig = R.path():moveTo(0, 0):lineTo(20, 2):lineTo(0, 4) + t:check(sum(R.mask(R.stroke(zig, { width = 1, miterLimit = 4 }))) > 30, "zig-zag stroke") + -- a curve stroke: a circle outline of radius 10, width 1: area 2 pi r w + a = sum(R.mask(R.stroke(R.path():ellipse(20, 20, 10, 10), { width = 1, join = "round", tolerance = 0.01 }))) + t:check(math.abs(a - 2 * math.pi * 10) < 1, "circle outline " .. a) +end + +-- 7. fill onto an image: colours, opacity, paint functions, compositing over existing pixels +do + local img = Types.Image.new(8, 8) + t:check(R.fill(img, R.path():rect(0, 0, 4, 8), { 255, 0, 0, 255 }), "fill red") + t:eq(buffer.readu32(img.pixels, 0), 0xFF0000FF, "opaque red pixel") + t:eq(buffer.readu32(img.pixels, 4 * 5), 0, "untouched pixel") + R.fill(img, R.path():rect(2, 0, 4, 8), { 0, 0, 255, 255 }, { opacity = 0.5 }) + local p = 4 * 3 + t:check(buffer.readu8(img.pixels, p) == 128 and buffer.readu8(img.pixels, p + 2) == 128 and buffer.readu8(img.pixels, p + 3) == 255, "half blue over red") + p = 4 * 5 + t:check(buffer.readu8(img.pixels, p + 2) == 255 and buffer.readu8(img.pixels, p + 3) == 128, "half blue over transparent") + local calls = 0 + R.fill(img, R.path():rect(0, 7, 8, 1), function(x: number, _y: number) + calls += 1 + return x * 30, 0, 0, 255 + end) + t:eq(calls, 8, "paint function per covered pixel") + t:eq(buffer.readu8(img.pixels, (7 * 8 + 2) * 4), math.floor(2.5 * 30 + 0.5), "paint at the pixel centre") + -- a transform scaling a unit square to the whole image + local img2 = Types.Image.new(4, 4) + R.fill(img2, R.path():rect(0, 0, 1, 1), { 0, 255, 0, 255 }, { transform = R.scale(4) }) + t:eq(buffer.readu32(img2.pixels, 4 * 15), 0xFF00FF00, "transformed fill") + local inv = R.invert({ 2, 0, 0, 4, 3, 5 }) :: any + local x, y = R.apply(inv, R.apply({ 2, 0, 0, 4, 3, 5 }, 7, 11)) + t:check(math.abs(x - 7) < 1e-9 and math.abs(y - 11) < 1e-9, "invert") + t:check(R.fill(img2, R.path():rect(0, 0, 1, 1), function() + error("boom") + end) == false, "a failing paint function returns false") +end + +-- 8. malformed paths and huge / non-finite coordinates never throw +do + local bad: { any } = { + { { op = "moveTo" }, { op = "lineTo", 1 }, { op = "quadTo", 1, 2, "x", 4 }, { op = "close" } }, + { { op = "lineTo", 0 / 0, 1 }, { op = "lineTo", 5, 5 }, { op = "lineTo", 0, 5 } }, + { { op = "moveTo", 0, 0 }, { op = "lineTo", math.huge, 1 }, { op = "lineTo", 1, 1e300 } }, + { { op = "moveTo", -1e6, -1e6 }, { op = "lineTo", 1e6, -1e6 }, { op = "lineTo", 1e6, 1e6 } }, + { 5, "x", { op = "cubicTo" }, { op = 3 } }, + {}, + } + local threw = 0 + for i, p in bad do + for _, rule in { "nonzero", "evenodd" } do + local ok = pcall(function() + R.mask(p, { rule = rule :: any, clip = { 0, 0, 64, 64 } }) + R.mask(p, { transform = { 0 / 0, 0, 0, 1, 0, 0 } }) + R.stroke(p, { width = 3, cap = "round", join = "round" }) + R.fill(Types.Image.new(16, 16), p, { 1, 2, 3, 4 }, { transform = { 1e9, 0, 0, 1e9, 0, 0 } }) + end) + if not ok then + threw += 1 + print(" threw on bad path " .. i) + end + end + end + local _, why = R.mask(R.path():rect(0, 0, 5000, 5000), { maxPixels = 1000 }) + t:eq(why, "limit", "over maxPixels") + t:check(R.mask("nope") == nil and R.mask(nil) == nil, "non-paths") + -- random command soup through the fuzz helper: bytes -> commands + t:fuzz("mask", function(b: buffer) + local cmds = {} + local ops = { "moveTo", "lineTo", "quadTo", "cubicTo", "close" } + local i = 0 + while i + 1 < buffer.len(b) do + local c: any = { op = ops[buffer.readu8(b, i) % 5 + 1] } + for k = 1, 6 do + local q = i + k + c[k] = if q < buffer.len(b) then (buffer.readi8(b, q)) * 0.73 else 0 + end + table.insert(cmds, c) + i += 7 + end + R.mask(cmds, { rule = if buffer.len(b) % 2 == 0 then "evenodd" else "nonzero", clip = { -10, -10, 40, 40 } }) + return R.stroke(cmds, { width = 2.5, cap = "square", join = "miter" }) + end, { "\0\1\2\3\4\5\6\1\9\9\9\9\9\9\2\1\2\3\4\5\6\3\1\2\3\4\5\6\4" }, { garbage = 400 }) + t:eq(threw, 0, "malformed paths never throw") +end + +t:done() diff --git a/tests/codecs/zstd.luau b/tests/codecs/zstd.luau new file mode 100644 index 0000000..8e25cf6 --- /dev/null +++ b/tests/codecs/zstd.luau @@ -0,0 +1,115 @@ +-- codecs/Zstd tests: every fixture case (the zstd CLI at levels 1..19, --ultra -22, --fast, --long, small windows, +-- with / without checksum and content size, multi-frame and skippable frames, empty input) decodes to its corpus; +-- offsets / consumedEnd; XXH64 vectors; checksum, limit and error codes; truncated / corrupted / random input never +-- throws. Fixtures: tools/fixtures/zstd.py. +local T = require("@tests/T") +local Zstd = require("@formats/codecs/Zstd") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/zstd") + +local t = T.suite("zstd") + +-- XXH64 reference values (xxhsum -H64) +do + local function hex(s: string): string + local hi, lo = Zstd.xxh64(buffer.fromstring(s)) + return string.format("%08x%08x", hi, lo) + end + t:eq(hex(""), "ef46db3751d8e999", "xxh64 empty") + t:eq(hex("a"), "d24ec4f1a98c6e5b", "xxh64 a") + t:eq(hex("abc"), "44bc2cf5ad770999", "xxh64 abc") + t:eq(hex("Nobody inspects the spammish repetition"), "fbcea83c8a378bf1", "xxh64 sentence") + t:eq(hex(string.rep("0123456789", 10)), "f80e7b96315afffa", "xxh64 100 bytes") +end + +-- every case decodes to its corpus +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local b = buffer.fromstring(c.data) + local out, consumed = Zstd.decompress(b) + t:check(out ~= nil, c.name .. ": " .. tostring(consumed)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + t:eq(consumed, #c.data, c.name .. ": consumed") + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- at an offset inside a bigger buffer, and string input +do + local c = case("text/l3") + local big = buffer.create(#c.data + 20) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 7, c.data) + local out, consumed = Zstd.decompress(big, 7, #c.data) + t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset") + t:eq(consumed, 7 + #c.data, "consumed at an offset") + t:check(buffer.tostring((Zstd.decompress(c.data))) == Fx.corpora.text, "string input") + t:check(Zstd.isFrame(buffer.fromstring(c.data)), "isFrame") + t:check(not Zstd.isFrame(buffer.fromstring("abcd")), "isFrame on other data") + -- trailing garbage is an error, as zstd -d says + local _, e = Zstd.decompress(c.data .. "junk") + t:check(e and e.code == Err.CORRUPT, "trailing garbage: " .. tostring(e)) +end + +-- checksum mismatch (the last 4 bytes), and verify = false skips it +do + local c = case("text/l9") + local b = buffer.fromstring(c.data) + local n = buffer.len(b) + buffer.writeu8(b, n - 1, bit32.bxor(buffer.readu8(b, n - 1), 0x10)) + local out, e = Zstd.decompress(b) + t:check(out == nil and Err.is(e) and e.code == Err.CHECKSUM, "checksum mismatch: " .. tostring(e)) + local out2 = Zstd.decompress(b, nil, nil, { verify = false }) + t:check(out2 and buffer.tostring(out2) == Fx.corpora.text, "verify = false") +end + +-- limits and arguments +do + local c = case("text/l3") + local _, e = Zstd.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes with a content size: " .. tostring(e)) + local s = case("text/stdin") + local _, e2 = Zstd.decompress(s.data, nil, nil, { maxBytes = 1000 }) + t:check(e2 and e2.code == Err.LIMIT, "maxBytes without a content size: " .. tostring(e2)) + local ok, r1, r2 = pcall(Zstd.decompress, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e3 = Zstd.decompress("") + t:check(e3 and e3.code == Err.TRUNCATED, "empty input is TRUNCATED: " .. tostring(e3)) + local _, e4 = Zstd.decompress("\40\181\47\253\0") + t:check(e4 and e4.code == Err.TRUNCATED, "header only: " .. tostring(e4)) + -- a dictionary ID: FHD with Dictionary_ID_flag = 1, single segment, then a 1-byte dictionary id and 1-byte size + local _, e5 = Zstd.decompress("\40\181\47\253\33\7\0\1\0\0") + t:check(e5 and e5.code == Err.UNSUPPORTED, "dictionary: " .. tostring(e5)) + -- reserved block type + local _, e6 = Zstd.decompress("\40\181\47\253\32\0\7\0\0") + t:check(e6 and e6.code == Err.CORRUPT, "reserved block type: " .. tostring(e6)) +end + +-- truncation, corruption and garbage never throw +do + local samples = {} + for i, c in Fx.cases do + if i % 5 == 0 and #c.data > 8 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Zstd.decompress(b) + end, samples, { mutations = 12, garbage = 2000 }) + -- keep the frame header intact so the mutations reach the blocks + t:fuzz("decompress (blocks)", function(b: buffer) + return Zstd.decompress(b, nil, nil, { verify = false, maxBytes = 1e6 }) + end, samples, { mutations = 40, garbage = 0, keepHeader = 12, seed = 99 }) +end + +t:done() diff --git a/tests/containers/tar.luau b/tests/containers/tar.luau new file mode 100644 index 0000000..fb2bc0d --- /dev/null +++ b/tests/containers/tar.luau @@ -0,0 +1,165 @@ +-- containers/Tar and containers/Archive tests: hand-made headers for the edge cases the reference archives do not hit +-- (base-256 numbers, the historical signed checksum, GNU 'K' long links, pax 'g' global records, pax size overrides, +-- v7 headers without magic, a missing end-of-archive marker), the writer's GNU / pax extensions (long links, fractional +-- and negative mtimes), and Archive helpers (streamName, entries of foreign archive values, failing loaders). +local T = require("@tests/T") +local Tar = require("@formats/containers/Tar") +local Archive = require("@formats/containers/Archive") +local Err = require("@formats/core/Err") + +local t = T.suite("containers/tar") + +-- a header block built by hand +local function hdr(fields: { [string]: any }): buffer + local h = buffer.create(512) + buffer.writestring(h, 0, fields.name or "f") + buffer.writestring(h, 100, fields.mode or "0000644\0") + buffer.writestring(h, 124, fields.size or "00000000000\0") + buffer.writestring(h, 136, fields.mtime or "00000000000\0") + buffer.writestring(h, 156, fields.type or "0") + if fields.link then + buffer.writestring(h, 157, fields.link) + end + if fields.magic ~= false then + buffer.writestring(h, 257, "ustar\00000") + end + if fields.raw then + for at, v in fields.raw do + buffer.writeu8(h, at, v) + end + end + buffer.writestring(h, 148, " ") + local sum, signed = 0, 0 + for i = 0, 511 do + local v = buffer.readu8(h, i) + sum += v + signed += if v >= 128 then v - 256 else v + end + buffer.writestring(h, 148, string.format("%06o\0 ", if fields.signed then signed % 0x40000 else sum)) + return h +end +local function cat(parts: { any }): buffer + local s = {} + for _, p in parts do + table.insert(s, if type(p) == "string" then p else buffer.tostring(p)) + end + return buffer.fromstring(table.concat(s)) +end +local function block(s: string): string + return s .. string.rep("\0", (512 - #s % 512) % 512) +end +local END = string.rep("\0", 1024) + +-- base-256 size (GNU), checksum with the signed sum, no end marker +do + local raw = { [124] = 0x80 } + for i = 125, 134 do + raw[i] = 0 + end + raw[135] = 5 + local b = cat({ hdr({ name = "big\200", raw = raw, signed = true }), block("hello") }) + local list, err = Tar.read(b) + t:check(list, "base-256 / signed checksum: " .. tostring(err)) + t:eq(list[1].size, 5, "base-256 size") + t:check(Tar.valid(b, 0), "valid() accepts the signed sum") +end + +-- GNU long link ('K'), pax global + per-file records, v7 header +do + local rec = "21 path=from/pax.txt\n" + local glob = "20 uname=globaluser\n" + local b = cat({ + hdr({ name = "././@LongLink", type = "K", size = string.format("%011o\0", 131) }), + block(string.rep("L", 130) .. "\0"), + hdr({ name = "sym", type = "2", link = "short" }), + hdr({ name = "pax_global", type = "g", size = string.format("%011o\0", #glob) }), + block(glob), + hdr({ name = "PaxHeaders/x", type = "x", size = string.format("%011o\0", #rec + 15) }), + block(rec .. "15 size=000003\n"), + hdr({ name = "ignored-name", size = "00000000077\0" }), + block("abc"), + hdr({ name = "v7file", magic = false, size = "00000000002\0", mtime = "12345670123\0" }), + block("v7"), + END, + }) + local list, err = Tar.read(b) + t:check(list, "extensions: " .. tostring(err)) + t:eq(#list, 3, "meta records are not entries") + t:eq(list[1].link, string.rep("L", 130), "GNU long link") + t:eq(list[2].name, "from/pax.txt", "pax path") + t:eq(list[2].size, 3, "pax size overrides the header") + t:eq(list[2].uname, "globaluser", "pax global record") + t:eq(list[3].name, "v7file", "v7 header") + t:eq(list[3].mtime, tonumber("12345670123", 8), "octal mtime") + t:eq(list[3].uname, "globaluser", "global records apply to later entries") +end + +-- errors +do + local _, e1 = Tar.read(cat({ hdr({ size = "00000002000\0" }), block("x") })) + t:check(e1 and e1.code == Err.TRUNCATED, "data past the end: " .. tostring(e1)) + local _, e2 = Tar.read(cat({ hdr({ type = "x", size = "00000000010\0" }), block("garbage!"), END })) + t:check(e2 and e2.code == Err.CORRUPT, "bad pax record: " .. tostring(e2)) + local good = hdr({}) + local bad = cat({ good, hdr({ name = "two" }) }) + buffer.writeu8(bad, 513, 77) + local _, e3 = Tar.read(bad) + t:check(e3 and e3.code == Err.CHECKSUM, "second header checksum: " .. tostring(e3)) + local list = Tar.read(buffer.create(0)) + t:check(list and #list == 0, "empty input is an empty archive") +end + +-- writer extensions +do + local long = string.rep("n", 120) + for _, fmt in { "gnu", "pax" } do + local out = Tar.write({ + { name = long, data = buffer.fromstring("x"), mtime = -5.25 }, + { name = "l", type = "2", link = string.rep("k", 150) }, + }, { format = fmt :: any }) :: buffer + local list = Tar.read(out) :: any + t:eq(list[1].name, long, fmt .. ": long name") + t:eq(list[2].link, string.rep("k", 150), fmt .. ": long link") + if fmt == "pax" then + t:eq(list[1].mtime, -5.25, "pax fractional negative mtime") + end + end + local _, e = Tar.write({ { name = "" } }) + t:check(e and e.code == Err.ARG, "empty name") +end + +-- Archive helpers +do + t:eq(Archive.streamName({ name = "/x/y/notes.txt.gz" }, { "gz" }), "notes.txt", "streamName strips the extension") + t:eq(Archive.streamName({ name = "a.tbz2" }, { "bz2" }), "a.tar", "streamName .tbz2") + t:eq(Archive.streamName(nil, { "gz" }), "data", "streamName default") + t:eq(Archive.streamName({ name = "plain" }, { "gz" }), "plain", "streamName without an extension") + local foreign = { + kind = "archive", + list = function() + return { { name = "a", size = 1, dir = false } } + end, + read = function() + error("boom") + end, + } + local items = Archive.entries(foreign) :: any + t:eq(#items, 1, "entries of a foreign archive") + local b, e = items[1].read() + t:check(b == nil and e and e.code == Err.CORRUPT, "a throwing read() becomes an Err") + t:check(Archive.entries({ kind = "image" }) == nil, "not an archive") + local a = Archive.new("x") + Archive.put(a, { name = "f", size = 1, dir = false, load = function() + error("bad") + end }) + local _, e2 = a:read("f") + t:check(e2 and e2.code == Err.CORRUPT, "a throwing loader becomes an Err") + local _, e3 = a:write() + t:check(e3 and e3.code == Err.UNSUPPORTED, "read-only archives") +end + +t:fuzz("read", function(b: buffer) + return Tar.read(b) +end, { buffer.tostring(Tar.write({ { name = string.rep("p", 130), data = buffer.fromstring("abc") }, { name = "d", dir = true } }) :: buffer) }, { mutations = 60 }) + +t:done() diff --git a/tests/font/bmfont.luau b/tests/font/bmfont.luau new file mode 100644 index 0000000..46ae665 --- /dev/null +++ b/tests/font/bmfont.luau @@ -0,0 +1,166 @@ +-- font/bmfont tests: the text, XML and binary descriptors (an independent Python writer, glyphs rendered by FreeType) +-- decode to the reference description; each variant re-encodes to every variant and decodes back unchanged (binary: +-- byte-identical to the Python writer); Font methods (glyphIndex / advance / kern); lazy pages through opts.loadPage +-- and the page PNG (glyph crops against FreeType's bitmaps); bake() from a TrueType font; errors; the fuzz pass. +-- Fixtures: tools/fixtures/bmfont.py. +local T = require("@tests/T") +local F = require("@formats") +local Bmfont = require("@formats/font/bmfont") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/bmfont") + +local t = T.suite("bmfont") +t:eq(Bmfont.name, "bmfont", "name") + +local CHAR_KEYS = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } + +local function sameDesc(got: any, want: any, label: string, faceQuotes: boolean) + local face = want.info.face + if not faceQuotes then + face = string.gsub(face, '"', "") + end + t:eq(got.info.face, face, label .. ": face") + for _, k in { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } do + t:eq(got.info[k], want.info[k], label .. ": info." .. k) + end + for i = 1, 4 do + t:eq(got.info.padding[i], want.info.padding[i], label .. ": padding") + end + t:eq(got.info.spacing[1] .. "," .. got.info.spacing[2], want.info.spacing[1] .. "," .. want.info.spacing[2], label .. ": spacing") + for k, v in want.common do + t:eq(got.common[k], v, label .. ": common." .. k) + end + t:eq(#got.pages, #want.pages, label .. ": pages") + t:eq(got.pages[1], want.pages[1], label .. ": page file") + t:eq(#got.chars, #want.chars, label .. ": char count") + for i, c in want.chars do + for _, k in CHAR_KEYS do + t:eq(got.chars[i][k], c[k], string.format("%s: char %d %s", label, c.id, k)) + end + end + t:eq(#got.kernings, #want.kernings, label .. ": kerning count") + for i, k in want.kernings do + local g = got.kernings[i] + t:check(g[1] == k[1] and g[2] == k[2] and g[3] == k[3], label .. ": kerning " .. i) + end +end + +-- 1. the three encodings +local fonts = {} +for _, v in { "text", "xml", "binary" } do + local f, err = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx[v]))) + t:check(f, v .. ": " .. tostring(err)) + t:eq(f.meta.variant, v, v .. ": variant") + sameDesc(f.meta.bmfont, Fx.desc, v, v ~= "text") + fonts[v] = f + t:eq(F.detect(Fx[v]), "bmfont", v .. ": F.detect") +end + +-- 2. re-encode every variant to every variant +for from, f in fonts do + for _, to in { "text", "xml", "binary" } do + local b, err = Bmfont.encode(f, { variant = to :: any }) + t:check(b, from .. " -> " .. to .. ": " .. tostring(err)) + local back = Bmfont.decode(Bytes.reader(b :: buffer)) + t:check(back and back.meta.variant == to, from .. " -> " .. to .. ": decodes") + sameDesc(back.meta.bmfont, Fx.desc, from .. " -> " .. to, from ~= "text" and to ~= "text") + if from == "binary" and to == "binary" then + t:eq(buffer.tostring(b :: buffer), Fx.binary, "binary re-encode is byte-identical to the reference writer") + end + end +end +t:eq(buffer.tostring(F.save(fonts.xml, nil, { format = "fnt" })):sub(1, 5), " 0 and gV > 0, "glyphIndex") + t:eq(f:glyphIndex(0x1F600), 0, "missing glyph") + t:eq(f:advance(gA), Fx.desc.chars[gA].xadvance, "advance") + t:eq(f:kern(gA, gV), Fx.desc.kernings[2][3], "kern A V") + t:eq(f:kern(gV, gA), Fx.desc.kernings[9][3], "kern V A") + t:eq(f.unitsPerEm, 24, "size") + t:check(f:outline(gA) == nil, "bitmap fonts have no outline") + t:check(f:rasterize(gA, 24) == nil, "no pages loaded yet") + local ok, e = f:loadPages() + t:check(not ok and e and e.code == Err.ARG, "loadPages without a loader") +end + +-- 4. lazy pages: the api attaches opts.loadPage; the PNG goes through F.load +do + local asked = {} + local f = F.load(Fx.binary, { + loadPage = function(file: string) + table.insert(asked, file) + return Fx.page + end, + }) + t:check(f and f.pages == nil and #asked == 0, "pages are lazy") + local crcs = {} + for _, c in Fx.crops do + crcs[c.id] = c.crc + end + local n = 0 + for _, c in Fx.desc.chars do + local img = f:rasterize(f:glyphIndex(c.id), 24) + t:check(img and img.format == "alpha8" and img.width == c.width, "rasterize " .. c.id) + t:eq(Crc32.of(img.pixels), crcs[c.id], "glyph crop " .. c.id .. " = FreeType's bitmap") + t:eq(img.meta.left, c.xoffset, "left") + n += 1 + end + t:eq(#asked, 1, "page loaded once") + t:eq(asked[1], "karla_0.png", "page file name") + t:note("%d glyph crops from the lazily loaded page match FreeType", n) +end + +-- 5. bake from a TrueType font +do + local ttf = F.font.load(Fx.ttf) + t:check(ttf, "ttf loads") + local baked, err = Bmfont.bake(ttf, { px = 20, chars = "Hello, wörld! AV" }) + t:check(baked, "bake: " .. tostring(err)) + t:eq(#baked.meta.bmfont.chars, 13, "unique characters baked") + t:check(baked.pages and #baked.pages == 1, "one page") + local g = baked:glyphIndex(string.byte("H")) + local a = baked:rasterize(g, 20) + local b = ttf:rasterize(ttf:glyphIndex(string.byte("H")), 20) + t:check(a and b and a.width == b.width and a.height == b.height, "baked glyph size") + t:eq(Crc32.of(a.pixels), Crc32.of(b.pixels), "baked glyph pixels = rasterize") + t:eq(a.meta.left, b.meta.left, "baked left") + t:eq(a.meta.top, b.meta.top, "baked top") + local enc = F.save(baked, nil, { format = "bmfont", variant = "binary" }) + local back = F.load(enc) + t:check(back and #back.meta.bmfont.chars == 13, "baked font round trip") + -- an outline font saved as fnt is baked on the way + local fnt = F.convert(Fx.ttf, "fnt", { px = 16 }) + t:check(fnt and string.sub(buffer.tostring(fnt), 1, 9) == "info face", "F.convert ttf -> fnt (text)") +end + +-- 6. errors and validation +do + local _, e1 = Bmfont.decode(Bytes.reader(buffer.fromstring("BMF\2"))) + t:check(e1 and e1.code == Err.UNSUPPORTED, "binary version 2: " .. tostring(e1)) + local _, e2 = Bmfont.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.binary, 1, 40)))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated binary: " .. tostring(e2)) + local _, e3 = Bmfont.decode(Bytes.reader(buffer.fromstring("hello"))) + t:check(e3 and e3.code == Err.CORRUPT, "not a descriptor") + local f = Bmfont.decode(Bytes.reader(buffer.fromstring(Fx.text))) + f.meta.bmfont.chars[3].x = 1.5 + local _, e4 = Bmfont.encode(f) + t:check(e4 and e4.code == Err.ARG, "fractional field: " .. tostring(e4)) + local _, e5 = Bmfont.encode({ kind = "image" }) + t:check(e5 and e5.code == Err.ARG, "not a font") +end + +t:fuzz("decode", function(b: buffer) + local f = Bmfont.decode(Bytes.reader(b)) + if f then + Bmfont.encode(f, { variant = "binary" }) + end + return f +end, { Fx.binary, string.sub(Fx.text, 1, 3000), string.sub(Fx.xml, 1, 3000) }, { mutations = 40 }) + +t:done() diff --git a/tests/font/ttf.luau b/tests/font/ttf.luau new file mode 100644 index 0000000..5d78823 --- /dev/null +++ b/tests/font/ttf.luau @@ -0,0 +1,237 @@ +-- font/ttf tests (and codecs/TrueType, codecs/Cff): for the imgui-luau TrueType fonts, Source Sans 3 (CFF), a +-- 'kern'-table font and a collection: metrics, names, cmap samples, advances / side bearings, outline control boxes and +-- areas against fontTools; kerning against HarfBuzz (GPOS) and FreeType ('kern'); rasterize() against FreeType's +-- unhinted renders (PSNR); the api; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Ttf = require("@formats/font/ttf") +local Raster = require("@formats/codecs/Raster") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("ttf") + +t:eq(Ttf.name, "ttf", "name") +t:check(table.find(Ttf.extensions, "otf") and table.find(Ttf.extensions, "ttc"), "extensions") + +-- 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.w), math.max(ay0 + img.height, by0 + r.h) + 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.w and jy < r.h then + b = string.byte(r.pixels, jy * r.w + 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 fonts: { [string]: any } = {} +local worstPsnr, sumPsnr, nPsnr = 99, 0, 0 +for _, c in Fx.fonts do + local font, err = Ttf.decode(Bytes.reader(buffer.fromstring(c.data)), { index = c.index }) + t:check(font, c.name .. ": decode: " .. tostring(err)) + fonts[c.name] = font + t:eq(font.kind, "font", c.name .. ": kind") + t:eq(font.unitsPerEm, c.upem, c.name .. ": unitsPerEm") + t:eq(font.ascent, c.ascent, c.name .. ": ascent") + t:eq(font.descent, c.descent, c.name .. ": descent") + t:eq(font.lineGap, c.lineGap, c.name .. ": lineGap") + t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": numGlyphs") + t:eq(font.info.family, c.family, c.name .. ": family") + t:eq(font.info.style, c.style, c.name .. ": style") + t:eq(font.info.fullName, c.fullName, c.name .. ": fullName") + t:eq(font.meta.outlines, if c.cff then "cff" else "truetype", c.name .. ": outlines") + if c.weight > 0 then + t:eq(font.meta.os2.weightClass, c.weight, c.name .. ": weight") + end + for _, m in c.cmap do + t:eq(font:glyphIndex(m[1]), m[2], string.format("%s: cmap U+%04X", c.name, m[1])) + end + local maxAreaErr = 0 + for _, g in c.glyphs do + local gid = g.gid + t:eq(font:advance(gid), g.adv, c.name .. ": advance " .. gid) + if not c.cff then + t:eq(font:leftSideBearing(gid), g.lsb, c.name .. ": lsb " .. gid) + end + local cmds = font:outline(gid) + t:check(cmds, c.name .. ": outline " .. gid .. ": " .. tostring(font.meta.lastError)) + local x0, y0, x1, y1 = font:bounds(gid) + if g.box then + t:check(x0 ~= nil, c.name .. ": glyph " .. gid .. " has bounds") + local b = g.box + local ok = math.abs(x0 - b[1]) < 1e-6 and math.abs(y0 - b[2]) < 1e-6 and math.abs(x1 - b[3]) < 1e-6 and math.abs(y1 - b[4]) < 1e-6 + t:check(ok, string.format("%s: glyph %d control box %g %g %g %g, want %g %g %g %g", c.name, gid, x0 or 0, y0, x1, y1, b[1], b[2], b[3], b[4])) + local a = area(cmds) + -- fontTools' AreaPen: positive for counter-clockwise contours, as the shoelace here + local d = math.abs(a - g.area) / math.max(1, math.abs(g.area)) + maxAreaErr = math.max(maxAreaErr, d) + t:check(d < 0.002 or math.abs(a - g.area) < 2, string.format("%s: glyph %d area %.1f, want %.1f", c.name, gid, a, g.area)) + else + t:check(x0 == nil, c.name .. ": empty glyph " .. gid) + end + end + for _, k in c.kern do + t:eq(font:kern(k[1], k[2]), k[3], string.format("%s: kern %d %d", c.name, k[1], k[2])) + end + local worst = 99 + for _, r in c.renders do + local img = font:rasterize(r.gid, r.px) + t:check(img and img.format == "alpha8", c.name .. ": rasterize " .. r.gid) + local p, ink = psnr(img, r) + worst = math.min(worst, p) + sumPsnr += p + nPsnr += 1 + t:check(p > 28 or ink == 0, string.format("%s: glyph %d at %d px: PSNR %.1f dB vs FreeType", c.name, r.gid, r.px, p)) + t:check(math.abs(img.meta.advance - font:advance(r.gid) * r.px / font.unitsPerEm) < 1e-9, "advance in pixels") + end + worstPsnr = math.min(worstPsnr, worst) + t:note("%-20s %4d glyphs, %3d cmap, %3d kern pairs, area err %.5f, worst PSNR %.1f dB", c.name, #c.glyphs, #c.cmap, #c.kern, maxAreaErr, worst) +end +t:note("rasterize vs FreeType: mean PSNR %.1f dB, worst %.1f dB over %d renders", sumPsnr / nPsnr, worstPsnr, nPsnr) + +-- kerning is non-trivial in at least the GPOS and 'kern' fonts +do + local nz = 0 + for _, c in Fx.fonts do + for _, k in c.kern do + if k[3] ~= 0 then + nz += 1 + end + end + end + t:check(nz > 20, "fixtures have non-zero kerning pairs: " .. nz) +end + +-- collections +if Fx.ttc then + local b = buffer.fromstring(Fx.ttc.data) + t:eq(Ttf.count(Bytes.reader(b)), Fx.ttc.count, "collection count") + local f0 = Ttf.decode(Bytes.reader(b)) + t:check(f0 and f0.meta.collection and f0.meta.collection.count == 2, "collection font 0") + local _, e = Ttf.decode(Bytes.reader(b), { index = 5 }) + t:check(e and e.code == Err.ARG, "collection index out of range") + local f1 = F.load(b, { index = 1 }) + t:check(f1 and f1.info.family == fonts["collection-1"].info.family, "F.load with opts.index") +end + +-- the api: detection by content, the font facade +do + local c = Fx.fonts[1] + t:eq(F.detect(c.data), "ttf", "F.detect") + local f = F.font.load(c.data) + t:check(f and f.kind == "font" and f.meta.source.format == "ttf", "F.font.load") + local g = f:glyphIndex(65) + t:check(g > 0 and f:advance(g) > 0, "glyph A") + t:eq(f:glyphIndex(-1), 0, "negative code point") + t:eq(f:glyphIndex(0.5), 0, "fractional code point") + t:check(f:outline(-1) == nil and f:outline(1e9) == nil and f:rasterize(g, -3) == nil, "bad glyph / size") + local sp = f:rasterize(f:glyphIndex(32), 20) + t:check(sp and sp.width == 0, "space rasterizes to an empty image") + local _, e = F.save(f, nil, { format = "ttf" }) + t:check(e and e.code == Err.UNSUPPORTED, "ttf is read-only") +end + +-- errors +do + local _, e1 = Ttf.decode(Bytes.reader(buffer.fromstring("OTTO"))) + t:check(e1 and e1.code == Err.TRUNCATED, "short file: " .. tostring(e1)) + local _, e2 = Ttf.decode(Bytes.reader(buffer.fromstring("\0\1\0\0\0\0\0\0\0\0\0\0"))) + t:check(e2 and e2.code == Err.CORRUPT, "no tables: " .. tostring(e2)) + t:eq(Ttf.sniff(Bytes.reader(buffer.fromstring("wOFF"))), 0, "sniff rejects woff") +end + +-- fuzz: whole-font mutations, then glyph access on whatever still parses +do + local samples = {} + for _, c in Fx.fonts do + if #c.data < 60000 then + table.insert(samples, c.data) + end + end + local rand = T.rng(99) + t:fuzz("decode + glyphs", function(b: buffer) + local f = Ttf.decode(Bytes.reader(b)) + if f then + for _ = 1, 12 do + local g = rand(f.numGlyphs + 2) + f:outline(g) + f:advance(g) + f:kern(g, rand(f.numGlyphs + 1)) + f:glyphIndex(rand(70000)) + f:rasterize(g, 9) + end + end + return f + end, samples, { mutations = 30, garbage = 200 }) + -- mutations inside the glyph data only (the header survives, so the outline parsers see the damage) + local hits = 0 + local cff = Fx.fonts[#Fx.fonts - 2] -- (any font: the loop below picks the CFF one) + for _, c in Fx.fonts do + if c.cff then + cff = c + end + end + local tries = 0 + for _, c in { Fx.fonts[1], cff } do + local base = buffer.fromstring(c.data) + local n = buffer.len(base) + for _ = 1, 40 do + local b = buffer.create(n) + buffer.copy(b, 0, base) + for _ = 1, 20 do + local p = n // 4 + rand(n - n // 4) + buffer.writeu8(b, p, rand(256)) + end + tries += 1 + local ok = pcall(function() + local f = Ttf.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 300) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + hits += 1 + end + end) + t:check(ok, c.name .. ": glyph-data mutation threw") + end + end + t:note("glyph-data mutations: %d fonts (%d parsed), every glyph outlined + rasterized, none threw", tries, hits) +end + +t:done() 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/bench.luau b/tools/bench.luau index 9f6aef7..e42b6c3 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1,5 +1,6 @@ -- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs. --- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus) and tools/fixtures/png.py (1024 x 768 images). +-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), zstd / brotli / +-- bzip2 / lzma (their *_bench corpora) and fonts (glyph outlines + rasterization: glyphs per second). local Deflate = require("@formats/codecs/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") @@ -56,3 +57,77 @@ do Png.encode(img) end) end + +-- ws-arch codecs: zstd, brotli, bzip2, xz / lzma +do + local Zstd = require("@formats/codecs/Zstd") + local ZB = require("@tests/gen/zstd_bench") + local z3, z19 = buffer.fromstring(ZB.data3), buffer.fromstring(ZB.data19) + local zo = assert(Zstd.decompress(z3)) + assert(buffer.len(zo) == ZB.size and Crc32.of(zo) == ZB.crc, "zstd bench corpus mismatch") + bench("zstd -3 (+ xxh64)", 3, ZB.size, function() + Zstd.decompress(z3) + end) + bench("zstd -3 (no checksum)", 3, ZB.size, function() + Zstd.decompress(z3, nil, nil, { verify = false }) + end) + bench("zstd -19 (no checksum)", 3, ZB.size, function() + Zstd.decompress(z19, nil, nil, { verify = false }) + end) +end +do + local Brotli = require("@formats/codecs/Brotli") + local BB = require("@tests/gen/brotli_bench") + local bz = buffer.fromstring(BB.data) + local bout = assert(Brotli.decompress(bz)) + assert(buffer.len(bout) == BB.size and Crc32.of(bout) == BB.crc, "brotli bench corpus mismatch") + bench("brotli decompress (q9 w22)", 5, BB.size, function() + Brotli.decompress(bz) + end) +end +do + local Bzip2 = require("@formats/codecs/Bzip2") + local BZ = require("@tests/gen/bzip2_bench") + local bz = buffer.fromstring(BZ.data) + bench("bzip2 decompress -9", 3, BZ.size, function() + Bzip2.decompress(bz) + end) +end +do + local Lzma = require("@formats/codecs/Lzma") + local LB = require("@tests/gen/lzma_bench") + local lx, la = buffer.fromstring(LB.xz), buffer.fromstring(LB.alone) + local lo = assert(Lzma.xz(lx)) + assert(buffer.len(lo) == LB.size and Crc32.of(lo) == LB.crc, "lzma bench corpus mismatch") + bench("xz -6 (lzma2 + crc64)", 3, LB.size, function() + Lzma.xz(lx) + end) + bench("lzma alone -6", 3, LB.size, function() + Lzma.alone(la) + end) +end + +-- fonts: outlines and rasterization (MB/s here = thousands of glyphs per second) +do + local Ttf = require("@formats/font/ttf") + local FX = require("@tests/gen/fonts") + for _, c in FX.fonts do + if c.name == "Roboto-Medium" or c.name == "SourceSans3-Regular" then + local f = assert(Ttf.decode(Bytes.reader(buffer.fromstring(c.data)))) + local gl = {} + for cp = 33, 126 do + table.insert(gl, f:glyphIndex(cp)) + end + bench(c.name .. " outlines (kglyph/s)", 3, #gl * 1000, function() + for _, g in gl do + f:outline(g) + end + end) + bench(c.name .. " rasterize 32 px (kglyph/s)", 3, #gl * 1000, function() + for _, g in gl do + f:rasterize(g, 32) + end + end) + end + end +end diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..6b52612 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png zstd brotli bzip2 lzma fonts > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua diff --git a/tools/brotli_static.py b/tools/brotli_static.py new file mode 100644 index 0000000..f0cecb3 --- /dev/null +++ b/tools/brotli_static.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# Brotli static data generator (python3 -I tools/brotli_static.py [brotli-source-dir]): writes +# src/Formats/codecs/Brotli/Static.luau from the official brotli C sources (MIT; licenses/brotli-LICENSE.txt): +# the 122784-byte RFC 7932 static dictionary (c/common/dictionary_inc.h, stored deflated + base64), the context +# lookup table (c/common/context.c) and the 121 word transforms (c/common/transform.c). +# Without an argument the source comes from `nix build nixpkgs#brotli.src`. +import base64, os, re, subprocess, sys, zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +OUT = os.path.join(ROOT, "src", "Formats", "codecs", "Brotli", "Static.luau") + + +def c_array(text, name): + m = re.search(re.escape(name) + r"[^=]*=\s*\{(.*?)\};", text, re.S) + body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S) + body = body.replace("BROTLI_TRANSFORM_IDENTITY", "0").replace("BROTLI_TRANSFORM_UPPERCASE_FIRST", "10") + body = body.replace("BROTLI_TRANSFORM_UPPERCASE_ALL", "11") + body = re.sub(r"BROTLI_TRANSFORM_OMIT_LAST_(\d)", lambda k: k.group(1), body) + body = re.sub(r"BROTLI_TRANSFORM_OMIT_FIRST_(\d)", lambda k: str(11 + int(k.group(1))), body) + return [int(x, 0) for x in re.findall(r"0x[0-9a-fA-F]+|\d+", body)] + + +def c_string(text, name): + m = re.search(re.escape(name) + r"[^=]*=\s*(.*?);", text, re.S) + parts = re.findall(r'"((?:[^"\\]|\\.)*)"', re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S)) + s = "".join(parts) + return s.encode("latin-1").decode("unicode_escape").encode("latin-1") + b"\0" + + +def b64_chunks(data, width=96): + s = base64.b64encode(data).decode() + return [s[i:i + width] for i in range(0, len(s), width)] + + +def main(): + src = sys.argv[1] if len(sys.argv) > 1 else subprocess.run( + ["nix", "build", "nixpkgs#brotli.src", "--no-link", "--print-out-paths"], capture_output=True, check=True, + text=True).stdout.strip() + common = os.path.join(src, "c", "common") + dict_text = open(os.path.join(common, "dictionary_inc.h")).read() + dictionary = bytes(c_array(dict_text, "kBrotliDictionaryData")) + assert len(dictionary) == 122784 + ctx = bytes(c_array(open(os.path.join(common, "context.c")).read(), "_kBrotliContextLookupTable")) + assert len(ctx) == 2048 + tr_text = open(os.path.join(common, "transform.c")).read() + ps = c_string(tr_text, "kPrefixSuffix") + assert len(ps) == 217, len(ps) + psmap = c_array(tr_text, "kPrefixSuffixMap") + trans = c_array(tr_text, "kTransformsData") + assert len(psmap) == 50 and len(trans) == 363 + z = zlib.compress(dictionary, 9) + lines = [ + "--!strict", + "-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see", + "-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),", + "-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).", + "return {", + "\tdictionarySize = %d," % len(dictionary), + "\tdictionaryCrc = %d," % zlib.crc32(dictionary), + "\tdictionary = {", + ] + lines += ['\t\t"%s",' % c for c in b64_chunks(z)] + lines += ["\t},", "\tcontext = {"] + lines += ['\t\t"%s",' % c for c in b64_chunks(ctx)] + lines += ["\t},"] + lines += ['\tprefixSuffix = "%s",' % base64.b64encode(ps).decode()] + lines += ["\tprefixSuffixMap = { %s }," % ", ".join(map(str, psmap))] + lines += ["\ttransforms = {"] + for i in range(0, len(trans), 30): + lines.append("\t\t%s," % ", ".join(map(str, trans[i:i + 30]))) + lines += ["\t},", "}", ""] + with open(OUT, "w") as f: + f.write("\n".join(lines)) + print("brotli_static: wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), os.path.getsize(OUT))) + + +if __name__ == "__main__": + main() diff --git a/tools/fixtures/7z.py b/tools/fixtures/7z.py new file mode 100644 index 0000000..aa4d0c4 --- /dev/null +++ b/tools/fixtures/7z.py @@ -0,0 +1,103 @@ +# 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested +# directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains: +# LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus +# BZip2 archives (codecs/Bzip2), archives whose methods are not supported (PPMd, BCJ2, AES) and an empty archive. +# tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } } +import os, random, subprocess, sys, tempfile + +TOOL = "_7zz" + + +def tree(rng): + with open(os.path.realpath(sys.executable), "rb") as f: + code = f.read(60000) + base = os.path.dirname(os.__file__) + text = b"" + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + text += f.read() + if len(text) > 50000: + break + return [ + ("readme.txt", text[:50000]), + ("bin/code.bin", code), + ("bin/runs.dat", b"ab" * 5000 + b"\0" * 9000 + bytes(range(256)) * 8), + ("bin/random.dat", rng.randbytes(3000)), + ("empty.txt", b""), + ("emptydir/", None), + ("a/b/c/deep.txt", b"deep\n" * 10), + ("héllo wörld ☃.txt", "unicode ☃\n".encode()), + ("\U0001d11e clef.txt", b"g clef\n"), + ] + + +def generate(ctx): + rng = random.Random(77) + files = tree(rng) + mtime = 1600000000 + out_files = [] + cases = [] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "src") + for name, data in files: + p = os.path.join(src, name) + if data is None: + os.makedirs(p, exist_ok=True) + os.utime(p, (mtime, mtime)) + out_files.append({"name": name.rstrip("/"), "dir": True, "mtime": mtime}) + else: + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + os.utime(p, (mtime + 60, mtime + 60)) + out_files.append({"name": name, "dir": False, "data": data, "mtime": mtime + 60}) + for sub in ("bin", "a", "a/b", "a/b/c"): + os.utime(os.path.join(src, sub), (mtime, mtime)) + out_files.append({"name": sub, "dir": True, "mtime": mtime}) + + def make(name, args, unsupported=None): + arc = os.path.join(d, name + ".7z") + if os.path.exists(arc): + os.remove(arc) + subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc] + args + ["."], + cwd=src, capture_output=True, check=True) + with open(arc, "rb") as f: + c = {"name": name, "data": f.read()} + if unsupported: + c["unsupported"] = unsupported + cases.append(c) + + make("lzma-nonsolid", ["-m0=LZMA", "-ms=off", "-mhc=off"]) + make("lzma-solid", ["-m0=LZMA:d=1m", "-ms=on"]) + make("lzma2-solid", ["-m0=LZMA2", "-ms=on"]) + make("lzma2-mt-blocks", ["-m0=LZMA2:d=64k:c=20k", "-ms=on", "-mmt=4"]) + make("lzma2-hc-off", ["-m0=LZMA2", "-mhc=off"]) + make("copy", ["-m0=Copy", "-mhc=off"]) + make("copy-hc", ["-m0=Copy"]) + make("deflate", ["-m0=Deflate", "-ms=on"]) + make("bcj-lzma", ["-m0=BCJ", "-m1=LZMA", "-ms=on"]) + make("bcj-lzma2", ["-m0=BCJ", "-m1=LZMA2", "-ms=off"]) + make("arm64-lzma2", ["-m0=ARM64", "-m1=LZMA2"]) + make("arm-lzma2", ["-m0=ARM", "-m1=LZMA2"]) + make("delta-lzma", ["-m0=Delta:4", "-m1=LZMA"]) + make("ppc-sparc", ["-m0=PPC", "-m1=SPARC", "-m2=LZMA2"]) + make("lzma-lc-lp", ["-m0=LZMA:lc=0:lp=2:pb=0", "-ms=e"]) + make("auto", ["-mx=9"]) + make("fast", ["-mx=1"]) + make("bzip2", ["-m0=BZip2", "-mhc=off"]) + make("bzip2-solid-bcj", ["-m0=BCJ", "-m1=BZip2", "-ms=on", "-mhc=on"]) + make("ppmd", ["-m0=PPMd", "-mhc=off"], unsupported="ppmd") + make("bcj2", ["-m0=BCJ2", "-m1=LZMA", "-m2=LZMA", "-m3=LZMA", "-mb0s0:1", "-mb0s1:2", "-mb0s2:3", "-mhc=off"], + unsupported="bcj2") + make("aes", ["-m0=LZMA2", "-mhc=off", "-pSecret"], unsupported="aes") + # an empty archive + arc = os.path.join(d, "empty.7z") + empty = os.path.join(d, "emptysrc") + os.makedirs(empty) + subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc, "-x!*", "."], + cwd=empty, capture_output=True) + if os.path.exists(arc): + with open(arc, "rb") as f: + cases.append({"name": "empty", "data": f.read(), "empty": True}) + ctx.emit("7z", {"files": out_files, "cases": cases}) diff --git a/tools/fixtures/_font_reference.py b/tools/fixtures/_font_reference.py new file mode 100644 index 0000000..17ba026 --- /dev/null +++ b/tools/fixtures/_font_reference.py @@ -0,0 +1,181 @@ +# Font reference data (run by tools/fixtures/fonts.py inside a nix python with fonttools, freetype-py, uharfbuzz and +# brotli). Reads a JSON list of {name, path | b64} on stdin; writes JSON on stdout: per font the bytes, the metrics, +# names, cmap samples (fontTools), advances / side bearings / control boxes / areas of sample glyphs (fontTools pens), +# kerning of sample pairs (HarfBuzz GPOS 'kern', or FreeType for 'kern' tables), FreeType renders (no hinting) of +# sample glyphs at a few sizes, and the WOFF / WOFF2 versions (fontTools). +import base64, io, json, sys + +import freetype +import uharfbuzz as hb +from fontTools.pens.areaPen import AreaPen +from fontTools.pens.boundsPen import ControlBoundsPen +from fontTools.ttLib import TTFont, newTable +from fontTools.ttLib.tables._k_e_r_n import KernTable_format_0 + +SAMPLE_TEXT = "AVTWYLPFoaey.,'\"-0147" +SIZES = [11, 24, 47] + + +def b64(b): + return base64.b64encode(b).decode() + + +def load(spec): + if "path" in spec: + return open(spec["path"], "rb").read() + return base64.b64decode(spec["b64"]) + + +def with_kern_table(data): + """a copy with a 'kern' format 0 table of a few pairs (none of the sample fonts has one)""" + f = TTFont(io.BytesIO(data)) + cmap = f.getBestCmap() + order = f.getGlyphOrder() + pairs = {} + letters = "AVTWYLoaey" + for i, a in enumerate(letters): + for j, b in enumerate(letters): + if ord(a) in cmap and ord(b) in cmap and (i * 7 + j * 3) % 4 == 0: + pairs[(cmap[ord(a)], cmap[ord(b)])] = -((i * 13 + j * 5) % 90) - 10 + k = newTable("kern") + k.version = 0 + st = KernTable_format_0() + st.version, st.coverage, st.format = 0, 1, 0 + st.kernTable = pairs + k.kernTables = [st] + f["kern"] = k + if "GPOS" in f: + del f["GPOS"] + out = io.BytesIO() + f.save(out) + return out.getvalue() + + +def collection(datas): + from fontTools.ttLib.ttCollection import TTCollection + c = TTCollection() + c.fonts = [TTFont(io.BytesIO(d)) for d in datas] + out = io.BytesIO() + c.save(out) + return out.getvalue() + + +def reference(name, data, index=0): + f = TTFont(io.BytesIO(data), fontNumber=index) + gs = f.getGlyphSet() + order = f.getGlyphOrder() + head, hhea, maxp = f["head"], f["hhea"], f["maxp"] + names = f["name"] + def nm(i): + r = names.getName(i, 3, 1, 0x409) or names.getName(i, 3, 1) or names.getName(i, 1, 0, 0) or names.getName(i, 0, 3) + return r.toUnicode() if r else "" + cmap = f.getBestCmap() or {} + cps = sorted(cmap) + sample_cps = cps[:: max(1, len(cps) // 150)] + [0x10FFFF, 0xFFFF, 0x7F, 0x9999] + cm = [[cp, f.getGlyphID(cmap[cp]) if cp in cmap else 0] for cp in sample_cps] + # glyphs: every glyph for small fonts, else a sample (plus the sample text's) + gids = list(range(len(order))) if len(order) <= 400 else list(range(0, len(order), len(order) // 300)) + for ch in SAMPLE_TEXT: + if ord(ch) in cmap: + gids.append(f.getGlyphID(cmap[ord(ch)])) + gids = sorted(set(gids)) + hmtx = f["hmtx"] + glyphs = [] + for g in gids: + gn = order[g] + adv, lsb = hmtx[gn] + bp = ControlBoundsPen(gs) + gs[gn].draw(bp) + ap = AreaPen(gs) + gs[gn].draw(ap) + e = {"gid": g, "adv": adv, "lsb": lsb, "area": float(ap.value)} + if bp.bounds: + e["box"] = [float(v) for v in bp.bounds] + glyphs.append(e) + # kerning + kern = [] + letters = [c for c in SAMPLE_TEXT if ord(c) in cmap] + if "kern" in f and "GPOS" not in f: + face = freetype.Face(io.BytesIO(data), index) + for a in letters: + for b in letters: + ga, gb = f.getGlyphID(cmap[ord(a)]), f.getGlyphID(cmap[ord(b)]) + v = face.get_kerning(a, b, freetype.FT_KERNING_UNSCALED) # freetype-py maps characters to glyphs + kern.append([ga, gb, v.x]) + elif "GPOS" in f: + blob = hb.Blob(data) + hface = hb.Face(blob, index) + hfont = hb.Font(hface) + feats = {"kern": True, "liga": False, "clig": False, "calt": False, "mark": False, "mkmk": False, "ccmp": False, "locl": False, "rlig": False, "dist": False, "curs": False} + for a in letters: + for b in letters: + buf = hb.Buffer() + buf.add_str(a + b) + buf.guess_segment_properties() + hb.shape(hfont, buf, feats) + ga, gb = buf.glyph_infos[0].codepoint, buf.glyph_infos[1].codepoint + adv = buf.glyph_positions[0].x_advance - hmtx[order[ga]][0] + kern.append([ga, gb, adv]) + # FreeType renders + face = freetype.Face(io.BytesIO(data), index) + renders = [] + rg = [f.getGlyphID(cmap[ord(c)]) for c in "AgQ@&e%" if ord(c) in cmap] + for px in SIZES: + face.set_pixel_sizes(0, px) + for g in rg: + face.load_glyph(g, freetype.FT_LOAD_NO_HINTING | freetype.FT_LOAD_NO_BITMAP) + face.glyph.render(freetype.FT_RENDER_MODE_NORMAL) + bm = face.glyph.bitmap + rows = [] + for y in range(bm.rows): + rows.append(bytes(bm.buffer[y * bm.pitch: y * bm.pitch + bm.width])) + renders.append({"gid": g, "px": px, "w": bm.width, "h": bm.rows, "left": face.glyph.bitmap_left, + "top": face.glyph.bitmap_top, "pixels": b64(b"".join(rows))}) + os2 = f["OS/2"] if "OS/2" in f else None + return { + "name": name, "data": b64(data), "index": index, "upem": head.unitsPerEm, "ascent": hhea.ascent, + "descent": hhea.descent, "lineGap": hhea.lineGap, "numGlyphs": maxp.numGlyphs, "family": nm(16) or nm(1), + "style": nm(17) or nm(2), "fullName": nm(4), "weight": os2.usWeightClass if os2 else 0, + "cff": "CFF " in f, "cmap": cm, "glyphs": glyphs, "kern": kern, "renders": renders, + } + + +def flavors(data): + out = {} + for fl in ("woff", "woff2"): + f = TTFont(io.BytesIO(data)) + f.flavor = fl + 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 + + +def main(): + specs = json.load(sys.stdin) + fonts = {} + for s in specs: + fonts[s["name"]] = load(s) + res = {"fonts": [], "woff": []} + for name, data in fonts.items(): + res["fonts"].append(reference(name, data)) + kd = with_kern_table(fonts["ProggyClean"] if "ProggyClean" in fonts else next(iter(fonts.values()))) + res["fonts"].append(reference("kern-table", kd)) + names = [n for n in ("Karla-Regular", "Cousine-Regular") if n in fonts] + if len(names) == 2: + ttc = collection([fonts[n] for n in names]) + r = reference("collection-1", ttc, 1) + res["fonts"].append(r) + res["ttc"] = {"data": b64(ttc), "count": 2, "second": names[1]} + # 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"], "woff2h": fl["woff2h"]}) + json.dump(res, sys.stdout) + + +main() diff --git a/tools/fixtures/bmfont.py b/tools/fixtures/bmfont.py new file mode 100644 index 0000000..a8b1420 --- /dev/null +++ b/tools/fixtures/bmfont.py @@ -0,0 +1,105 @@ +# BMFont fixtures (tools/fixtures.py): a bitmap font rendered from Karla-Regular (imgui-luau fonts, or DejaVu Sans +# from nixpkgs when missing) with FreeType + Pillow, written by an independent Python writer of the three AngelCode +# encodings (text, XML, binary v3) from the BMFont documentation, plus its page PNG. +# tests/gen/bmfont.luau { text, xml, binary, page (png bytes), desc = { info, common, pages, chars, kernings }, +# crops = { { id, crc } } (CRC-32 of each glyph's alpha crop) } +import base64, json, os, subprocess + +FONT = os.path.join(os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")), "Karla-Regular.ttf") + +CODE = r''' +import base64, io, json, struct, sys, zlib +import freetype +from PIL import Image +data = base64.b64decode(sys.stdin.read()) +face = freetype.Face(io.BytesIO(data)) +face.set_pixel_sizes(0, 24) +chars = [c for c in range(32, 127)] + [0xE9, 0x2014] +page = Image.new("RGBA", (256, 256), (255, 255, 255, 0)) +x, y, rowh = 1, 1, 0 +out = [] +crops = [] +for cp in chars: + face.load_char(chr(cp), freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING) + g = face.glyph + bm = g.bitmap + w, h = bm.width, bm.rows + if x + w + 1 > 256: + x, y, rowh = 1, y + rowh + 1, 0 + alpha = bytes(bm.buffer[r * bm.pitch + c] for r in range(h) for c in range(w)) + for r in range(h): + for c in range(w): + page.putpixel((x + c, y + r), (255, 255, 255, alpha[r * w + c])) + out.append({"id": cp, "x": x, "y": y, "width": w, "height": h, "xoffset": g.bitmap_left, + "yoffset": 19 - g.bitmap_top, "xadvance": g.advance.x // 64, "page": 0, "chnl": 15}) + crops.append({"id": cp, "crc": zlib.crc32(alpha)}) + x += w + 1 + rowh = max(rowh, h) +kern = [] +for a in "AVTWYLo": + for b in "AVTWYoe.": + k = face.get_kerning(a, b).x // 64 + kern.append([ord(a), ord(b), -((ord(a) * 7 + ord(b)) % 5) - 1]) +info = {"face": "Karla \"Test\" & Co", "size": 24, "bold": 0, "italic": 1, "charset": "", "unicode": 1, "stretchH": 100, + "smooth": 1, "aa": 1, "padding": [1, 2, 3, 4], "spacing": [1, 1], "outline": 0} +common = {"lineHeight": 28, "base": 19, "scaleW": 256, "scaleH": 256, "pages": 1, "packed": 0, "alphaChnl": 0, + "redChnl": 4, "greenChnl": 4, "blueChnl": 4} +pages = ["karla_0.png"] +CHAR_KEYS = ["id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl"] +def tq(s): return '"' + s.replace('"', "") + '"' +lines = ["info face=%s size=24 bold=0 italic=1 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,2,3,4 spacing=1,1 outline=0" % tq(info["face"]), + "common lineHeight=28 base=19 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4", + 'page id=0 file="karla_0.png"', "chars count=%d" % len(out)] +for c in out: + lines.append("char " + " ".join("%s=%d" % (k, c[k]) for k in CHAR_KEYS)) +lines.append("kernings count=%d" % len(kern)) +for k in kern: + lines.append("kerning first=%d second=%d amount=%d" % tuple(k)) +text = "\r\n".join(lines) + "\r\n" +def xe(s): return s.replace("&", "&").replace("<", "<").replace('"', """) +xl = ['', "", + ' ' % xe(info["face"]), + ' ', + " ", ' ', " ", ' ' % len(out)] +for c in out: + xl.append(" ") +xl.append(" ") +xl.append(' ' % len(kern)) +for k in kern: + xl.append(' ' % tuple(k)) +xl += [" ", ""] +xml = "\n".join(xl) + "\n" +face_name = info["face"].encode() +b = bytearray(b"BMF\x03") +blk = struct.pack("' + s + "\n" + out.append(s) + size += len(s) + return "".join(out).encode()[:n] + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def generate(ctx): + rng = random.Random(7) + text = text_corpus(400000) + corpora = { + "empty": b"", + "one": b"a", + "english": english(rng, 120000), + "text": text[:150000], + "random": rng.randbytes(30000), + "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)), + "utf8": ("Grüße, Привет, 你好, こんにちは, ¡Hola! " * 600).encode(), + "far": (lambda r: r + rng.randbytes(70000) + r)(rng.randbytes(9000)), + } + jobs, names = [], [] + for cname, data in corpora.items(): + for q in range(12): + jobs.append((data, q, 22, "generic")) + names.append(("%s/q%d" % (cname, q), cname)) + for w in (10, 12, 16, 18, 24): + jobs.append((data, 9, w, "generic")) + names.append(("%s/q9-w%d" % (cname, w), cname)) + for mode in ("text", "font"): + for q in (5, 11): + jobs.append((data, q, 20, mode)) + names.append(("%s/%s-q%d" % (cname, mode, q), cname)) + outs = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps(jobs))) + cases = [{"name": n, "corpus": c, "data": d} for (n, c), d in zip(names, outs)] + # the large-window extension (brotli CLI), on the far-match corpus and the text + for cname in ("far", "text", "english"): + for q in (5, 11): + d = ctx.nix("brotli", ["brotli", "-c", "-q", str(q), "--large_window=26"], input=corpora[cname]) + cases.append({"name": "%s/large-q%d" % (cname, q), "corpus": cname, "data": d}) + ctx.emit("brotli", {"corpora": corpora, "cases": cases}) + bench = (text + english(rng, 1500000) + corpora["binary"] * 10 + text) * 2 + bench = bench[:4000000] + bout = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps([(bench, 9, 22, "generic")])))[0] + ctx.emit("brotli_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bout}) diff --git a/tools/fixtures/bzip2.py b/tools/fixtures/bzip2.py new file mode 100644 index 0000000..0464a8a --- /dev/null +++ b/tools/fixtures/bzip2.py @@ -0,0 +1,61 @@ +# Bzip2 fixtures (tools/fixtures.py): deterministic corpora compressed with Python's bz2 module (libbzip2) at block +# sizes 1..9, RLE1 edge cases (runs of 1..300 bytes, runs straddling block ends), every byte value, random data, +# concatenated streams with trailing garbage; plus a 4 MB bench corpus. +# tests/gen/bzip2.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } } +# tests/gen/bzip2_bench.luau { size, crc, data } +import bz2, os, zlib + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def generate(ctx): + rng = ctx.rng(7) + runs = bytearray() + for n in list(range(1, 20)) + [250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 300, 1000, 5000]: + runs += bytes([n % 251]) * n + b"x" + corpora = { + "empty": b"", + "one": b"a", + "two": b"ab", + "four": b"aaaa", + "five": b"aaaaa", + "text": text_corpus(300000), + "random": rng.randbytes(60000), + "runs": bytes(runs), + "zeros": b"\0" * 250000, + "allbytes": bytes(range(256)) * 50, + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(40000)), + # a run crossing the 100k block boundary at level 1 + "boundary": b"q" * 99990 + b"r" * 30 + rng.randbytes(1000), + # more than 18 Huffman group switches / many symbols in use + "skewed": bytes(rng.choice(range(256)) if rng.random() < 0.1 else 65 for _ in range(120000)), + } + cases = [] + for cname, data in corpora.items(): + for level in (1, 5, 9) if len(data) > 1000 else (9,): + cases.append(("%s/l%d" % (cname, level), cname, bz2.compress(data, level))) + for level in range(1, 10): + cases.append(("text/all-l%d" % level, "text", bz2.compress(corpora["text"], level))) + corpora["multi"] = corpora["text"][:20000] + b"" + corpora["runs"] + multi = bz2.compress(corpora["text"][:20000], 9) + bz2.compress(b"", 1) + bz2.compress(corpora["runs"], 3) + cases.append(("multi/streams", "multi", multi)) + cases.append(("multi/trailing", "multi", multi + b"garbage after the last stream")) + ctx.emit("bzip2", { + "corpora": corpora, + "cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases], + }) + bench = bytearray() + while len(bench) < 4_000_000: + bench += corpora["text"] + corpora["binary"] + rng.randbytes(20000) + bench = bytes(bench[:4_000_000]) + ctx.emit("bzip2_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bz2.compress(bench, 9)}) diff --git a/tools/fixtures/fonts.py b/tools/fixtures/fonts.py new file mode 100644 index 0000000..bab68e6 --- /dev/null +++ b/tools/fixtures/fonts.py @@ -0,0 +1,37 @@ +# Font fixtures (tools/fixtures.py): the imgui-luau fonts (TrueType: Cousine, DroidSans, Karla, Proggy*, Roboto, read +# from ~/dev/luau/imgui/imgui-luau/fonts or $IMGUI_FONTS; skipped if missing) and Source Sans 3 (CFF OpenType, nixpkgs +# source-sans), plus a copy of ProggyClean with a 'kern' table and a two-font collection, both made with fontTools. +# Reference values come from tools/fixtures/_font_reference.py: fontTools (metrics, names, cmap, hmtx, control boxes, +# areas, WOFF / WOFF2), HarfBuzz (GPOS kerning), FreeType (kern tables, unhinted renders). +# tests/gen/fonts.luau { fonts = { { name, data, upem, ..., cmap, glyphs, kern, renders } }, woff = { ... }, ttc } +import base64, glob, json, os, subprocess + +INPUTS = ["tools/fixtures/_font_reference.py"] + +FONTS = os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")) +PICK = ["Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyClean", "Roboto-Medium"] + + +def generate(ctx): + specs = [] + for name in PICK: + p = os.path.join(FONTS, name + ".ttf") + if os.path.exists(p): + specs.append({"name": name, "b64": base64.b64encode(open(p, "rb").read()).decode()}) + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#source-sans"], capture_output=True, + check=True, text=True).stdout.strip().split("\n")[-1] + otf = os.path.join(out, "share", "fonts", "opentype", "SourceSans3-Regular.otf") + specs.append({"name": "SourceSans3-Regular", "b64": base64.b64encode(open(otf, "rb").read()).decode()}) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_font_reference.py")).read() + raw = ctx.python(["fonttools", "freetype-py", "uharfbuzz", "brotli"], code, input=json.dumps(specs).encode()) + res = json.loads(raw) + d = base64.b64decode + for f in res["fonts"]: + f["data"] = d(f["data"]) + for r in f["renders"]: + r["pixels"] = d(r["pixels"]) + for w in res["woff"]: + 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) diff --git a/tools/fixtures/lzma.py b/tools/fixtures/lzma.py new file mode 100644 index 0000000..09be77f --- /dev/null +++ b/tools/fixtures/lzma.py @@ -0,0 +1,105 @@ +# LZMA / LZMA2 / xz fixtures (tools/fixtures.py): deterministic corpora compressed by liblzma (Python's lzma module and +# the xz CLI): every preset and -e, lc / lp / pb variants, raw LZMA1 / LZMA2, .lzma files with and without the size +# and end marker, xz with every check type, BCJ (x86, PowerPC, ARM, ARM-Thumb, SPARC, ARM64) and delta filters, +# multi-block (--block-size), multi-stream and stream padding. +# tests/gen/lzma.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data, props?, dict?, +# size? } } } kind: "raw" (LZMA1), "raw2" (LZMA2), "alone", "xz" +# tests/gen/lzma_bench.luau { size, crc, xz, alone } (a ~4 MB corpus at -6) +import lzma, os, random, subprocess, sys, zlib + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def binary_corpus(limit): + # machine code: a slice of the Python interpreter (x86-64 here; exercises the x86 BCJ filter) + with open(os.path.realpath(sys.executable), "rb") as f: + data = f.read() + if len(data) < limit: + lib = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "..", "lib") + for name in sorted(os.listdir(lib)): + p = os.path.join(lib, name) + if name.startswith("libpython") and os.path.isfile(p): + with open(p, "rb") as f: + data += f.read(limit) + break + return data[:limit] + + +def xz_cli(args, data): + return subprocess.run(["xz"] + args + ["-c"], input=data, capture_output=True, check=True).stdout + + +def generate(ctx): + rng = random.Random(7) + corpora = { + "empty": b"", + "one": b"a", + "text": text_corpus(150000), + "binary": binary_corpus(120000), + "random": rng.randbytes(20000), + "runs": b"abc" * 3000 + b"\0" * 30000 + bytes(range(256)) * 30 + b"z" * 300, + "words": b" ".join(rng.choice([b"lorem", b"ipsum", b"dolor", b"sit", b"amet", b"\xff\xfe", b"0123"]) for _ in range(20000)), + } + cases = [] + + def add(name, kind, corpus, data, **extra): + c = {"name": name, "kind": kind, "corpus": corpus, "data": data} + c.update(extra) + cases.append(c) + + for cname, data in corpora.items(): + small = cname in ("empty", "one", "random") + presets = [0, 6] if small else [0, 1, 3, 6, 9, 9 | lzma.PRESET_EXTREME] + for p in presets: + add("%s/xz-%d%s" % (cname, p & 15, "e" if p & lzma.PRESET_EXTREME else ""), "xz", cname, + lzma.compress(data, lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, preset=p)) + for chk, cn in ((lzma.CHECK_NONE, "none"), (lzma.CHECK_CRC32, "crc32"), (lzma.CHECK_SHA256, "sha256")): + add("%s/xz-check-%s" % (cname, cn), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, check=chk, preset=2)) + # .lzma (alone): with a size (Python writes an end marker and no size; the CLI writes the same); raw streams + add("%s/alone" % cname, "alone", cname, lzma.compress(data, lzma.FORMAT_ALONE, preset=6)) + for lc, lp, pb in ((3, 0, 2), (0, 2, 0), (4, 0, 4), (1, 3, 1), (0, 4, 3)): + f = [{"id": lzma.FILTER_LZMA1, "preset": 6, "lc": lc, "lp": lp, "pb": pb, "dict_size": 1 << 20}] + raw = lzma.compress(data, lzma.FORMAT_RAW, filters=f) + add("%s/raw-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw", cname, raw, props=bytes([(pb * 5 + lp) * 9 + lc]), size=len(data)) + for lc, lp, pb in ((3, 0, 2), (0, 4, 4), (2, 2, 1)): + f = [{"id": lzma.FILTER_LZMA2, "preset": 6, "lc": lc, "lp": lp, "pb": pb}] + add("%s/raw2-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw2", cname, lzma.compress(data, lzma.FORMAT_RAW, filters=f)) + if not small: + for fid, fname in ((lzma.FILTER_X86, "x86"), (lzma.FILTER_POWERPC, "ppc"), (lzma.FILTER_ARM, "arm"), + (lzma.FILTER_ARMTHUMB, "armthumb"), (lzma.FILTER_SPARC, "sparc")): + f = [{"id": fid}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-%s" % (cname, fname), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + f = [{"id": lzma.FILTER_X86, "start_offset": 0x1000}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-x86-start" % cname, "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + for dist in (1, 4, 256): + f = [{"id": lzma.FILTER_DELTA, "dist": dist}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-delta%d" % (cname, dist), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + add("%s/xz-cli-arm64" % cname, "xz", cname, xz_cli(["--arm64", "--lzma2=preset=3"], data)) + add("%s/xz-cli-blocks" % cname, "xz", cname, xz_cli(["-6", "--block-size=20000"], data)) + add("%s/xz-cli-x86-delta" % cname, "xz", cname, xz_cli(["--x86", "--delta=dist=2", "--lzma2=preset=1"], data)) + add("%s/alone-cli" % cname, "alone", cname, xz_cli(["--format=lzma", "-3"], data)) + # multi-stream + stream padding + corpora["multi"] = corpora["text"][:40000] + corpora["runs"] + b"" + corpora["one"] + multi = (lzma.compress(corpora["text"][:40000], lzma.FORMAT_XZ, preset=1) + b"\0" * 8 + + lzma.compress(corpora["runs"], lzma.FORMAT_XZ, check=lzma.CHECK_CRC32) + + lzma.compress(b"", lzma.FORMAT_XZ) + lzma.compress(b"a", lzma.FORMAT_XZ, check=lzma.CHECK_NONE) + b"\0" * 4) + add("multi/xz-streams", "xz", "multi", multi) + + ctx.emit("lzma", {"corpora": corpora, "cases": cases}) + + # real text and machine code, little long-range repetition + bench = text_corpus(2_000_000) + binary_corpus(1_000_000) + bench = bench[:3_000_000] + ctx.emit("lzma_bench", {"size": len(bench), "crc": zlib.crc32(bench), + "xz": lzma.compress(bench, lzma.FORMAT_XZ, preset=6), + "alone": lzma.compress(bench, lzma.FORMAT_ALONE, preset=6)}) diff --git a/tools/fixtures/tar.py b/tools/fixtures/tar.py new file mode 100644 index 0000000..4c7f03e --- /dev/null +++ b/tools/fixtures/tar.py @@ -0,0 +1,125 @@ +# tar + gzip fixtures (tools/fixtures.py): reference archives from Python's tarfile (ustar / GNU / pax formats, long +# names, non-ASCII names, links, directories, pax mtimes) and from the host / nix GNU tar (--format=ustar / gnu / +# posix / v7), gzip members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members), and +# compressed tars (.tar.gz, .tgz, .tar.zst, .tar.xz, .tar.bz2, .tar.br) for the api's unwrap. +# tests/gen/tar.luau { files = { { name, data, ... } }, writes = { { format, entries, data } }, tars = { { name, +# data, entries = { { name, size, type, link?, mtime, mode, crc } } } }, gzips = { ... }, +# wrapped = { { name, data, inner = "tar" } } } +import bz2, gzip, io, json, lzma, os, shutil, subprocess, tarfile, tempfile, zlib + + +def tool(name, pkg, argv, input=None, cwd=None): + exe = shutil.which(name) + cmd = ([exe] if exe else ["nix", "shell", "nixpkgs#" + pkg, "-c", name]) + argv + return subprocess.run(cmd, input=input, capture_output=True, check=True, cwd=cwd).stdout + + +def entries_of(data): + out = [] + with tarfile.open(fileobj=io.BytesIO(data)) as t: + for m in t.getmembers(): + e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0", + "size": m.size if m.isfile() else 0, "mtime": m.mtime, "mode": m.mode} + if m.issym() or m.islnk(): + e["link"] = m.linkname + if m.isfile(): + e["crc"] = zlib.crc32(t.extractfile(m).read()) + out.append(e) + return out + + +def generate(ctx): + rng = ctx.rng(5) + files = [ + ("hello.txt", b"hello, tar\n"), + ("empty", b""), + ("dir/sub/data.bin", rng.randbytes(3000)), + ("exact512", bytes(range(256)) * 2), + ("d" * 60 + "/" + "e" * 60 + "/long-name-over-100-bytes.txt", b"long " * 50), + ("x" * 150, b"no slash to split at"), + ("unicodé/naïve-ファイル.txt", "ünïcödé".encode()), + ] + # the writer test: the same entries through Python's tarfile in three formats (fixed metadata) + writes = [] + for fmt, pf in (("ustar", tarfile.USTAR_FORMAT), ("gnu", tarfile.GNU_FORMAT), ("pax", tarfile.PAX_FORMAT)): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w", format=pf) as t: + ents = [] + for name, data in files: + if fmt == "ustar" and (not name.isascii() or name.startswith("x" * 101)): + continue + ti = tarfile.TarInfo(name) + ti.size, ti.mtime, ti.mode, ti.uname, ti.gname = len(data), 1700000000, 0o644, "user", "group" + t.addfile(ti, io.BytesIO(data)) + ents.append({"name": name, "data": data}) + ti = tarfile.TarInfo("adir") + ti.type, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.DIRTYPE, 1700000000, 0o755, "user", "group" + t.addfile(ti) + ents.append({"name": "adir", "dir": True}) + ti = tarfile.TarInfo("link-to-hello") + ti.type, ti.linkname, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.SYMTYPE, "hello.txt", 1700000000, 0o777, "user", "group" + t.addfile(ti) + ents.append({"name": "link-to-hello", "type": "2", "link": "hello.txt", "mode": 0o777}) + writes.append({"format": fmt, "entries": ents, "data": buf.getvalue()}) + + tars = [] + for w in writes: + tars.append({"name": "python-" + w["format"], "data": w["data"], "entries": entries_of(w["data"])}) + # pax with a fractional mtime and a huge uid + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as t: + ti = tarfile.TarInfo("frac.txt") + ti.size, ti.mtime, ti.uid = 3, 1600000000.5, 3000000 + t.addfile(ti, io.BytesIO(b"abc")) + tars.append({"name": "python-pax-extras", "data": buf.getvalue(), "entries": entries_of(buf.getvalue())}) + # GNU tar on a real tree + tmp = tempfile.mkdtemp() + try: + root = os.path.join(tmp, "tree") + for name, data in files: + p = os.path.join(root, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + os.makedirs(os.path.join(root, "emptydir")) + os.symlink("hello.txt", os.path.join(root, "sym")) + os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard")) + for dirpath, dirs, fs in os.walk(root): + for n in dirs + fs: + os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False) + for fmt in ("ustar", "gnu", "posix", "v7"): + argv = ["--format=" + fmt, "--sort=name", "--owner=0", "--group=0", "--numeric-owner", "-cf", "-", "."] + if fmt in ("ustar", "v7"): + argv = ["--exclude=./" + "x" * 150, "--exclude=./d" + "d" * 59] + argv + if fmt == "v7": + argv = ["--exclude=./unicodé"] + argv + data = tool("tar", "gnutar", argv, cwd=root) + tars.append({"name": "gnutar-" + fmt, "data": data, "entries": entries_of(data)}) + finally: + shutil.rmtree(tmp) + + # gzip + text = ("The quick brown fox jumps over the lazy dog. " * 300).encode() + gzips = [] + b = io.BytesIO() + with gzip.GzipFile(filename="story.txt", mode="wb", fileobj=b, mtime=1234567890, compresslevel=9) as g: + g.write(text) + gzips.append({"name": "python-fname", "data": b.getvalue(), "entry": "story.txt", "mtime": 1234567890, "crc": zlib.crc32(text), "size": len(text)}) + gzips.append({"name": "python-noname", "data": gzip.compress(text, 1, mtime=0), "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)}) + cli = tool("gzip", "gzip", ["-9", "-n", "-c"], input=text) + gzips.append({"name": "cli-n", "data": cli, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)}) + two = gzip.compress(text[:1000], mtime=0) + gzip.compress(text[1000:], mtime=0) + gzips.append({"name": "members", "data": two, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)}) + + # compressed tars + inner = writes[2]["data"] + wrapped = [ + {"name": "a.tar.gz", "data": gzip.compress(inner, mtime=0), "outer": "gzip"}, + {"name": "a.tgz", "data": tool("gzip", "gzip", ["-c", "-n"], input=inner), "outer": "gzip"}, + {"name": "a.tar.bz2", "data": bz2.compress(inner), "outer": "bz2"}, + {"name": "a.tar.xz", "data": lzma.compress(inner), "outer": "xz"}, + {"name": "a.tar.zst", "data": tool("zstd", "zstd", ["-c", "-q"], input=inner), "outer": "zst"}, + {"name": "a.tar.br", "data": ctx.python(["brotli"], "import brotli, sys; sys.stdout.buffer.write(brotli.compress(sys.stdin.buffer.read()))", input=inner), "outer": "br"}, + ] + ctx.emit("tar", {"files": [{"name": n, "data": d} for n, d in files], "writes": writes, "tars": tars, + "gzips": gzips, "wrapped": wrapped, "innerEntries": entries_of(inner)}) diff --git a/tools/fixtures/zstd.py b/tools/fixtures/zstd.py new file mode 100644 index 0000000..afaa29c --- /dev/null +++ b/tools/fixtures/zstd.py @@ -0,0 +1,85 @@ +# Zstd fixtures (tools/fixtures.py): deterministic corpora compressed with the zstd CLI (the reference) at levels +# 1..19 and --ultra -22, --long, small windows (small blocks), with / without the content checksum, with / without the +# content size (stdin), multi-frame and skippable-frame streams, and empty input; plus a ~6 MB bench corpus. +# tests/gen/zstd.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } } +# tests/gen/zstd_bench.luau { size, data3, data19, crc } +import os, random, shutil, subprocess, tempfile, zlib + + +def generate(ctx): + rng = random.Random(7) + + def zstd(args, data, from_file=True): + exe = shutil.which("zstd") + if from_file: + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "in") + with open(p, "wb") as f: + f.write(data) + argv = ["zstd", "-q", "-c"] + args + [p] + if exe: + return subprocess.run([exe] + argv[1:], capture_output=True, check=True).stdout + return ctx.nix("zstd", argv) + argv = ["zstd", "-q", "-c"] + args + if exe: + return subprocess.run([exe] + argv[1:], input=data, capture_output=True, check=True).stdout + return ctx.nix("zstd", argv, input=data) + + def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + text = text_corpus(400000) + corpora = { + "empty": b"", + "one": b"a", + "short": b"hello, hello, hello zstd world\n", + "text": text[:200000], + "random": rng.randbytes(50000), + "runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300, + "far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)), + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)), + "mixed": bytes(rng.choice(b"aaaaabbbcd\n") for _ in range(30000)) + rng.randbytes(3000) + text[200000:300000], + "big": (text + bytes(rng.choice(b"\0\0\x01\x02\x03xyz") for _ in range(200000))), + } + + cases = [] # (name, corpus, data) + for cname, data in corpora.items(): + levels = [1, 3, 19] if cname in ("big",) else [1, 2, 3, 5, 7, 9, 12, 15, 17, 19] + for lv in levels: + cases.append(("%s/l%d" % (cname, lv), cname, zstd(["-%d" % lv], data))) + if cname != "big": + cases.append(("%s/ultra22" % cname, cname, zstd(["--ultra", "-22"], data))) + cases.append(("%s/long" % cname, cname, zstd(["--long=24", "-9"], data))) + cases.append(("%s/negative" % cname, cname, zstd(["--fast=3"], data))) + cases.append(("%s/wlog10" % cname, cname, zstd(["--zstd=wlog=10", "-6"], data))) + cases.append(("%s/nocheck" % cname, cname, zstd(["-5", "--no-check"], data))) + cases.append(("%s/stdin" % cname, cname, zstd(["-4", "--check"], data, from_file=False))) + + # several frames, a skippable frame between them, and a skippable frame first + t = corpora["text"] + skip = (0x184D2A53).to_bytes(4, "little") + (11).to_bytes(4, "little") + b"skip me now" + multi = zstd(["-3"], t[:50000]) + skip + zstd(["-1", "--no-check"], corpora["runs"]) + zstd(["-3"], b"") + zstd(["-19"], t[50000:90000]) + corpora["multi"] = t[:50000] + corpora["runs"] + t[50000:90000] + cases.append(("multi/frames", "multi", multi)) + corpora["skipfirst"] = corpora["short"] + cases.append(("skipfirst/frames", "skipfirst", skip + zstd(["-3"], corpora["short"]) + skip)) + + ctx.emit("zstd", { + "corpora": corpora, + "cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases], + }) + + bench = bytearray() + while len(bench) < 6_000_000: + bench += text + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000) + bench = bytes(bench[:6_000_000]) + ctx.emit("zstd_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data3": zstd(["-3"], bench), + "data19": zstd(["-19"], bench)})