Files
rosetta/src/Formats/codecs/compress/Deflate/init.luau
T
4DBug 51b08575c4 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
2026-10-31 12:25:03 -05:00

267 lines
9.6 KiB
Luau

--!strict
-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
-- (same author; no third-party code); the compressor is new.
--
-- local Deflate = require("@formats/codecs/compress/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Adler32 = require("@formats/core/Adler32")
local Inflate = require("@formats/codecs/compress/Deflate/Inflate")
local Compress = require("@formats/codecs/compress/Deflate/Compress")
local Deflate = {}
Deflate.version = "1.1.0"
local toBuffer = Bytes.toBuffer
local args = Bytes.span
local function shrink(out: buffer, n: number): buffer
if buffer.len(out) == n then
return out
end
local b = buffer.create(n)
buffer.copy(b, 0, out, 0, n)
return b
end
local function inflateErr(msg: string, at: number?): Err.Err
local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT
return Err.new(code, "inflate: " .. msg, at)
end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
return nil, aerr
end
local exact = expectedSize ~= nil
local cap
if exact then
if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize))
end
cap = expectedSize
else
cap = math.max(1024, l * 4)
end
local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact)
if not out then
return nil, inflateErr(tostring(n), o)
end
if exact and n ~= expectedSize then
return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number))
end
return shrink(out, n), consumed
end
-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err
function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.zlib", buf, offset, length)
if not b then
return nil, aerr
end
if l < 6 then
return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o)
end
local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1)
if cmf % 16 ~= 8 or cmf // 16 > 7 then
return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o)
end
if (cmf * 256 + flg) % 31 ~= 0 then
return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o)
end
if bit32.band(flg, 0x20) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o)
end
local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize)
if not out then
return nil, consumed
end
if consumed + 4 > o + l then
return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed)
end
local want = bit32.byteswap(buffer.readu32(b, consumed))
local got = Adler32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
return out, consumed + 4
end
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length)
if not b then
return nil, aerr
end
local e = o + l
local parts, total = {}, 0
local p = o
repeat
if p + 18 > e then
if #parts > 0 then
break
end
return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p)
end
if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then
if #parts > 0 then
break -- trailing garbage after a member: ignored, as gzip -d does
end
return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p)
end
if buffer.readu8(b, p + 2) ~= 8 then
return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2)
end
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3)
end
local q = p + 10
if bit32.band(flg, 4) ~= 0 then -- FEXTRA
if q + 2 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
q += 2 + buffer.readu16(b, q)
end
for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated
if bit32.band(flg, bit) ~= 0 then
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
q += 1
end
end
if bit32.band(flg, 2) ~= 0 then -- FHCRC
q += 2
end
if q >= e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
local out, consumed = Deflate.inflate(b, q, e - q)
if not out then
return nil, consumed
end
if consumed + 8 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed)
end
local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4)
local got = Crc32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
if buffer.len(out) % 4294967296 ~= isize then
return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4)
end
table.insert(parts, out)
total += buffer.len(out)
p = consumed + 8
-- skip zero padding
local z = p
while z < e and buffer.readu8(b, z) == 0 do
z += 1
end
if z == e then
break
end
until p >= e
if #parts == 1 then
return parts[1], nil
end
local res = buffer.create(total)
local w = 0
for _, part in parts do
buffer.copy(res, w, part)
w += buffer.len(part)
end
return res, nil
end
export type CompressOptions = {
level: number?, -- 0 (stored) .. 9 (best); default 6
}
local function level(opts: CompressOptions?): number?
local lv = if opts and opts.level ~= nil then opts.level else 6
if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then
return nil
end
return lv
end
-- compress(buf, opts?) -> raw deflate buffer | nil, Err
function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9")
end
return Compress.raw(b, 0, buffer.len(b), lv), nil
end
-- zlibCompress(buf, opts?) -> zlib stream | nil, Err
function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 6)
local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3
local cmf = 0x78
local flg = flevel * 64
flg += 31 - (cmf * 256 + flg) % 31
buffer.writeu8(out, 0, cmf)
buffer.writeu8(out, 1, flg)
buffer.copy(out, 2, raw, 0, n)
buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b))))
return out, nil
end
-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err
function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 18)
buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0")
buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0)
buffer.writeu8(out, 9, 255)
buffer.copy(out, 10, raw, 0, n)
buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b)))
buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296)
return out, nil
end
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Crc32.of(b, offset, length, crc)
end
Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Adler32.of(b, offset, length, adler)
end
return Deflate