--!strict --!native --!optimize 2 -- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth -- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman -- length-limited codes). Level 0 = stored blocks only. -- -- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments). local Huffman = require("@formats/core/Huffman") local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local floor = math.floor local WSIZE = 32768 local HSIZE = 65536 local MAXMATCH = 258 local BLOCKSYMS = 16384 -- symbols per block -- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no -- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are -- greedy (no lazy matching). local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 } -- length 3..258 -> code 257..285 (index len), its extra bits and base local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0) local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } for c = 1, 29 do local base = LBASE[c] local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1 for len = base, top do LCODE[len] = 256 + c LEXTRA[len] = LEXT[c] LBASEOF[len] = base end end local DBASE = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, } local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } -- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0) for c = 1, 30 do local base = DBASE[c] local top = if c == 30 then 32768 else DBASE[c + 1] - 1 for d = base, math.min(top, 256) do DSMALL[d] = c - 1 end if top > 256 then for k = math.max(base, 257), top, 128 do DLARGE[(k - 1) // 128 + 1] = c - 1 end end end local function dcode(d: number): number if d <= 256 then return DSMALL[d] end return DLARGE[(d - 1) // 128 + 1] end local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } -- fixed codes local FIXLEN = table.create(288, 0) for i = 1, 288 do FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8 end local FIXDLEN = table.create(30, 5) -- reversed (LSB-first) canonical codes for lengths local function revCodes(lens: { number }): { number } local codes = Huffman.codes(lens) for i, l in lens do if l > 0 then codes[i] = Huffman.reverse(codes[i], l) end end return codes end local FIXCODE = revCodes(FIXLEN) local FIXDCODE = revCodes(FIXDLEN) local POW = table.create(33, 0) for i = 0, 32 do POW[i + 1] = 2 ^ i end -- ------------------------------------------------------------------------------------------------ bit output type Out = { buf: buffer, op: number, acc: number, cnt: number } local function ensure(o: Out, n: number) if o.op + n > blen(o.buf) then local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) bcopy(nb, 0, o.buf, 0, o.op) o.buf = nb end end -- put(v, n): n <= 24 bits, LSB first local function put(o: Out, v: number, n: number) local acc = o.acc + v * POW[o.cnt + 1] local cnt = o.cnt + n if cnt >= 8 then ensure(o, 4) local buf, op = o.buf, o.op while cnt >= 8 do local byte = acc % 256 writeu8(buf, op, byte) op += 1 acc = (acc - byte) / 256 cnt -= 8 end o.op = op end o.acc, o.cnt = acc, cnt end local function alignOut(o: Out) if o.cnt > 0 then put(o, 0, 8 - o.cnt) end end -- ------------------------------------------------------------------------------------------------ blocks -- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) local p = s repeat local n = math.min(65535, e - p) local last = final and p + n >= e put(o, if last then 1 else 0, 3) alignOut(o) ensure(o, 4 + n) writeu16(o.buf, o.op, n) writeu16(o.buf, o.op + 2, 65535 - n) bcopy(o.buf, o.op + 4, src, p, n) o.op += 4 + n p += n until p >= e end local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) for i = 1, nsym do local l = L[i] if l < 256 then put(o, lcode[l + 1], llen[l + 1]) else local len = l - 256 local c = LCODE[len] put(o, lcode[c + 1], llen[c + 1]) local xb = LEXTRA[len] if xb > 0 then put(o, len - LBASEOF[len], xb) end local d = D[i] local dc = dcode(d) put(o, dcodes[dc + 1], dlen[dc + 1]) xb = DEXT[dc + 1] if xb > 0 then put(o, d - DBASE[dc + 1], xb) end end end put(o, lcode[257], llen[257]) -- end of block end local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) local lf = table.create(286, 0) local df = table.create(30, 0) local extra = 0 for i = 1, nsym do local l = L[i] if l < 256 then lf[l + 1] += 1 else local len = l - 256 lf[LCODE[len] + 1] += 1 extra += LEXTRA[len] local dc = dcode(D[i]) df[dc + 1] += 1 extra += DEXT[dc + 1] end end lf[257] = 1 local llen = Huffman.lengths(lf, 15) local dlen = Huffman.lengths(df, 15) local hlit = 286 while hlit > 257 and llen[hlit] == 0 do hlit -= 1 end local hdist = 30 while hdist > 1 and dlen[hdist] == 0 do hdist -= 1 end if dlen[1] == 0 and hdist == 1 then dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes) end -- code-length symbols: RLE of the hlit + hdist lengths local all = table.create(hlit + hdist, 0) for i = 1, hlit do all[i] = llen[i] end for i = 1, hdist do all[hlit + i] = dlen[i] end local cs, cx = {}, {} -- symbol, extra value local cf = table.create(19, 0) local i = 1 local total = hlit + hdist while i <= total do local v = all[i] local run = 1 while i + run <= total and all[i + run] == v do run += 1 end if v == 0 and run >= 3 then local r = math.min(run, 138) if r >= 11 then table.insert(cs, 18) table.insert(cx, r - 11) cf[19] += 1 else table.insert(cs, 17) table.insert(cx, r - 3) cf[18] += 1 end i += r elseif v ~= 0 and run >= 4 then table.insert(cs, v) table.insert(cx, 0) cf[v + 1] += 1 local r = math.min(run - 1, 6) table.insert(cs, 16) table.insert(cx, r - 3) cf[17] += 1 i += 1 + r else table.insert(cs, v) table.insert(cx, 0) cf[v + 1] += 1 i += 1 end end local clen = Huffman.lengths(cf, 7) local hclen = 19 while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do hclen -= 1 end -- costs in bits local dyn = 17 + 3 * hclen + extra for k = 1, 19 do dyn += cf[k] * clen[k] end dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7 local fix = 3 + extra for k = 1, 286 do dyn += lf[k] * llen[k] fix += lf[k] * FIXLEN[k] end for k = 1, 30 do dyn += df[k] * dlen[k] fix += df[k] * 5 end local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7 if stored <= dyn and stored <= fix then storedBlock(o, src, s, e, final) return end if fix <= dyn then put(o, if final then 3 else 2, 3) emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) return end put(o, if final then 5 else 4, 3) put(o, hlit - 257, 5) put(o, hdist - 1, 5) put(o, hclen - 4, 4) for k = 1, hclen do put(o, clen[CLORDER[k] + 1], 3) end local ccode = revCodes(clen) for k = 1, #cs do local c = cs[k] put(o, ccode[c + 1], clen[c + 1]) if c == 16 then put(o, cx[k], 2) elseif c == 17 then put(o, cx[k], 3) elseif c == 18 then put(o, cx[k], 7) end end emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) end -- ------------------------------------------------------------------------------------------------ LZ77 local Compress = {} function Compress.raw(src: buffer, off: number, len: number, level: number): buffer local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 } local e = off + len if level == 0 or len == 0 then if len == 0 then put(o, 3, 3) -- one empty fixed block put(o, 0, 7) else storedBlock(o, src, off, e, true) end alignOut(o) local out = bcreate(o.op) bcopy(out, 0, o.buf, 0, o.op) return out end local maxChain = CHAIN[level] local nice = NICE[level] local good = GOOD[level] local lazyMax = LAZY[level] local head = table.create(HSIZE, -1) local prev = table.create(WSIZE, -1) local L = table.create(BLOCKSYMS, 0) local D = table.create(BLOCKSYMS, 0) local nsym = 0 local blockStart = off local function hash(p: number): number return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE end local function insert(p: number) local h = hash(p) + 1 prev[p % WSIZE + 1] = head[h] head[h] = p end -- longest match at p among earlier positions: len (0 if < 3), dist local function find(p: number, steps: number): (number, number) local maxLen = math.min(MAXMATCH, e - p) if maxLen < 3 then return 0, 0 end local best, bestDist = 2, 0 local c = head[hash(p) + 1] local limit = p - WSIZE while c >= 0 and c > limit and steps > 0 do if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then local k = 1 while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do k += 1 end if k > best then best, bestDist = k, p - c if k >= nice or k >= maxLen then break end end end local nc = prev[c % WSIZE + 1] if nc >= c then break -- the slot was reused by a newer position: the chain ends here end c = nc steps -= 1 end if best < 3 then return 0, 0 end return best, bestDist end local function flush(upto: number, final: boolean) block(o, src, blockStart, upto, L, D, nsym, final) nsym = 0 blockStart = upto end local p = off local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed while p < e do local mlen, mdist = 0, 0 if p <= stop3 then mlen, mdist = find(p, maxChain) insert(p) if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain) if l2 > mlen then -- a literal now, the longer match from p + 1 nsym += 1 L[nsym] = readu8(src, p) D[nsym] = 0 p += 1 insert(p) mlen, mdist = l2, d2 end end end if mlen >= 3 then nsym += 1 L[nsym] = 256 + mlen D[nsym] = mdist local q = p + 1 local qe = math.min(p + mlen, stop3 + 1) while q < qe do insert(q) q += 1 end p += mlen else nsym += 1 L[nsym] = readu8(src, p) D[nsym] = 0 p += 1 end if nsym >= BLOCKSYMS - 2 then flush(p, p >= e) end end if nsym > 0 or blockStart < e then flush(e, true) elseif blockStart == e and o.op == 0 and o.cnt == 0 then put(o, 3, 3) put(o, 0, 7) end alignOut(o) local out = bcreate(o.op) bcopy(out, 0, o.buf, 0, o.op) return out end return Compress