--!strict --!native --!optimize 2 -- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft -- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with -- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the -- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the -- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and -- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the -- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the -- models and the window persist across the frames of a folder. Written from the public descriptions of the format -- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. -- -- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message -- -- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is -- their total. Never throws: bad or truncated data returns nil, message. local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, writeu8 = buffer.readu8, buffer.writeu8 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local floor = math.floor local Quantum = {} -- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer) local PBASE = table.create(42, 0) local PEXTRA = table.create(42, 0) do local b = 0 for i = 0, 41 do local e = if i < 4 then 0 else i // 2 - 1 PEXTRA[i + 1] = e PBASE[i + 1] = b b += lshift(1, e) end end local LEXTRA = { 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 } local LBASE = table.create(27, 0) do local b = 0 for i = 1, 27 do LBASE[i] = b b += lshift(1, LEXTRA[i]) end end -- ------------------------------------------------------------------------------------------------ models -- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) type Model = { n: number, sym: { number }, cum: { number }, shifts: number } local function model(first: number, n: number): Model local sym = table.create(n, 0) local cum = table.create(n + 1, 0) for i = 1, n do sym[i] = first + i - 1 cum[i] = n - i + 1 end cum[n + 1] = 0 return { n = n, sym = sym, cum = cum, shifts = 4 } end local function rescale(m: Model) local n, sym, cum = m.n, m.sym, m.cum m.shifts -= 1 if m.shifts > 0 then for i = n, 1, -1 do local c = rshift(cum[i], 1) if c <= cum[i + 1] then c = cum[i + 1] + 1 end cum[i] = c end return end m.shifts = 50 -- cumulative -> halved frequencies (rounded up: no symbol drops to zero) for i = 1, n do cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1) end -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's) for i = 1, n - 1 do for j = i + 1, n do if cum[i] < cum[j] then cum[i], cum[j] = cum[j], cum[i] sym[i], sym[j] = sym[j], sym[i] end end end for i = n, 1, -1 do cum[i] += cum[i + 1] end end -- ------------------------------------------------------------------------------------------------ decode -- the coder and bit reader of one frame type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } local function bit(c: Coder): number if c.cnt == 0 then local p = c.pos if p < c.stop then c.acc = readu8(c.src, p) c.pos = p + 1 else c.acc = 0 c.over += 1 end c.cnt = 8 end c.cnt -= 1 return band(rshift(c.acc, c.cnt), 1) end -- raw(c, n) -> the next n (0..19) bits, most significant first local function raw(c: Coder, n: number): number local v = 0 for _ = 1, n do v = v * 2 + bit(c) end return v end local function symbol(c: Coder, m: Model): number local cum = m.cum local H, L, C = c.H, c.L, c.C local range = H - L + 1 local total = cum[1] if range <= 0 or C < L or C > H then -- only corrupt registers get here (the decoder keeps L <= C <= H) c.bad = true return 0 end local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF) local n = m.n local i = 2 while i <= n and cum[i] > f do i += 1 end -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1]) local s = m.sym[i - 1] H = L + floor(cum[i - 1] * range / total) - 1 L = L + floor(cum[i] * range / total) for k = 1, i - 1 do cum[k] += 8 end if cum[1] > 3800 then rescale(m) end while true do if band(bxor(L, H), 0x8000) ~= 0 then if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then -- underflow: L and H straddle the middle C = bxor(C, 0x4000) L = band(L, 0x3FFF) H = bor(H, 0x4000) else break end end L = band(lshift(L, 1), 0xFFFF) H = bor(band(lshift(H, 1), 0xFFFF), 1) C = bor(band(lshift(C, 1), 0xFFFF), bit(c)) end c.H, c.L, c.C = H, L, C return s end function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) end if outSize < 0 or outSize % 1 ~= 0 then return nil, "bad output size" end local total = 0 for _, b in blocks do if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then return nil, "bad block range" end total += b.size end if total ~= outSize then return nil, "block sizes do not add up to the output size" end local window = lshift(1, windowBits) local slots = windowBits * 2 local selector = model(0, 7) local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) } local m3 = model(0, math.min(slots, 24)) local m4 = model(0, math.min(slots, 36)) local m5 = model(0, slots) local mlen = model(0, 27) local out = bcreate(outSize) local op = 0 for _, b in blocks do local frameEnd = op + b.size local c: Coder = { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false } c.C = raw(c, 16) while op < frameEnd do local sel = symbol(c, selector) if c.bad then return nil, "bad arithmetic code" end if sel < 4 then writeu8(out, op, symbol(c, lit[sel + 1])) op += 1 else local len, slot if sel == 4 then len = 3 slot = symbol(c, m3) elseif sel == 5 then len = 4 slot = symbol(c, m4) elseif sel == 6 then local ls = symbol(c, mlen) len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5 slot = symbol(c, m5) else return nil, "bad selector" end local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1 if dist > op or dist > window then return nil, "match offset before the start of the data" end if op + len > frameEnd then return nil, "match past the end of its frame" end local from = op - dist if dist >= len then bcopy(out, op, out, from, len) else for k = 0, len - 1 do writeu8(out, op + k, readu8(out, from + k)) end end op += len end if c.bad then return nil, "bad arithmetic code" end if c.over > 4 then return nil, "truncated frame" end end end return out, nil end return Quantum