--!strict --!native -- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. -- -- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: -- entry = symbol * 32 + length a code of `length` <= P bits -- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) -- entry = 0 no code (incomplete code set): the stream is corrupt -- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables -- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. -- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a -- core/Bits reader. -- -- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. -- Never throws: bad code sets return -1 / nil. local Bits = require("@formats/core/Bits") local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local bfill = buffer.fill local MAXLEN = 16 local Huffman = {} Huffman.MAXLEN = MAXLEN -- 8-bit reversal local REV = table.create(256, 0) for i = 0, 255 do local r, v = 0, i for _ = 1, 8 do r = r * 2 + v % 2 v = v // 2 end REV[i + 1] = r end -- reverse(code, len) -> the low len bits of code reversed (len <= 16) local function reverse(code: number, len: number): number return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) end Huffman.reverse = reverse -- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen function Huffman.capacity(nsym: number, P: number, maxLen: number): number return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) end local count = table.create(MAXLEN + 1, 0) local nextc = table.create(MAXLEN + 1, 0) local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number for i = 1, MAXLEN + 1 do count[i] = 0 end for s = 0, n - 1 do local l = readu8(lens, off + s) if l > MAXLEN then return -1 end count[l + 1] += 1 end count[1] = 0 local left = 1 local maxLen = 0 for l = 1, MAXLEN do left = left * 2 - count[l + 1] if left < 0 then return -1 end if count[l + 1] > 0 then maxLen = l end end local code = 0 for l = 1, MAXLEN do code = (code + count[l]) * 2 nextc[l] = code end local psize = lshift(1, P) bfill(tab, 0, 0, psize * 4) local S = if maxLen > P then maxLen - P else 0 local ssize = lshift(1, S) local nextSub = psize for s = 0, n - 1 do local l = readu8(lens, off + s) if l > 0 then local c = nextc[l] nextc[l] = c + 1 local entry = s * 32 + l if l <= P then if msb then -- the code is the top l bits of the P-bit index: fill every completion of the low bits local first = lshift(c, P - l) local last = first + lshift(1, P - l) - 1 for i = first, last do writeu32(tab, i * 4, entry) end else local step = lshift(1, l) local i = reverse(c, l) while i < psize do writeu32(tab, i * 4, entry) i += step end end else local pre, rest if msb then pre = rshift(c, l - P) rest = band(c, lshift(1, l - P) - 1) else local rev = reverse(c, l) pre = band(rev, psize - 1) rest = rshift(rev, P) end local e = readu32(tab, pre * 4) local sub if e == 0 then sub = nextSub nextSub += ssize bfill(tab, sub * 4, 0, ssize * 4) writeu32(tab, pre * 4, sub * 32) else sub = rshift(e, 5) end local k = l - P -- bits of the code in the subtable index if msb then local first = lshift(rest, S - k) for i = first, first + lshift(1, S - k) - 1 do writeu32(tab, (sub + i) * 4, entry) end else local step = lshift(1, k) local i = rest while i < ssize do writeu32(tab, (sub + i) * 4, entry) i += step end end end end end return S end -- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next -- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an -- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, false) end -- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number return build(lens, off, n, tab, P, true) end -- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end local idx = br:peek(P + S) e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4) l = band(e, 31) if l == 0 then return -1 end end br:skip(l) return rshift(e, 5) end -- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number local e = readu32(tab, br:peek(P) * 4) local l = band(e, 31) if l == 0 then if e == 0 then return -1 end local idx = br:peek(P + S) e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) l = band(e, 31) if l == 0 then return -1 end end br:skip(l) return rshift(e, 5) end -- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). -- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. function Huffman.codes(lengths: { number }): { number } local cnt = table.create(MAXLEN + 1, 0) for _, l in lengths do if l > 0 then cnt[l + 1] += 1 end end local nxt = table.create(MAXLEN + 1, 0) local code = 0 for l = 1, MAXLEN do code = (code + cnt[l]) * 2 nxt[l + 1] = code end local out = table.create(#lengths, 0) for i, l in lengths do if l > 0 then out[i] = nxt[l + 1] nxt[l + 1] += 1 end end return out end -- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without -- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. function Huffman.lengths(freqs: { number }, maxLen: number): { number } local n = #freqs local out = table.create(n, 0) -- leaves sorted by frequency (ties by symbol, for determinism) local syms = {} for i = 1, n do if freqs[i] > 0 then table.insert(syms, i) end end if #syms == 0 then return out end if #syms == 1 then out[syms[1]] = 1 return out end table.sort(syms, function(a: number, b: number): boolean if freqs[a] ~= freqs[b] then return freqs[a] < freqs[b] end return a < b end) -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) local m = #syms local weight = table.create(2 * m, 0) local parent = table.create(2 * m, 0) for i = 1, m do weight[i] = freqs[syms[i]] end local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node local function take(): number if li <= m and (ni >= nn or weight[li] <= weight[ni]) then li += 1 return li - 1 end ni += 1 return ni - 1 end for _ = 1, m - 1 do local a = take() local b = take() weight[nn] = weight[a] + weight[b] parent[a] = nn parent[b] = nn nn += 1 end -- depths: the root is nn - 1 local depth = table.create(2 * m, 0) for i = nn - 2, 1, -1 do depth[i] = depth[parent[i]] + 1 end -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) local bl = table.create(m + maxLen + 2, 0) local deepest = 0 for i = 1, m do bl[depth[i]] += 1 deepest = math.max(deepest, depth[i]) end for l = deepest, maxLen + 1, -1 do while bl[l] > 0 do local j = l - 2 while j > 0 and bl[j] == 0 do j -= 1 end bl[l] -= 2 bl[l - 1] += 1 bl[j + 1] += 2 bl[j] -= 1 end end -- the longest codes go to the least frequent symbols (syms is sorted ascending) local k = 1 for l = math.min(deepest, maxLen), 1, -1 do for _ = 1, bl[l] do out[syms[k]] = l k += 1 end end return out end return Huffman