--!strict --!native --!optimize 2 -- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: -- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset -- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5") -- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length -- offset prefixes, 4 KB window -- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes) -- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman) -- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill -- them (spaces; lz5's pattern), and offsets before the start of the output read that fill. -- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c, -- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead -- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description). -- -- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message -- -- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes -- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7. local Huffman = require("@rosetta/codecs/entropy/Huffman") local Lzh = {} local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift local floor = math.floor -- ------------------------------------------------------------------------------------------------ bit reader -- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and -- over counts them type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number } local function reader(src: buffer, off: number, len: number): Reader return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } end local function fill(r: Reader) while r.cnt <= 24 do local b = 0 if r.pos < r.limit then b = readu8(r.src, r.pos) r.pos += 1 else r.over += 8 end r.acc = r.acc * 256 + b r.cnt += 8 end end local function peek(r: Reader, n: number): number if r.cnt < n then fill(r) end return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n end local function skip(r: Reader, n: number) if r.cnt < n then fill(r) end r.cnt -= n r.acc = r.acc % 2 ^ r.cnt end local function bits(r: Reader, n: number): number if n == 0 then return 0 end local v = peek(r, n) skip(r, n) return v end -- ------------------------------------------------------------------------------------------------ static Huffman type Table = { tab: buffer, P: number, S: number, single: number } local function newTable(nsym: number, P: number): Table return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } end local function build(t: Table, lens: buffer, n: number): boolean t.single = -1 local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P) if S < 0 then return false end t.S = S return true end local function decodeSym(r: Reader, t: Table): number if t.single >= 0 then return t.single end local P, S = t.P, t.S local e = readu32(t.tab, peek(r, P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end local idx = peek(r, P + S) e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) l = band(e, 31) if l == 0 then return -1 end end skip(r, l) return rshift(e, 5) end local lens = buffer.create(512) local function lengthValue(r: Reader): number local len = bits(r, 3) if len == 7 then while bits(r, 1) == 1 do len += 1 if len > 16 then return 17 end end end return len end -- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean local n = bits(r, nbits) if n == 0 then t.single = bits(r, nbits) return true end n = math.min(n, maxN) buffer.fill(lens, 0, 0, 512) local i = 0 while i < n do local l = lengthValue(r) if l > 16 then return false end writeu8(lens, i, l) if i == special then local z = bits(r, 2) i += z -- zeros (already zero) end i += 1 end return build(t, lens, math.min(i, maxN)) end local function readCodes(r: Reader, temp: Table, codes: Table): boolean local n = bits(r, 9) if n == 0 then codes.single = bits(r, 9) return true end n = math.min(n, 510) buffer.fill(lens, 0, 0, 512) local i = 0 while i < n do local c = decodeSym(r, temp) if c < 0 then return false end if c <= 2 then local count = if c == 0 then 1 elseif c == 1 then bits(r, 4) + 3 else bits(r, 9) + 20 i += count else if c - 2 > 16 then return false end writeu8(lens, i, c - 2) i += 1 end end return build(codes, lens, n) end local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string? local r = reader(src, off, len) local obits = OFFSET_BITS[method] local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8) local o = 0 local remaining = 0 while o < n do if remaining == 0 then remaining = bits(r, 16) if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then return if r.over > 0 then "truncated" else "bad Huffman table" end if r.over > 32 then return "truncated" end if remaining == 0 then return "empty block" end end remaining -= 1 local c = decodeSym(r, codes) if c < 0 then return "bad code" end if c < 256 then writeu8(out, o, c) o += 1 else local count = c - 256 + 3 local p = decodeSym(r, offs) if p < 0 then return "bad offset code" end if p > 1 then p = lshift(1, p - 1) + bits(r, p - 1) end local from = o - p - 1 for _ = 1, count do if o >= n then break end writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) o += 1 from += 1 end end if r.over > 32 then return "truncated" end end return nil end -- ------------------------------------------------------------------------------------------------ lh1 local NUM_CODES = 314 local NUM_NODES = NUM_CODES * 2 - 1 local REORDER = 32 * 1024 local FDIST = { 1, 3, 8, 12, 24, 16 } local offsetLookup = table.create(256, 0) local offsetLength = table.create(64, 0) do local code, offset = 0, 0 for i, count in FDIST do local l = i - 1 + 3 local iter = lshift(1, 8 - l) for _ = 1, count do for k = 0, iter - 1 do offsetLookup[code + k + 1] = offset end offsetLength[offset + 1] = l code += iter offset += 1 end end end local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) -- node arrays (0-based indexes stored at [i + 1]) local leaf = table.create(NUM_NODES, false) local child = table.create(NUM_NODES, 0) local parent = table.create(NUM_NODES, 0) local freq = table.create(NUM_NODES, 0) local group = table.create(NUM_NODES, 0) local leafNodes = table.create(NUM_CODES, 0) local groups = table.create(NUM_NODES, 0) local leader = table.create(NUM_NODES, 0) local numGroups = 0 local function initGroups() for i = 0, NUM_NODES - 1 do groups[i + 1] = i end numGroups = 0 end local function allocGroup(): number local g = groups[numGroups + 1] numGroups += 1 return g end local function freeGroup(g: number) numGroups -= 1 groups[numGroups + 1] = g end initGroups() do local ni = NUM_NODES - 1 local lg = allocGroup() for i = 0, NUM_CODES - 1 do leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg leader[lg + 1] = ni leafNodes[i + 1] = ni ni -= 1 end local c = NUM_NODES - 1 while ni >= 0 do leaf[ni + 1], child[ni + 1] = false, c parent[c + 1], parent[c] = ni, ni freq[ni + 1] = freq[c + 1] + freq[c] if freq[ni + 1] == freq[ni + 2] then group[ni + 1] = group[ni + 2] else group[ni + 1] = allocGroup() end leader[group[ni + 1] + 1] = ni ni -= 1 c -= 2 end end local function makeLeader(ni: number): number local g = group[ni + 1] local li = leader[g + 1] if li == ni then return ni end leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1] child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1] for _, x in { ni, li } do if leaf[x + 1] then leafNodes[child[x + 1] + 1] = x else parent[child[x + 1] + 1] = x parent[child[x + 1]] = x end end return li end local function incrementNode(ni: number) freq[ni + 1] += 1 if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then leader[group[ni + 1] + 1] += 1 if freq[ni + 1] == freq[ni] then group[ni + 1] = group[ni] else group[ni + 1] = allocGroup() leader[group[ni + 1] + 1] = ni end elseif freq[ni + 1] == freq[ni] then freeGroup(group[ni + 1]) group[ni + 1] = group[ni] end end local function reconstruct() -- leaves to the front, halved local li = 0 for i = 0, NUM_NODES - 1 do if leaf[i + 1] then leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], (freq[i + 1] + 1) // 2 li += 1 end end local lp = NUM_CODES - 1 local c = NUM_NODES - 1 local i = NUM_NODES - 1 while i >= 0 do while c - i < 2 do leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] leafNodes[child[i + 1] + 1] = i i -= 1 lp -= 1 end local f = freq[c + 1] + freq[c] while lp >= 0 and f >= freq[lp + 1] do leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] leafNodes[child[i + 1] + 1] = i i -= 1 lp -= 1 end leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c parent[c + 1], parent[c] = i, i i -= 1 c -= 2 end initGroups() local g = allocGroup() group[1] = g leader[g + 1] = 0 for k = 1, NUM_NODES - 1 do if freq[k + 1] == freq[k] then group[k + 1] = group[k] else g = allocGroup() group[k + 1] = g leader[g + 1] = k end end end local o = 0 while o < n do local ni = 0 local guard = 0 while not leaf[ni + 1] do ni = child[ni + 1] - bits(r, 1) guard += 1 if guard > NUM_NODES or ni < 0 then return "bad tree" end end local code = child[ni + 1] -- increment_for_code if freq[1] >= REORDER then reconstruct() end freq[1] += 1 local x = leafNodes[code + 1] while x ~= 0 do x = makeLeader(x) incrementNode(x) x = parent[x + 1] end if code < 256 then writeu8(out, o, code) o += 1 else local future = peek(r, 8) local hi = offsetLookup[future + 1] skip(r, offsetLength[hi + 1]) local offset = hi * 64 + bits(r, 6) local count = code - 256 + 3 local from = o - offset - 1 for _ = 1, count do if o >= n then break end writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) o += 1 from += 1 end end if r.over > 32 then return "truncated" end end return nil end -- ------------------------------------------------------------------------------------------------ LArc lzs / lz5 -- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances) local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local ring = buffer.create(2048) buffer.fill(ring, 0, 0x20) local rp = 2048 - 17 local o = 0 while o < n do if bits(r, 1) == 1 then local b = bits(r, 8) writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 2048 o += 1 else local pos = bits(r, 11) local l = bits(r, 4) + 2 for k = 0, l - 1 do if o >= n then break end local b = readu8(ring, (pos + k) % 2048) writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 2048 o += 1 end end if r.over > 32 then return "truncated" end end return nil end local LZ5_INIT = buffer.create(4096) do local p = 0 for i = 0, 255 do for _ = 1, 13 do writeu8(LZ5_INIT, p, i) p += 1 end end for i = 0, 255 do writeu8(LZ5_INIT, p, i) p += 1 end for i = 0, 255 do writeu8(LZ5_INIT, p, 255 - i) p += 1 end p += 128 for _ = 1, 110 do writeu8(LZ5_INIT, p, 0x20) p += 1 end end local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string? local ring = buffer.create(4096) buffer.copy(ring, 0, LZ5_INIT) local rp = 4096 - 18 local p = off local limit = math.min(off + len, buffer.len(src)) local o = 0 while o < n do if p >= limit then return "truncated" end local flags = readu8(src, p) p += 1 for bit = 0, 7 do if o >= n then break end if band(flags, lshift(1, bit)) ~= 0 then if p >= limit then return "truncated" end local b = readu8(src, p) p += 1 writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 4096 o += 1 else if p + 2 > limit then return "truncated" end local c0, c1 = readu8(src, p), readu8(src, p + 1) p += 2 local start = lshift(band(c1, 0xF0), 4) + c0 local l = band(c1, 15) + 3 for k = 0, l - 1 do if o >= n then break end local b = readu8(ring, (start + k) % 4096) writeu8(out, o, b) writeu8(ring, rp, b) rp = (rp + 1) % 4096 o += 1 end end end end return nil end -- ------------------------------------------------------------------------------------------------ ARJ method 4 local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? local r = reader(src, off, len) local function prefixed(start: number, stop: number): number local plus, pwr = 0, lshift(1, start) local width = start while width < stop do if bits(r, 1) == 0 then break end plus += pwr pwr *= 2 width += 1 end return (if width ~= 0 then bits(r, width) else 0) + plus end local o = 0 while o < n do local c = prefixed(0, 7) if c == 0 then writeu8(out, o, bits(r, 8)) o += 1 else local count = c - 1 + 3 local pos = prefixed(9, 13) local from = o - pos - 1 for _ = 1, count do if o >= n then break end writeu8(out, o, if from >= 0 then readu8(out, from) else 0) o += 1 from += 1 end end if r.over > 32 then return "truncated" end end return nil end -- ------------------------------------------------------------------------------------------------ api Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } -- decode(src, off, len, outSize, method) -> buffer | nil, message function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then return nil, "bad arguments" end local out = buffer.create(outSize) if outSize == 0 then return out, nil end local err: string? if OFFSET_BITS[method] then err = decodeNew(src, off, len, out, outSize, method) elseif method == "lh1" then err = decodeLh1(src, off, len, out, outSize) elseif method == "lzs" then err = decodeLzs(src, off, len, out, outSize) elseif method == "lz5" then err = decodeLz5(src, off, len, out, outSize) elseif method == "arj4" then err = decodeArj4(src, off, len, out, outSize) else return nil, "unsupported: method " .. tostring(method) end if err then return nil, err end return out, nil end return Lzh