diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..17d4818 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,3 +10,4 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and diff --git a/src/Formats/codecs/Lzw/init.luau b/src/Formats/codecs/Lzw/init.luau new file mode 100644 index 0000000..168ded4 --- /dev/null +++ b/src/Formats/codecs/Lzw/init.luau @@ -0,0 +1,282 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and +-- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13. +-- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width +-- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear). +-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code +-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is +-- detected by its first bytes (0x00 then an odd byte) and decoded too. +-- +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff") +-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer +-- local codes = Lzw.encode(data, off, len, "tiff") +-- +-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of +-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or +-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that +-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway). +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local blen = buffer.len + +local Lzw = {} + +local MAX_CODES = 4096 + +-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield) +local prefix = buffer.create(MAX_CODES * 2) -- u16: the code this entry extends +local suffix = buffer.create(MAX_CODES) -- u8: its last byte +local first = buffer.create(MAX_CODES) -- u8: its first byte +local length = buffer.create(MAX_CODES * 2) -- u16: its length + +-- ------------------------------------------------------------------------------------------------ decode +-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim) +local function emit(out: buffer, o: number, c: number, l: number, lim: number) + local p = o + l - 1 + if p < lim then + while p >= o do + writeu8(out, p, readu8(suffix, c)) + c = readu16(prefix, c * 2) + p -= 1 + end + else + while p >= o do + if p < lim then + writeu8(out, p, readu8(suffix, c)) + end + c = readu16(prefix, c * 2) + p -= 1 + end + end +end + +function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?) + local n = blen(src) + if off < 0 or off > n then + return 0, "corrupt" + end + local e = math.min(off + math.max(0, len), n) + local lim = math.min(outOff + math.max(0, maxOut), blen(out)) + if outOff < 0 then + return 0, "corrupt" + end + local msb = variant == "tiff" + local early = 0 -- 1 for TIFF's early change + local min = minCodeSize or 8 + if msb then + min = 8 + early = 1 + -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check) + if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then + msb = false + early = 0 + end + end + if min < 1 or min > 11 then + return 0, "corrupt" + end + local clear = lshift(1, min) + local eoi = clear + 1 + for i = 0, clear - 1 do + writeu16(prefix, i * 2, 0) + writeu8(suffix, i, band(i, 255)) + writeu8(first, i, band(i, 255)) + writeu16(length, i * 2, 1) + end + local size = min + 1 + local mask = lshift(1, size) - 1 + local nextc = clear + 2 + local prev = -1 + local o = outOff + local p = off + local acc, nb = 0, 0 + while true do + -- refill (at most 12 + 7 bits held: below 2^20) + while nb < size do + if p >= e then + return o - outOff, "truncated" + end + if msb then + acc = acc * 256 + readu8(src, p) + else + acc += lshift(readu8(src, p), nb) + end + p += 1 + nb += 8 + end + local c + if msb then + nb -= size + c = band(rshift(acc, nb), mask) + acc = band(acc, lshift(1, nb) - 1) + else + c = band(acc, mask) + acc = rshift(acc, size) + nb -= size + end + if c == clear then + size = min + 1 + mask = lshift(1, size) - 1 + nextc = clear + 2 + prev = -1 + elseif c == eoi then + return o - outOff, nil + else + if o >= lim then + return o - outOff, nil -- full: the rest (normally just EOI) is ignored + end + if prev < 0 then + if c >= clear then + return o - outOff, "corrupt" + end + writeu8(out, o, readu8(suffix, c)) + o += 1 + prev = c + else + local l + if c < nextc then + l = readu16(length, c * 2) + emit(out, o, c, l, lim) + if nextc < MAX_CODES then + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, readu8(first, c)) + writeu8(first, nextc, readu8(first, prev)) + writeu16(length, nextc * 2, readu16(length, prev * 2) + 1) + nextc += 1 + end + elseif c == nextc and nextc < MAX_CODES then + -- KwKwK: the new entry is prev + first(prev) + local f = readu8(first, prev) + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, f) + writeu8(first, nextc, f) + l = readu16(length, prev * 2) + 1 + writeu16(length, nextc * 2, l) + nextc += 1 + emit(out, o, c, l, lim) + else + return o - outOff, "corrupt" + end + o = math.min(o + l, lim) + prev = c + end + if nextc + early >= lshift(1, size) and size < 12 then + size += 1 + mask = lshift(1, size) - 1 + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ encode +local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries +local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty) +local hval = buffer.create(HASH * 2) -- u16 code + +-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in +-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF). +function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer + local msb = variant == "tiff" + local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11) + local early = if msb then 1 else 0 + local symMask = lshift(1, min) - 1 + local clear = lshift(1, min) + local eoi = clear + 1 + local n = blen(data) + off = math.clamp(off, 0, n) + local e = math.clamp(off + len, off, n) + local cap = (e - off) * 2 + 64 + local out = buffer.create(cap) + local op = 0 + local acc, nb = 0, 0 + local size = min + 1 + local function put(code: number) + if op + 4 > cap then + cap *= 2 + local nbuf = buffer.create(cap) + buffer.copy(nbuf, 0, out, 0, op) + out = nbuf + end + if msb then + acc = acc * lshift(1, size) + code + nb += size + while nb >= 8 do + nb -= 8 + writeu8(out, op, rshift(acc, nb)) + op += 1 + acc = band(acc, lshift(1, nb) - 1) + end + else + acc += lshift(code, nb) + nb += size + while nb >= 8 do + writeu8(out, op, band(acc, 255)) + op += 1 + acc = rshift(acc, 8) + nb -= 8 + end + end + end + buffer.fill(hkey, 0, 0, HASH * 4) + local nextc = clear + 2 + put(clear) + if e > off then + local cur = band(readu8(data, off), symMask) + for i = off + 1, e - 1 do + local b = band(readu8(data, i), symMask) + local key = cur * 256 + b + 1 + local h = band(cur * 31 + b * 4099, HASH - 1) + local found = -1 + while true do + local k = buffer.readi32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu16(hval, h * 2) + break + end + h = band(h + 1, HASH - 1) + end + if found >= 0 then + cur = found + else + put(cur) + if nextc >= MAX_CODES - 2 then + put(clear) + size = min + 1 + nextc = clear + 2 + buffer.fill(hkey, 0, 0, HASH * 4) + else + buffer.writei32(hkey, h * 4, key) + writeu16(hval, h * 2, nextc) + nextc += 1 + if nextc + early > lshift(1, size) and size < 12 then + size += 1 + end + end + cur = b + end + end + put(cur) + -- the decoder adds an entry for this last code too: its width may grow before EOI + if nextc < MAX_CODES then + nextc += 1 + if nextc + early > lshift(1, size) and size < 12 then + size += 1 + end + end + end + put(eoi) + if nb > 0 then + writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255)) + op += 1 + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res +end + +return Lzw diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 29090f1..9cbeb8f 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -164,6 +164,28 @@ end -- ------------------------------------------------------------------------------------------------ API export type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options +-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format, +-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> +-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for +-- the embedded parts) when called directly. +local function withHooks(o: Options): Options + if o.decodeImage ~= nil and o.encodeImage ~= nil then + return o + end + local c = table.clone(o) + if c.decodeImage == nil then + c.decodeImage = function(b: buffer): (any, Err.Err?) + return F.load(b, { category = "image" }) + end + end + if c.encodeImage == nil then + c.encodeImage = function(img: any, format: string): (any, Err.Err?) + return F.save(img, nil, { format = format, category = "image" }) + end + end + return c +end + -- load(src, opts?) -> value | nil, Err function F.load(src: any, opts: Options?): (any, Err.Err?) local o = opts or {} @@ -181,7 +203,7 @@ function F.load(src: any, opts: Options?): (any, Err.Err?) end local value, err if m.decode then - local ok, v, e = pcall(m.decode, Bytes.reader(buf), o) + local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) end @@ -274,7 +296,7 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?) if not entry then return nil, err end - local ok, buf, e = pcall(m.encode, value, o) + local ok, buf, e = pcall(m.encode, value, withHooks(o)) if not ok then return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) end diff --git a/tests/codecs/lzw.luau b/tests/codecs/lzw.luau new file mode 100644 index 0000000..04fe064 --- /dev/null +++ b/tests/codecs/lzw.luau @@ -0,0 +1,119 @@ +-- codecs/Lzw tests: GIF (LSB) and TIFF (MSB, early change) code streams from Pillow / libtiff decode to their data; +-- our encoder round-trips random and structured data at every GIF minimum code size and through table resets; the +-- output limit, truncated and corrupt streams; the fuzz no-throw pass. Fixtures: tools/fixtures/lzw.py. +local T = require("@tests/T") +local Lzw = require("@formats/codecs/Lzw") +local Fx = require("@tests/gen/lzw") + +local t = T.suite("lzw") + +local function dec(codes: buffer, n: number, variant: string, min: number?): (string, number, string?) + local out = buffer.create(n) + local got, err = Lzw.decode(codes, 0, buffer.len(codes), out, 0, n, variant, min) + return buffer.tostring(out), got, err +end + +-- reference streams +for _, c in Fx.gif do + local s, n, err = dec(buffer.fromstring(c.codes), #c.data, "gif", c.min) + t:check(err == nil, "gif " .. c.name .. ": " .. tostring(err)) + t:eq(n, #c.data, "gif " .. c.name .. ": length") + t:check(s == c.data, "gif " .. c.name .. ": data") +end +for _, c in Fx.tiff do + local s, n, err = dec(buffer.fromstring(c.codes), #c.data, "tiff") + t:check(err == nil, "tiff " .. c.name .. ": " .. tostring(err)) + t:eq(n, #c.data, "tiff " .. c.name .. ": length") + t:check(s == c.data, "tiff " .. c.name .. ": data") +end +t:note("%d GIF and %d TIFF reference streams decode", #Fx.gif, #Fx.tiff) + +-- round trips +local rand = T.rng(3) +local function data(n: number, kind: number, max: number): buffer + local b = buffer.create(n) + for i = 0, n - 1 do + local v + if kind == 0 then + v = rand(max) + elseif kind == 1 then + v = (i // 7) % max + else + v = if rand(10) == 0 then rand(max) else (i % 13) % max + end + buffer.writeu8(b, i, v) + end + return b +end +local trips = 0 +for _, n in { 0, 1, 2, 3, 100, 5000, 70000 } do + for kind = 0, 2 do + for min = 2, 8 do + local d = data(n, kind, 2 ^ min) + local codes = Lzw.encode(d, 0, n, "gif", min) + local s, got, err = dec(codes, n, "gif", min) + t:check(err == nil and got == n and s == buffer.tostring(d), string.format("gif round trip n=%d kind=%d min=%d: %s", n, kind, min, tostring(err))) + trips += 1 + end + local d = data(n, kind, 256) + local codes = Lzw.encode(d, 0, n, "tiff") + local s, got, err = dec(codes, n, "tiff") + t:check(err == nil and got == n and s == buffer.tostring(d), string.format("tiff round trip n=%d kind=%d: %s", n, kind, tostring(err))) + trips += 1 + end +end +t:note("%d round trips", trips) + +-- compression actually happens; a range inside a bigger buffer +do + local d = buffer.create(10000) + local codes = Lzw.encode(d, 0, 10000, "tiff") + t:check(buffer.len(codes) < 400, "zeros compress: " .. buffer.len(codes)) + local big = data(300, 1, 256) + local codes2 = Lzw.encode(big, 100, 100, "gif", 8) + local out = buffer.create(120) + local n = Lzw.decode(codes2, 0, buffer.len(codes2), out, 10, 100, "gif", 8) + t:eq(n, 100, "sub-range length") + t:check(buffer.readstring(out, 10, 100) == buffer.readstring(big, 100, 100), "sub-range data") +end + +-- limits, truncation, corruption +do + local d = data(1000, 2, 16) + local codes = Lzw.encode(d, 0, 1000, "gif", 4) + local s, n, err = dec(codes, 500, "gif", 4) + t:check(n == 500 and err == nil and s == buffer.readstring(d, 0, 500), "output limit") + local cut = buffer.create(buffer.len(codes) // 2) + buffer.copy(cut, 0, codes, 0, buffer.len(cut)) + local _, n2, err2 = dec(cut, 1000, "gif", 4) + t:check(err2 == "truncated" and n2 > 0 and n2 < 1000, "truncated: " .. tostring(err2)) + local bad = buffer.fromstring("\255\255\255\255") + local _, _, err3 = dec(bad, 100, "gif", 2) + t:check(err3 == "corrupt", "corrupt: " .. tostring(err3)) + local _, _, err4 = dec(codes, 100, "gif", 0) + t:check(err4 == "corrupt", "bad min code size") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.gif do + if i % 2 == 1 then + table.insert(samples, c.codes) + end + end + for i, c in Fx.tiff do + if i % 2 == 0 then + table.insert(samples, c.codes) + end + end + local out = buffer.create(100000) + t:fuzz("decode gif", function(b: buffer) + return Lzw.decode(b, 0, buffer.len(b), out, 0, 100000, "gif", 8) + end, samples) + t:fuzz("decode tiff", function(b: buffer) + return Lzw.decode(b, 0, buffer.len(b), out, 0, 100000, "tiff") + end, samples) +end + +t:done() diff --git a/tools/fixtures/lzw.py b/tools/fixtures/lzw.py new file mode 100644 index 0000000..6cb37f9 --- /dev/null +++ b/tools/fixtures/lzw.py @@ -0,0 +1,70 @@ +# LZW fixtures (tools/fixtures.py): code streams written by reference encoders, with the data they encode. +# tests/gen/lzw.luau { gif = { { name, min, codes, data } }, tiff = { { name, codes, data } } } +# gif: Pillow's GIF writer (its own LZW), the image data sub-blocks joined; data = the palette indexes +# tiff: libtiff's LZW (Pillow compression="tiff_lzw"), one strip; data = the raw 8-bit samples +import struct + +CODE = r''' +import io, random, struct, sys +from PIL import Image +rng = random.Random(7) +def img(w, h, kind, ncol): + px = bytearray() + for y in range(h): + for x in range(w): + if kind == "noise": + px.append(rng.randrange(ncol)) + elif kind == "flat": + px.append(3 % ncol) + else: + px.append(((x // 3) ^ (y // 5)) % ncol if rng.random() < 0.97 else rng.randrange(ncol)) + return bytes(px) +out = [] +for (w, h, kind, ncol) in ((1, 1, "noise", 2), (16, 16, "noise", 2), (64, 48, "pattern", 4), (64, 48, "noise", 16), + (300, 200, "pattern", 256), (300, 200, "noise", 256), (256, 200, "flat", 256), (97, 3, "noise", 128)): + data = img(w, h, kind, ncol) + im = Image.frombytes("P", (w, h), data) + im.putpalette(bytes(range(256)) * 3) + b = io.BytesIO(); im.save(b, "GIF", optimize=False, interlace=False); g = b.getvalue() + # walk to the image descriptor + p = 13 + (3 << ((g[10] & 7) + 1) if g[10] & 0x80 else 0) + while g[p] != 0x2C: + p += 2 + while g[p]: p += g[p] + 1 + p += 1 + flags = g[p + 9]; p += 10 + if flags & 0x80: p += 3 << ((flags & 7) + 1) + mn = g[p]; p += 1; codes = bytearray() + while g[p]: codes += g[p + 1:p + 1 + g[p]]; p += g[p] + 1 + # Pillow may reduce the palette: decode its own image back for the indexes + back = Image.open(io.BytesIO(g)); back.load() + out.append(("gif", "%dx%d-%s-%d" % (w, h, kind, ncol), mn, bytes(codes), back.tobytes())) + t = io.BytesIO() + Image.frombytes("L", (w, h), data).save(t, "TIFF", compression="tiff_lzw", rowsperstrip=h) + tb = t.getvalue() + le = tb[:2] == b"II"; E = "<" if le else ">" + ifd = struct.unpack(E + "I", tb[4:8])[0]; n = struct.unpack(E + "H", tb[ifd:ifd + 2])[0] + tags = {} + for i in range(n): + tag, typ, cnt, val = struct.unpack(E + "HHII", tb[ifd + 2 + i * 12: ifd + 14 + i * 12]) + if typ == 3 and cnt == 1: + val = struct.unpack(E + "H", tb[ifd + 10 + i * 12: ifd + 12 + i * 12])[0] + tags[tag] = (val, cnt) + assert tags[259][0] == 5 and tags[273][1] == 1, "one LZW strip" + off, cnt = tags[273][0], tags[279][0] + out.append(("tiff", "%dx%d-%s-%d" % (w, h, kind, ncol), 8, tb[off:off + cnt], data)) +for kind, name, mn, codes, data in out: + sys.stdout.buffer.write(struct.pack("<4sB", kind.ljust(4).encode(), len(name)) + name.encode() + struct.pack("