ws-arch2-cab: codecs/compress/Lzx (CAB LZX: windows 2^15..2^21, verbatim / aligned / uncompressed blocks, delta-coded trees, R0..R2, E8 translation, 32 KB frames; written from the spec) + cab LZX folders, checked against cabextract on cabinets of a fixture LZX compressor (tools/fixtures/_lzx.py) and libmspack's samples; Deflate.mszip (generic MSZIP blocks: CK + deflate, dictionary carried across blocks; for cab and later model/x); cab bench lines

This commit is contained in:
4DBug committed 2026-10-31 15:46:28 -05:00
1 parent 825c45b03c
commit c54c8daff5
9 files changed
+990 -49

No files matched your search

+27 -1
View File
@@ -2,7 +2,7 @@
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), .Z (tools/fixtures/z.py), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
-- (glyphs per second), cab (LZX / MSZIP / Quantum), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
@@ -1177,6 +1177,32 @@ 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)
do
local Cab = require("@formats/archive/cab")
local CF = require("@tests/gen/cab")
for _, kind in { "lzx", "mszip" } do
local datas, total = {}, 0
for _, c in CF.cases do
local a = Cab.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
if a and a.meta.folders[1].method == kind and #c.data > 20000 then
table.insert(datas, buffer.fromstring(c.data))
for _, e in a:list() do
total += e.size
end
end
end
bench("cab " .. kind .. " (" .. #datas .. " cabinets)", 5, total, function()
for _, d in datas do
local a = Cab.decode(Bytes.reader(d)) :: any
for _, e in a:list() do
a:read(e.name)
end
end
end)
end
end
do
-- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds)
-- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file
+351
View File
@@ -0,0 +1,351 @@
# A small LZX compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes LZX 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 LZX format description (as codecs/compress/Lzx): verbatim, aligned
# offset and uncompressed blocks of chosen sizes (spanning frames), delta-coded trees with pre-tree runs, repeated
# offsets, the E8 translation, 32 KB frames aligned to 16 bits. Hash-chain matching; not tuned for ratio or speed.
import heapq, random, struct
FRAME = 32768
SLOTS = {15: 30, 16: 32, 17: 34, 18: 36, 19: 38, 20: 42, 21: 50}
EXTRA = [0 if i < 4 else min(i // 2 - 1, 17) for i in range(51)]
BASE = []
_b = 0
for _e in EXTRA:
BASE.append(_b)
_b += 1 << _e
def slot_of(fo):
s = 0
while s + 1 < len(BASE) and BASE[s + 1] <= fo:
s += 1
return s
def lengths(freqs, maxlen):
"""length-limited Huffman code lengths (halving the frequencies until the code fits); every tree complete"""
f = list(freqs)
used = [i for i, x in enumerate(f) if x > 0]
while len(used) < 2: # a complete code needs two symbols
i = next(i for i in range(len(f)) if f[i] == 0)
f[i] = 1
used.append(i)
while True:
heap = [(f[i], i, (i,)) for i in used]
heapq.heapify(heap)
depth = {i: 0 for i in used}
k = len(f)
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
for s in a[2] + b[2]:
depth[s] += 1
heapq.heappush(heap, (a[0] + b[0], k, a[2] + b[2]))
k += 1
if max(depth.values()) <= maxlen:
out = [0] * len(f)
for s, d in depth.items():
out[s] = d
return out
f = [(x + 1) // 2 if x else 0 for x in f]
def codes(lens):
"""canonical codes (MSB first)"""
out = [0] * len(lens)
code = 0
for l in range(1, 17):
for s, x in enumerate(lens):
if x == l:
out[s] = code
code += 1
code <<= 1
return out
class Bits:
def __init__(self):
self.out = bytearray()
self.acc = 0
self.n = 0
def put(self, v, n):
for i in range(n - 1, -1, -1):
self.acc = (self.acc << 1) | ((v >> i) & 1)
self.n += 1
if self.n == 16:
self.out += struct.pack("<H", self.acc)
self.acc, self.n = 0, 0
def align(self):
if self.n:
self.put(0, 16 - self.n)
def aligned(self):
return self.n == 0
def e8(data, size):
"""the encoder's E8 translation (relative call targets to absolute), frame by frame"""
d = bytearray(data)
for base in range(0, min(len(d), FRAME * 32768), FRAME):
fs = min(FRAME, len(d) - base)
i, stop = base, base + fs - 10
while i < stop:
if d[i] == 0xE8:
rel = struct.unpack_from("<i", d, i + 1)[0]
if -i <= rel < size:
struct.pack_into("<i", d, i + 1, rel + i if rel < size - i else rel - size)
i += 5
else:
i += 1
return bytes(d)
def tokens(data, start, end, window, reps, rng, maxchain=24):
"""LZ77 tokens of data[start:end) (literal ints, or (length, offset)); matches stay inside the 32 KB frame"""
out = []
head = {}
prev = {}
def insert(p):
if p + 3 <= len(data):
k = data[p:p + 3]
prev[p] = head.get(k)
head[k] = p
for p in range(max(0, start - 4096), start):
insert(p)
p = start
r = list(reps)
while p < end:
limit = min(257, end - p, (p // FRAME + 1) * FRAME - p)
best, boff = 0, 0
if limit >= 2:
for o in r: # repeated offsets first
if o <= p:
l = 0
while l < limit and data[p + l] == data[p + l - o]:
l += 1
if l > best:
best, boff = l, o
if limit >= 3:
q = head.get(data[p:p + 3])
chain = 0
while q is not None and chain < maxchain and p - q <= window - 3:
l = 0
while l < limit and data[q + l] == data[p + l]:
l += 1
if l > best + 1:
best, boff = l, p - q
q = prev.get(q)
chain += 1
if best >= 3 or (best == 2 and boff in r):
out.append((best, boff))
if boff == r[0]:
pass
elif boff == r[1]:
r[0], r[1] = r[1], r[0]
elif boff == r[2]:
r[0], r[2] = r[2], r[0]
else:
r = [boff, r[0], r[1]]
for k in range(best):
insert(p + k)
p += best
else:
out.append(data[p])
insert(p)
p += 1
return out, r
class Tree:
"""code lengths persisting across blocks (the deltas' base)"""
def __init__(self, n):
self.lens = [0] * n
def pretree_items(prev, new, rng, runs):
"""the pre-tree symbols ((sym, extra bits, nbits) or (19, ...)) that turn prev into new"""
items = []
x = 0
n = len(new)
while x < n:
if runs and new[x] == 0:
r = 0
while x + r < n and new[x + r] == 0:
r += 1
if r >= 20:
r = min(r, 51)
items.append((18, r - 20, 5, None))
x += r
continue
if r >= 4:
r = min(r, 19)
items.append((17, r - 4, 4, None))
x += r
continue
if runs:
r = 0
while x + r < n and new[x + r] == new[x]:
r += 1
if r >= 4:
r = min(r, 5)
items.append((19, r - 4, 1, (prev[x] - new[x]) % 17))
x += r
continue
items.append(((prev[x] - new[x]) % 17, 0, 0, None))
x += 1
return items
def write_tree(bits, tree, first, last, new, rng):
items = pretree_items(tree.lens[first:last], new, rng, runs=rng.random() < 0.9)
freq = [0] * 20
for s, _, _, d in items:
freq[s] += 1
if d is not None:
freq[d] += 1
pl = lengths(freq, 15)
pc = codes(pl)
for l in pl:
bits.put(l, 4)
for s, ex, nb, d in items:
bits.put(pc[s], pl[s])
if nb:
bits.put(ex, nb)
if d is not None:
bits.put(pc[d], pl[d])
tree.lens[first:last] = new
def compress(data, wbits=16, e8size=0, seed=1, plan=None):
"""data -> (LZX stream bytes, [compressed bytes per 32 KB frame]); plan: [(block type 1..3, size)] (default:
random sizes and types)"""
rng = random.Random(seed)
window = 1 << wbits
nslots = SLOTS[wbits]
src = e8(data, e8size) if e8size else bytes(data)
if plan is None:
plan = []
left = len(src)
while left > 0:
n = min(left, rng.choice([5000, 20000, 32768, 45000, 70000, 100000]))
plan.append((rng.choice([1, 1, 2, 2, 3]) if n > 100 else 1, n))
left -= n
bits = Bits()
frames = []
frame_start = 0
main = Tree(256 + 8 * nslots)
length = Tree(249)
reps = [1, 1, 1]
pos = 0
first = True
def frame_end_check(p):
nonlocal frame_start
if p % FRAME == 0 or p == len(src):
bits.align()
frames.append(len(bits.out) - frame_start)
frame_start = len(bits.out)
for btype, size in plan:
if first:
if e8size:
bits.put(1, 1)
bits.put(e8size >> 16, 16)
bits.put(e8size & 0xFFFF, 16)
else:
bits.put(0, 1)
first = False
bits.put(btype, 3)
bits.put(size >> 8, 16)
bits.put(size & 0xFF, 8)
end = pos + size
if btype == 3:
if bits.aligned():
bits.put(0, 16)
bits.align()
for r in reps:
bits.out += struct.pack("<I", r)
while pos < end:
n = min(end, (pos // FRAME + 1) * FRAME) - pos
bits.out += src[pos:pos + n]
pos += n
frame_end_check(pos)
if size & 1:
bits.out += b"\0"
if pos % FRAME == 0 or pos == len(src): # the pad byte belongs to the frame just closed
frames[-1] += 1
frame_start += 1
continue
toks, newreps = tokens(src, pos, end, window, reps, rng)
# symbols
mf = [0] * (256 + 8 * nslots)
lf = [0] * 249
af = [0] * 8
syms = []
r = list(reps)
for t in toks:
if isinstance(t, int):
mf[t] += 1
syms.append((t,))
continue
l, o = t
if o == r[0]:
slot = 0
elif o == r[1]:
slot = 1
r[0], r[1] = r[1], r[0]
elif o == r[2]:
slot = 2
r[0], r[2] = r[2], r[0]
else:
slot = slot_of(o + 2)
r = [o, r[0], r[1]]
hdr = min(l - 2, 7)
m = 256 + slot * 8 + hdr
mf[m] += 1
ls = l - 2 - 7 if hdr == 7 else None
if ls is not None:
lf[ls] += 1
foot = None
if slot >= 3:
foot = o + 2 - BASE[slot]
if btype == 2 and EXTRA[slot] >= 3:
af[foot & 7] += 1
syms.append((m, ls, slot, foot))
assert r == newreps
reps = newreps
if btype == 2:
al = lengths(af, 7)
for x in al:
bits.put(x, 3)
ac = codes(al)
ml = lengths(mf, 16)
ll = lengths(lf, 16) if any(lf) or rng.random() < 0.5 else [0] * 249
write_tree(bits, main, 0, 256, ml[:256], rng)
write_tree(bits, main, 256, len(ml), ml[256:], rng)
write_tree(bits, length, 0, 249, ll, rng)
mc, lc = codes(ml), codes(ll)
for t, s in zip(toks, syms):
m = s[0]
bits.put(mc[m], ml[m])
if m < 256:
pos += 1
else:
_, ls, slot, foot = s
if ls is not None:
bits.put(lc[ls], ll[ls])
if slot >= 3:
ex = EXTRA[slot]
if btype == 2 and ex >= 3:
if ex > 3:
bits.put(foot >> 3, ex - 3)
bits.put(ac[foot & 7], al[foot & 7])
elif ex:
bits.put(foot, ex)
pos += t[0]
frame_end_check(pos)
return bytes(bits.out), frames
+58 -17
View File
@@ -5,14 +5,17 @@
# is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); cabextract, gcab and 7z must extract
# our writer's cabinets to the same bytes.
# tests/gen/cab.luau { cases = { { name, data, entries = { { name, size, crc, mtime } } } }, ours = { ok, log },
# spanned = { { name, data } } }
# spanned = { { name, data } }, bad = { { name, data } } }
import calendar, importlib.util, os, re, struct, subprocess, time, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_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)
INPUTS = ["tools/fixtures/_arch2.py"]
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py"]
ENV = dict(os.environ, TZ="UTC")
@@ -34,7 +37,7 @@ def dos(t):
def build(folders, reserve=None):
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(blockdata, previous) -> payload)];
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(stream) -> [(payload, size)])];
reserve = (header bytes, folder size, data size)"""
hres, fres, dres = reserve or (b"", 0, 0)
flags = 4 if reserve else 0
@@ -50,13 +53,7 @@ def build(folders, reserve=None):
files += struct.pack("<IIHHHH", len(data), off, fi, d, t, attr) + name + b"\0"
off += len(data)
stream += data
out = []
prev = b""
for s in range(0, len(stream), 32768):
chunk = stream[s:s + 32768]
out.append((enc(chunk, prev), len(chunk)))
prev = chunk
blocks.append(out)
blocks.append(enc(stream))
coff = head + len(folders) * (8 + fres)
dat = coff + len(files)
folder_tab = b""
@@ -73,13 +70,33 @@ def build(folders, reserve=None):
return hdr + folder_tab + files + data
def store(chunk, prev):
return chunk
def chunks(stream):
return [stream[s:s + 32768] for s in range(0, len(stream), 32768)]
def mszip_dict(chunk, prev):
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
return b"CK" + c.compress(chunk) + c.flush()
def store(stream):
return [(c, len(c)) for c in chunks(stream)]
def mszip_dict(stream):
out, prev = [], b""
for chunk in chunks(stream):
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
out.append((b"CK" + c.compress(chunk) + c.flush(), len(chunk)))
prev = chunk
return out
def lzx(wbits, e8size=0, seed=1, plan=None):
def enc(stream):
data, frames = L.compress(stream, wbits, e8size, seed, plan)
out, p = [], 0
for i, n in enumerate(frames):
out.append((data[p:p + n], min(32768, len(stream) - i * 32768)))
p += n
assert p == len(data)
return out
return enc
LIST = re.compile(r"^\s*(\d+) \| (\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d):(\d\d) \| (.*)$")
@@ -147,16 +164,40 @@ def generate(ctx):
open(p, "wb").write(c)
A.tool(["cabextract"], ["cabextract", "-t", p]) # checksums and data as cabextract reads them
add(("mszip with dictionary", "two folders, reserve, utf-8")[i], p)
# LZX (our fixture compressor, checked by cabextract): windows 2^15 .. 2^21, the three block types, E8
x86 = bytearray(rng.randbytes(90000))
for i in range(0, len(x86) - 5, 23):
x86[i] = 0xE8
x86 = bytes(x86) + text[:40000]
lzx_cases = [
("lzx 2^15 text", 15, 0, [(b"t.txt", text[:100000])], None),
("lzx 2^16 mixed", 16, 0, [(b"a.txt", text), (b"b.bin", rand[:30000]), (b"c.txt", text[:5000])], None),
("lzx 2^17 types", 17, 0, [(b"m.bin", big)], [(1, 40000), (2, 30001), (3, 7777), (2, 50000), (3, 4), (1, len(big) - 127782)]),
("lzx 2^21 e8", 21, 12000000, [(b"x86.exe", x86), (b"tail.txt", text[:3000])], None),
("lzx 2^18 e8 small", 18, 70000, [(b"s.bin", x86[:20000])], [(2, 20000)]),
]
for i, (label, wb, e8size, fl, plan) in enumerate(lzx_cases):
c = build([(3 | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], lzx(wb, e8size, 100 + i, plan))])
p = os.path.join(tmp, "lzx%d.cab" % i)
open(p, "wb").write(c)
ents = reference(p, tmp, "lzx%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 LZX 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_255c_filename", "reserve_---", "reserve_--D",
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"):
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")]
# broken cabinets cabextract fails on (crafted bad trees, loops, short headers / strings)
bad = [{"name": n, "data": open(os.path.join(cabd, n), "rb").read()} for n in sorted(os.listdir(cabd))
if n.endswith(".cab") and (n.startswith(("partial_", "bad_", "lzx-")) or (n.startswith("cve-") and "9732" not in n))]
# our writer, extracted by the reference tools
log, ok = [], True
for opts in ("compression=mszip", "compression=none", "compression=mszip,level=1"):
@@ -174,6 +215,6 @@ def generate(ctx):
good = r.returncode == 0 and got == want
ok = ok and good
log.append("%s %s: %s" % (opts, tool, "ok" if good else "FAILED %r" % (got,)))
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned})
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned, "bad": bad})
finally:
A.rmtree(tmp)