Files
rosetta/src/Formats/codecs/compress/Lzw/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

283 lines
8.5 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/compress/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