ws-arch2-cab: codecs/compress/Quantum (CAB Quantum: 16-bit arithmetic decoder, the adaptive models with their rescale / re-sort rules, windows 2^10..2^21, one frame per CFDATA; written from the format descriptions) + cab Quantum folders, checked against cabextract on cabinets of a fixture Quantum compressor (tools/fixtures/_quantum.py) and libmspack's mszip_lzx_qtm sample
This commit is contained in:
1 parent
c54c8daff5
commit
9761df1af1
8 files changed
+486
-12
No files matched your search
+2
-1
@@ -70,7 +70,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| archive | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` |
|
||||
| archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` |
|
||||
| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` |
|
||||
| archive | cab | .cab | yes | yes | methods: "store", "mszip", "lzx" | `tests/archive/cab.luau` |
|
||||
| archive | cab | .cab | yes | yes | methods: "store", "mszip", "lzx", "quantum" | `tests/archive/cab.luau` |
|
||||
| archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` |
|
||||
| archive | d64 | .d64 .d71 .d81 | yes | yes | variants: "d64", "d71", "d81" | `tests/archive/d64.luau` |
|
||||
| archive | fat | .img .ima .vfd .flp .fat | yes | yes | variants: "fat12", "fat16", "fat32" | `tests/archive/fat.luau` |
|
||||
@@ -142,6 +142,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
|
||||
- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
|
||||
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
|
||||
- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft
|
||||
- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
|
||||
- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
|
||||
- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
|
||||
|
||||
@@ -800,8 +800,8 @@ local list: { Entry } = {
|
||||
path = "archive/cab",
|
||||
extensions = { "cab" },
|
||||
mime = { "application/vnd.ms-cab-compressed" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx" } },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } },
|
||||
load = function()
|
||||
return require("@formats/archive/cab")
|
||||
end,
|
||||
|
||||
@@ -15,6 +15,7 @@ local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Lzx = require("@formats/codecs/compress/Lzx")
|
||||
local Quantum = require("@formats/codecs/compress/Quantum")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Sum = require("@formats/archive/cab/Sum")
|
||||
|
||||
@@ -24,8 +25,8 @@ local Cab = {
|
||||
category = "archive",
|
||||
extensions = { "cab" },
|
||||
mime = { "application/vnd.ms-cab-compressed" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx" } },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
@@ -131,6 +132,12 @@ local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: n
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
return res, nil
|
||||
elseif method == 2 then
|
||||
local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31))
|
||||
if not res then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
return res, nil
|
||||
end
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method)
|
||||
end
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
--!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
|
||||
@@ -3,7 +3,8 @@
|
||||
-- files cabextract extracts (names, sizes, data CRCs, DOS times read as UTC); cabextract / gcab / 7z extract our
|
||||
-- writer's output (fixture step) and it round-trips; spanned files are UNSUPPORTED; checksum, truncation and
|
||||
-- signature errors, libmspack's broken cabinets; LZX (codecs/compress/Lzx) from a fixture compressor whose cabinets
|
||||
-- cabextract extracts (windows 2^15 .. 2^21, verbatim / aligned / uncompressed blocks, E8); Deflate's preset
|
||||
-- cabextract extracts (windows 2^15 .. 2^21, verbatim / aligned / uncompressed blocks, E8); Quantum
|
||||
-- (codecs/compress/Quantum) the same way (windows 2^10 .. 2^21, model rescaling); Deflate's preset
|
||||
-- dictionary; the fuzz pass. Fixtures: tools/fixtures/cab.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
@@ -35,7 +36,7 @@ for _, c in Fx.cases do
|
||||
t:eq(F.detect(c.data), "cab", c.name .. ": detect")
|
||||
table.insert(samples, string.sub(c.data, 1, 4000))
|
||||
end
|
||||
t:check(methods.store and methods.mszip and methods.lzx, "covers store, mszip and lzx")
|
||||
t:check(methods.store and methods.mszip and methods.lzx and methods.quantum, "covers store, mszip, lzx and quantum")
|
||||
|
||||
-- attributes, UTF-8 names, reserve areas (the builder's two-folder cabinet)
|
||||
local two = assert(load(Fx.cases[5].data))
|
||||
@@ -98,6 +99,12 @@ t:check(not Lzx.decode(buffer.create(10), 0, 10, 100, 14), "LZX window 2^14 unsu
|
||||
t:check(not Lzx.decode(buffer.create(10), 0, 10, 100, 16), "LZX of zeros")
|
||||
t:check(not Lzx.decode(buffer.create(10), 4, 10, 100, 16), "LZX range past the end")
|
||||
|
||||
-- Quantum directly
|
||||
local Quantum = require("@formats/codecs/compress/Quantum")
|
||||
t:check(not Quantum.decode(buffer.create(10), {}, 0, 9), "Quantum window 2^9 unsupported")
|
||||
t:check(not Quantum.decode(buffer.create(10), { { at = 0, len = 10, size = 5 } }, 6, 16), "Quantum sizes must add up")
|
||||
t:check(not Quantum.decode(buffer.create(10), { { at = 4, len = 10, size = 5 } }, 5, 16), "Quantum range past the end")
|
||||
|
||||
-- Deflate's preset dictionary and MSZIP blocks
|
||||
local block1 = assert(Deflate.compress(string.rep("ab", 50)))
|
||||
local mszip = buffer.create(buffer.len(block1) + 2)
|
||||
|
||||
+3
-3
@@ -1177,12 +1177,12 @@ do
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ws-arch2 cabinets: LZX (codecs/compress/Lzx) and MSZIP folders of tools/fixtures/cab.py (MB/s of output; each run
|
||||
-- decodes the cabinet again, so the folder cache does not count)
|
||||
-- ws-arch2 cabinets: LZX (codecs/compress/Lzx), Quantum (codecs/compress/Quantum) and MSZIP folders of
|
||||
-- tools/fixtures/cab.py (MB/s of output; each run decodes the cabinet again, so the folder cache does not count)
|
||||
do
|
||||
local Cab = require("@formats/archive/cab")
|
||||
local CF = require("@tests/gen/cab")
|
||||
for _, kind in { "lzx", "mszip" } do
|
||||
for _, kind in { "lzx", "quantum", "mszip" } do
|
||||
local datas, total = {}, 0
|
||||
for _, c in CF.cases do
|
||||
local a = Cab.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
# A small Quantum compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes Quantum
|
||||
# cabinets, so the fixtures make them here and cabextract (the reference) must extract them to the original bytes
|
||||
# before our decoder is compared with its output. Written from the format description (as codecs/compress/Quantum):
|
||||
# the same adaptive models, a 16-bit arithmetic encoder with underflow bits (Witten / Neal / Cleary style), position /
|
||||
# length footers as raw bits placed where the decoder (16 code bits ahead) reads them, one frame per 32 KB block.
|
||||
FRAME = 32768
|
||||
PEXTRA = [0 if i < 4 else i // 2 - 1 for i in range(42)]
|
||||
PBASE = []
|
||||
_b = 0
|
||||
for _e in PEXTRA:
|
||||
PBASE.append(_b)
|
||||
_b += 1 << _e
|
||||
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]
|
||||
LBASE = []
|
||||
_b = 0
|
||||
for _e in LEXTRA:
|
||||
LBASE.append(_b)
|
||||
_b += 1 << _e
|
||||
|
||||
|
||||
class Model:
|
||||
def __init__(self, first, n):
|
||||
self.n = n
|
||||
self.sym = [first + i for i in range(n)]
|
||||
self.cum = [n - i for i in range(n)] + [0]
|
||||
self.shifts = 4
|
||||
|
||||
def update(self, i):
|
||||
"""after coding sym[i] (0-based)"""
|
||||
for k in range(i + 1):
|
||||
self.cum[k] += 8
|
||||
if self.cum[0] > 3800:
|
||||
self.rescale()
|
||||
|
||||
def rescale(self):
|
||||
n, cum, sym = self.n, self.cum, self.sym
|
||||
self.shifts -= 1
|
||||
if self.shifts:
|
||||
for i in range(n - 1, -1, -1):
|
||||
cum[i] >>= 1
|
||||
if cum[i] <= cum[i + 1]:
|
||||
cum[i] = cum[i + 1] + 1
|
||||
return
|
||||
self.shifts = 50
|
||||
for i in range(n):
|
||||
cum[i] = (cum[i] - cum[i + 1] + 1) >> 1
|
||||
for i in range(n - 1):
|
||||
for j in range(i + 1, n):
|
||||
if cum[i] < cum[j]:
|
||||
cum[i], cum[j] = cum[j], cum[i]
|
||||
sym[i], sym[j] = sym[j], sym[i]
|
||||
for i in range(n - 1, -1, -1):
|
||||
cum[i] += cum[i + 1]
|
||||
|
||||
|
||||
class Encoder:
|
||||
"""one frame: code bits (by shift position) and raw bit runs to insert at code positions"""
|
||||
|
||||
def __init__(self):
|
||||
self.H, self.L = 0xFFFF, 0
|
||||
self.code = []
|
||||
self.pending = 0
|
||||
self.shifts = 0
|
||||
self.raws = [] # (code position, value, nbits)
|
||||
|
||||
def emit(self, b):
|
||||
self.code.append(b)
|
||||
self.code.extend([1 - b] * self.pending)
|
||||
self.pending = 0
|
||||
|
||||
def encode(self, m, s):
|
||||
i = m.sym.index(s)
|
||||
rng = self.H - self.L + 1
|
||||
tot = m.cum[0]
|
||||
self.H = self.L + (m.cum[i] * rng) // tot - 1
|
||||
self.L = self.L + (m.cum[i + 1] * rng) // tot
|
||||
m.update(i)
|
||||
while True:
|
||||
if (self.L ^ self.H) & 0x8000 == 0:
|
||||
self.emit(self.H >> 15)
|
||||
elif (self.L & 0x4000) and not (self.H & 0x4000):
|
||||
self.pending += 1
|
||||
self.L &= 0x3FFF
|
||||
self.H |= 0x4000
|
||||
else:
|
||||
break
|
||||
self.L = (self.L << 1) & 0xFFFF
|
||||
self.H = ((self.H << 1) & 0xFFFF) | 1
|
||||
self.shifts += 1
|
||||
|
||||
def raw(self, v, n):
|
||||
if n:
|
||||
self.raws.append((16 + self.shifts, v, n))
|
||||
|
||||
def finish(self):
|
||||
"""the frame's bytes: flushed code with the raw runs merged in, zero padded"""
|
||||
self.pending += 1
|
||||
self.emit(0 if self.L < 0x4000 else 1)
|
||||
need = 16 + self.shifts
|
||||
code = self.code + [0] * max(0, need - len(self.code))
|
||||
bits = []
|
||||
p = 0
|
||||
for at, v, n in self.raws:
|
||||
bits.extend(code[p:at])
|
||||
p = at
|
||||
bits.extend((v >> (n - 1 - k)) & 1 for k in range(n))
|
||||
bits.extend(code[p:])
|
||||
bits.extend([0] * (-len(bits) % 8 + 16)) # byte padding and 2 zero bytes: the decoder's lookahead stays inside
|
||||
return bytes(int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8))
|
||||
|
||||
|
||||
def slot_of(off1):
|
||||
s = 0
|
||||
while s + 1 < len(PBASE) and PBASE[s + 1] <= off1:
|
||||
s += 1
|
||||
return s
|
||||
|
||||
|
||||
def compress(data, wbits=16, maxchain=24):
|
||||
"""data -> [frame bytes] (one per 32 KB block)"""
|
||||
window = 1 << wbits
|
||||
slots = wbits * 2
|
||||
sel = Model(0, 7)
|
||||
lit = [Model(0, 64), Model(64, 64), Model(128, 64), Model(192, 64)]
|
||||
m3, m4, m5, mlen = Model(0, min(slots, 24)), Model(0, min(slots, 36)), Model(0, slots), Model(0, 27)
|
||||
lim3, lim4 = PBASE[m3.n - 1] + (1 << PEXTRA[m3.n - 1]), PBASE[m4.n - 1] + (1 << PEXTRA[m4.n - 1])
|
||||
limw = min(window, PBASE[slots - 1] + (1 << PEXTRA[slots - 1]))
|
||||
head, prev = {}, {}
|
||||
frames = []
|
||||
p = 0
|
||||
|
||||
def insert(q):
|
||||
if q + 3 <= len(data):
|
||||
k = data[q:q + 3]
|
||||
prev[q] = head.get(k)
|
||||
head[k] = q
|
||||
while p < len(data):
|
||||
end = min(len(data), p + FRAME)
|
||||
enc = Encoder()
|
||||
while p < end:
|
||||
limit = min(259, end - p)
|
||||
best, boff = 0, 0
|
||||
if limit >= 3:
|
||||
q = head.get(data[p:p + 3])
|
||||
chain = 0
|
||||
while q is not None and chain < maxchain and p - q <= limw:
|
||||
l = 0
|
||||
while l < limit and data[q + l] == data[p + l]:
|
||||
l += 1
|
||||
o = p - q
|
||||
ok = l >= 5 or (l == 4 and o <= lim4) or (l == 3 and o <= lim3)
|
||||
if ok and l > best:
|
||||
best, boff = l, o
|
||||
q = prev.get(q)
|
||||
chain += 1
|
||||
if best >= 3:
|
||||
o1 = boff - 1
|
||||
s = slot_of(o1)
|
||||
if best == 3:
|
||||
enc.encode(sel, 4)
|
||||
enc.encode(m3, s)
|
||||
elif best == 4:
|
||||
enc.encode(sel, 5)
|
||||
enc.encode(m4, s)
|
||||
else:
|
||||
l5 = best - 5
|
||||
ls = max(i for i in range(27) if LBASE[i] <= l5)
|
||||
enc.encode(sel, 6)
|
||||
enc.encode(mlen, ls)
|
||||
enc.raw(l5 - LBASE[ls], LEXTRA[ls])
|
||||
enc.encode(m5, s)
|
||||
enc.raw(o1 - PBASE[s], PEXTRA[s])
|
||||
for k in range(best):
|
||||
insert(p + k)
|
||||
p += best
|
||||
else:
|
||||
b = data[p]
|
||||
enc.encode(sel, b >> 6)
|
||||
enc.encode(lit[b >> 6], b)
|
||||
insert(p)
|
||||
p += 1
|
||||
frames.append(enc.finish())
|
||||
return frames
|
||||
+27
-2
@@ -14,8 +14,11 @@ _s.loader.exec_module(A)
|
||||
_s = importlib.util.spec_from_file_location("_lzx", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_lzx.py"))
|
||||
L = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(L)
|
||||
_s = importlib.util.spec_from_file_location("_quantum", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_quantum.py"))
|
||||
Q = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(Q)
|
||||
|
||||
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py"]
|
||||
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py", "tools/fixtures/_quantum.py"]
|
||||
ENV = dict(os.environ, TZ="UTC")
|
||||
|
||||
|
||||
@@ -99,6 +102,13 @@ def lzx(wbits, e8size=0, seed=1, plan=None):
|
||||
return enc
|
||||
|
||||
|
||||
def quantum(wbits):
|
||||
def enc(stream):
|
||||
frames = Q.compress(stream, wbits)
|
||||
return [(f, min(32768, len(stream) - i * 32768)) for i, f in enumerate(frames)]
|
||||
return enc
|
||||
|
||||
|
||||
LIST = re.compile(r"^\s*(\d+) \| (\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d):(\d\d) \| (.*)$")
|
||||
|
||||
|
||||
@@ -185,13 +195,28 @@ def generate(ctx):
|
||||
if {e["name"]: e["crc"] for e in ents} != want:
|
||||
raise RuntimeError("cabextract does not extract the fixture LZX cabinet " + label)
|
||||
cases.append({"name": label, "data": c, "entries": ents})
|
||||
# Quantum (our fixture compressor, checked by cabextract): windows 2^10 .. 2^21, model rescaling and re-sorting
|
||||
quantum_cases = [
|
||||
("quantum 2^10 text", 10, [(b"q.txt", text[:20000])]),
|
||||
("quantum 2^16 mixed", 16, [(b"a.txt", text[:60000]), (b"b.bin", rand[:20000]), (b"c.bin", x86[:30000])]),
|
||||
("quantum 2^21 big", 21, [(b"big.bin", big)]),
|
||||
]
|
||||
for i, (label, wb, fl) in enumerate(quantum_cases):
|
||||
c = build([(2 | (4 << 4) | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], quantum(wb))])
|
||||
p = os.path.join(tmp, "qtm%d.cab" % i)
|
||||
open(p, "wb").write(c)
|
||||
ents = reference(p, tmp, "qtm%d" % i)
|
||||
want = {n.decode(): zlib.crc32(d) for n, d in fl}
|
||||
if {e["name"]: e["crc"] for e in ents} != want:
|
||||
raise RuntimeError("cabextract does not extract the fixture Quantum cabinet " + label)
|
||||
cases.append({"name": label, "data": c, "entries": ents})
|
||||
# the libmspack test cabinets
|
||||
ms = os.path.join(tmp, "ms")
|
||||
os.makedirs(ms)
|
||||
subprocess.run(["tar", "xzf", mspack_cabs(), "-C", ms, "--wildcards", "*/test/test_files/cabd/*.cab"], check=True)
|
||||
cabd = os.path.join(ms, os.listdir(ms)[0], "test", "test_files", "cabd")
|
||||
for n in ("normal_2files_1folder", "normal_2files_2folders", "normal_255c_filename", "reserve_---", "reserve_--D",
|
||||
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD"):
|
||||
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD", "mszip_lzx_qtm"):
|
||||
add("libmspack " + n, os.path.join(cabd, n + ".cab"))
|
||||
spanned = [{"name": n, "data": open(os.path.join(cabd, n + ".cab"), "rb").read()}
|
||||
for n in ("multi_basic_pt1", "multi_basic_pt2", "multi_basic_pt3")]
|
||||
|
||||
Reference in new issue
Block a user