merge ws/arch2-cab (archive/cab; codecs/compress/Lzx, Quantum; Deflate preset dictionary + mszip)

This commit is contained in:
4DBug committed 2026-10-31 16:27:11 -05:00
commit 3e83879a6e
15 files changed
+2267 -5

No files matched your search

+12
View File
@@ -1082,6 +1082,18 @@ local list: { Entry } = {
return require("@formats/archive/bz2")
end,
},
{
name = "cab",
category = "archive",
path = "archive/cab",
extensions = { "cab" },
mime = { "application/vnd.ms-cab-compressed" },
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,
},
{
name = "cpio",
category = "archive",
+42
View File
@@ -0,0 +1,42 @@
--!strict
--!native
--!optimize 2
-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3
-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format
-- description ([MS-CAB] 2.4, CFDATA.csum).
local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len
local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift
local Sum = {}
-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum)
function Sum.of(buf: buffer, off: number, len: number, seed: number): number
if off < 0 or len <= 0 or off + len > blen(buf) then
return seed
end
local s = seed
local p = off
local stop = off + len - len % 4
while p < stop do
s = bxor(s, readu32(buf, p))
p += 4
end
local rem = len % 4
local tail = 0
if rem == 3 then
tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2))
elseif rem == 2 then
tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1))
elseif rem == 1 then
tail = readu8(buf, p)
end
return bxor(s, tail)
end
-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData)
function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number
return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536)
end
return Sum
+427
View File
@@ -0,0 +1,427 @@
--!strict
-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and
-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose
-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum
-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local
-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM)
-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same
-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the
-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a
-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one),
-- signed / self-extracting stubs before the header.
-- ------------------------------------------------------------------------------------------------ requires
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")
-- ------------------------------------------------------------------------------------------------ contract
local Cab = {
name = "cab",
category = "archive",
extensions = { "cab" },
mime = { "application/vnd.ms-cab-compressed" },
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 = {
maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30)
maxEntries: number?, -- default 65535
verify: boolean?, -- check the data block checksums (default true)
}
export type EncodeOptions = {
compression: ("mszip" | "none")?, -- default "mszip"
level: number?, -- deflate level 0..9 (default 6)
setId: number?, -- the cabinet set id (default 0)
}
-- ------------------------------------------------------------------------------------------------ constants
local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004
local ATTR_UTF8 = 0x80
local METHOD = { [0] = "store", "mszip", "quantum", "lzx" }
local BLOCK = 32768
-- ------------------------------------------------------------------------------------------------ sniff
function Cab.sniff(r: Bytes.Reader): number
if r:peek(8) == "MSCF\0\0\0\0" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Folder = {
dataAt: number, -- offset of the first CFDATA (relative to the reader)
blocks: number,
type: number, -- typeCompress
index: number,
}
type Block = { at: number, len: number, size: number }
-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next
-- cabinet (a block with cbUncomp 0)
local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?)
local list: { Block } = {}
local p = f.dataAt
local total = 0
for i = 1, f.blocks do
local h = r:sub(p, 8)
local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le()
if h.err then
return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p)
end
local at = p + 8 + dataReserve
if at + cbData > r:size() then
return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p)
end
if cbUncomp == 0 then
return list, total, true
end
if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then
return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p)
end
total += cbUncomp
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "folder larger than maxBytes")
end
table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp })
p = at + cbData
end
return list, total, false
end
-- the decompressed data of a folder's blocks
local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?)
local method = bit32.band(typ, 15)
local out = buffer.create(total)
if method == 0 then
local o = 0
for _, b in list do
if b.len ~= b.size then
return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at)
end
buffer.copy(out, o, buf, b.at, b.len)
o += b.len
end
return out, nil
elseif method == 1 then
local spans: { { offset: number, length: number, size: number } } = {}
for _, b in list do
table.insert(spans, { offset = b.at, length = b.len, size = b.size })
end
return Deflate.mszip(buf, spans)
elseif method == 3 then
local bits = bit32.band(bit32.rshift(typ, 8), 31)
local n = 0
for _, b in list do
n += b.len
end
local src = buffer.create(n)
local o = 0
for _, b in list do
buffer.copy(src, o, buf, b.at, b.len)
o += b.len
end
local res, err = Lzx.decode(src, 0, n, total, bits)
if not res then
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
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Cab.encode(archive, opts)
end
function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxBytes = o.maxBytes or 2 ^ 30
local maxEntries = o.maxEntries or 65535
local verify = o.verify ~= false
if not r:match("MSCF") then
return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base)
end
r:skip(4)
local cbCabinet = r:u32le()
r:skip(4)
local coffFiles = r:u32le()
r:skip(4)
local minor, major = r:u8(), r:u8()
local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le()
local setId, iCabinet = r:u16le(), r:u16le()
local headerReserve, folderReserve, dataReserve = 0, 0, 0
if bit32.band(flags, FLAG_RESERVE) ~= 0 then
headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8()
end
local a = Archive.new("cab", encode)
local meta: any = a.meta
if headerReserve > 0 then
meta.reserve = r:bytes(headerReserve)
end
if bit32.band(flags, FLAG_PREV) ~= 0 then
meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256)
end
if bit32.band(flags, FLAG_NEXT) ~= 0 then
meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256)
end
if r.err then
return nil, r.err
end
if major ~= 1 then
return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor)
end
meta.setId, meta.cabinet = setId, iCabinet
meta.source = {
format = "cab",
version = major .. "." .. minor,
size = cbCabinet,
flags = flags,
reserve = { header = headerReserve, folder = folderReserve, data = dataReserve },
}
-- folders
local folders: { Folder } = {}
local methods = {}
for i = 1, cFolders do
local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le()
r:skip(folderReserve)
if r.err then
return nil, r.err
end
folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i }
local m = METHOD[bit32.band(typ, 15)]
methods[i] = {
method = m or ("type " .. bit32.band(typ, 15)),
window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil,
level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil,
blocks = nblocks,
}
end
meta.folders = methods
if cFiles == 0 or cFolders == 0 then
return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders")
end
if cFiles > maxEntries then
return nil, Err.new(Err.LIMIT, "more than maxEntries files")
end
-- the folder cache: the last decompressed folder
local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false
local function folderData(f: Folder): (buffer?, Err.Err?, boolean?)
if cachedIndex == f.index then
return cachedData, nil, cachedRuns
end
local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes)
if not list then
return nil, total, false
end
local data, err = inflateFolder(r.buf, list, total, f.type)
if not data then
return nil, err, false
end
cachedIndex, cachedData, cachedRuns = f.index, data, runs == true
return data, nil, runs
end
-- files
local fr = r:sub(coffFiles)
for _ = 1, cFiles do
local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le()
local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le()
local raw = fr:cstring(65536)
if fr.err then
return nil, fr.err
end
local name = string.gsub(raw, "\\", "/")
local spanned: string? = nil
local folder: Folder?
if iFolder == 0xFFFD or iFolder == 0xFFFF then
spanned = "a file continued from the previous cabinet"
folder = folders[1]
elseif iFolder == 0xFFFE then
spanned = "a file continued in the next cabinet"
folder = folders[#folders]
else
folder = folders[iFolder + 1]
if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then
spanned = "a folder continued from the previous cabinet"
end
end
if not folder then
return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder)
end
local fo = folder :: Folder
if size > maxBytes then
return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
end
local e: any = {
name = name,
size = size,
method = METHOD[bit32.band(fo.type, 15)] or "unknown",
mtime = Archive.fromDos(date * 65536 + time),
dir = false,
attributes = bit32.band(attribs, 0xFF7F),
utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0,
folder = fo.index,
offset = offset,
readonly = bit32.band(attribs, 0x01) ~= 0,
executable = bit32.band(attribs, 0x40) ~= 0,
}
if spanned then
e.spanned = true
end
if size > 0 or spanned then
e.load = function(): (buffer?, Err.Err?)
if spanned then
return nil, Err.new(Err.UNSUPPORTED, spanned :: string)
end
local data, err, runs = folderData(fo)
if not data then
return nil, err
end
if offset + size > buffer.len(data) then
if runs then
return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet")
end
return nil, Err.new(Err.CORRUPT, "file past the end of its folder")
end
local out = buffer.create(size)
buffer.copy(out, 0, data, offset, size)
return out, nil
end
end
Archive.put(a, e)
end
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names)
function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local compression = o.compression or "mszip"
if compression ~= "mszip" and compression ~= "none" then
return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"")
end
local level = o.level or 6
if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
return nil, Err.new(Err.ARG, "level must be 0..9")
end
local files, ferr = Archive.files(archive)
if not files then
return nil, ferr
end
if #files == 0 then
return nil, Err.new(Err.ARG, "a cabinet needs at least one file")
end
if #files > 65535 then
return nil, Err.new(Err.ARG, "more than 65535 files")
end
local total = 0
for _, f in files do
total += buffer.len(f.data)
end
if total > 0x7FFF8000 then
return nil, Err.new(Err.ARG, "more than 2 GB of data")
end
-- the folder data, in 32 KB blocks
local folder = buffer.create(total)
local p = 0
for _, f in files do
buffer.copy(folder, p, f.data, 0, buffer.len(f.data))
p += buffer.len(f.data)
end
local data = Bytes.writer(total // 2 + 64)
local nblocks = 0
local s = 0
while s < total do
local n = math.min(BLOCK, total - s)
local chunk = buffer.create(n)
buffer.copy(chunk, 0, folder, s, n)
local payload: buffer
if compression == "mszip" then
local z, zerr = Deflate.compress(chunk, { level = level })
if not z then
return nil, zerr
end
payload = buffer.create(buffer.len(z) + 2)
buffer.writeu16(payload, 0, 0x4B43)
buffer.copy(payload, 2, z, 0, buffer.len(z))
else
payload = chunk
end
local len = buffer.len(payload)
data:u32le(Sum.block(payload, 0, len, n))
data:u16le(len)
data:u16le(n)
data:bytes(payload)
nblocks += 1
s += n
end
local blob = data:finish()
-- names and the file table
local table_ = Bytes.writer(64 + #files * 32)
local offset = 0
for _, f in files do
local e: any = f.entry
local name = string.gsub(f.name, "/", "\\")
local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20
if string.find(name, "[\128-\255]") then
attribs = bit32.bor(attribs, ATTR_UTF8)
end
local stamp = Archive.toDos(e.mtime)
table_:u32le(buffer.len(f.data))
table_:u32le(offset)
table_:u16le(0)
table_:u16le(stamp // 65536)
table_:u16le(stamp % 65536)
table_:u16le(attribs)
table_:cstring(name)
offset += buffer.len(f.data)
end
local fileTable = table_:finish()
local nfolders = 1
local coffFiles = 36 + 8 * nfolders
local dataAt = coffFiles + buffer.len(fileTable)
local size = dataAt + buffer.len(blob)
local w = Bytes.writer(size)
w:string("MSCF")
w:u32le(0)
w:u32le(size)
w:u32le(0)
w:u32le(coffFiles)
w:u32le(0)
w:u8(3)
w:u8(1)
w:u16le(nfolders)
w:u16le(#files)
w:u16le(0)
w:u16le(o.setId or 0)
w:u16le(0)
w:u32le(dataAt)
w:u16le(nblocks)
w:u16le(if compression == "mszip" then 1 else 0)
w:bytes(fileTable)
w:bytes(blob)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" })
function Cab.new(): any
local a = Archive.new("cab", encode)
a.meta.source = { format = "cab" }
return a
end
return Cab
@@ -64,10 +64,19 @@ end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and
-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing).
-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it,
-- distances may reach into it, and outLen includes it (cap does not).
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?)
local out = bcreate(cap)
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?)
local op = 0
if dict then
op = blen(dict)
cap += op
end
local out = bcreate(cap)
if dict then
bcopy(out, 0, dict, 0, op)
end
local pos = start
local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer
+50 -2
View File
@@ -6,6 +6,8 @@
-- local Deflate = require("@formats/codecs/compress/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary
-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained)
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
@@ -43,7 +45,9 @@ end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may
-- reach into it; the result holds only the new bytes.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
return nil, aerr
@@ -58,10 +62,20 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?,
else
cap = math.max(1024, l * 4)
end
local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact)
if dict ~= nil and type(dict) ~= "buffer" then
return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer")
end
local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict)
if not out then
return nil, inflateErr(tostring(n), o)
end
if dict then
local d = buffer.len(dict)
n -= d
local res = buffer.create(n)
buffer.copy(res, 0, out, d, n)
out = res
end
if exact and n ~= expectedSize then
return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number))
end
@@ -295,6 +309,40 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E
return out, nil
end
-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x
-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that
-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the
-- blocks' output concatenated.
function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?)
local total = 0
for _, b in blocks do
if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then
return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range")
end
total += b.size
end
local out = buffer.create(total)
local o = 0
for _, b in blocks do
if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then
return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset)
end
local dict: buffer? = nil
if o > 0 then
local d = math.min(o, 32768)
dict = buffer.create(d)
buffer.copy(dict :: buffer, 0, out, o - d, d)
end
local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict)
if not part then
return nil, err
end
buffer.copy(out, o, part, 0, b.size)
o += b.size
end
return out, nil
end
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
+449
View File
@@ -0,0 +1,449 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and
-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19),
-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the
-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets
-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification
-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from
-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants).
--
-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message
--
-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact
-- uncompressed size. Never throws: bad or truncated data returns nil, message.
local Huffman = require("@formats/codecs/entropy/Huffman")
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32
local writeu8, writei32 = buffer.writeu8, buffer.writei32
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local Lzx = {}
local FRAME = 32768
local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6
local MAXMAIN = 256 + 8 * 50
local NLEN = 249
local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder)
-- position slots: footer bits and base of each formatted offset slot
local EXTRA = table.create(51, 0)
local BASE = table.create(51, 0)
do
local b = 0
for i = 0, 50 do
local e = if i < 4 then 0 else math.min(i // 2 - 1, 17)
EXTRA[i + 1] = e
BASE[i + 1] = b
b += lshift(1, e)
end
end
local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 }
-- ------------------------------------------------------------------------------------------------ bit reader
-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the
-- end, zero words are read and over counts their bits.
type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number }
local function refill(s: State)
while s.cnt <= 16 do
local p = s.pos
local w = 0
if p + 2 <= s.stop then
w = readu16(s.src, p)
s.pos = p + 2
elseif p < s.stop then
w = readu8(s.src, p)
s.pos = p + 1
s.over += 8
else
s.over += 16
end
s.bb = bor(s.bb, lshift(w, 16 - s.cnt))
s.cnt += 16
end
end
-- bits(s, n) -> the next n (1..17) bits
local function bits(s: State, n: number): number
if s.cnt < n then
refill(s)
end
local v = rshift(s.bb, 32 - n)
s.bb = lshift(s.bb, n)
s.cnt -= n
return v
end
-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code
local function sym(s: State, tab: buffer, P: number, S: number): number
if s.cnt < 16 then
refill(s)
end
local e = readu32(tab, rshift(s.bb, 32 - P) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return -1
end
e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4)
l = band(e, 31)
if l == 0 then
return -1
end
end
s.bb = lshift(s.bb, l)
s.cnt -= l
return rshift(e, 5)
end
-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree
local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean
for i = 0, 19 do
writeu8(preLens, i, bits(s, 4))
end
local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP)
if S < 0 then
return false
end
local cap = blen(lens)
local x = first
while x < last do
local z = sym(s, pre, PREP, S)
if z < 0 then
return false
end
if z == 17 or z == 18 then
local run = if z == 17 then bits(s, 4) + 4 else bits(s, 5) + 20
for _ = 1, run do
if x < cap then
writeu8(lens, x, 0)
end
x += 1
end
elseif z == 19 then
local run = bits(s, 1) + 4
local d = sym(s, pre, PREP, S)
if d < 0 or d > 16 then
return false
end
local v = (readu8(lens, x) - d + 17) % 17
for _ = 1, run do
if x < cap then
writeu8(lens, x, v)
end
x += 1
end
else
writeu8(lens, x, (readu8(lens, x) - z + 17) % 17)
x += 1
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ decode
-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative)
local function translate(out: buffer, n: number, size: number)
local base = 0
local frame = 0
while base < n and frame < 32768 do
local fs = math.min(FRAME, n - base)
if fs > 10 then
local i = base
local stop = base + fs - 10
while i < stop do
if readu8(out, i) == 0xE8 then
local abs = readi32(out, i + 1)
if abs >= -i and abs < size then
writei32(out, i + 1, if abs >= 0 then abs - i else abs + size)
end
i += 5
else
i += 1
end
end
end
base += fs
frame += 1
end
end
function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?)
local nslots = SLOTS[windowBits]
if not nslots then
return nil, "unsupported: LZX window 2^" .. tostring(windowBits)
end
if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then
return nil, "bad arguments"
end
local windowSize = lshift(1, windowBits)
local mainN = 256 + 8 * nslots
local out = bcreate(outSize)
local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20)
local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4)
local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4)
local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4)
local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4)
local s: State = { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 }
local R0: number, R1: number, R2: number = 1, 1, 1
local intel = 0
local started = false
local btype, bremain, bsize = 0, 0, 0
local mainS, lenS, alignS = 0, 0, 0
local op = 0
while op < outSize do
local frameEnd = math.min(op + FRAME, outSize)
while op < frameEnd do
if bremain == 0 then
-- a new block
if btype == 3 and band(bsize, 1) == 1 then
s.pos += 1
end
if not started then
started = true
if bits(s, 1) == 1 then
local hi = bits(s, 16)
intel = hi * 65536 + bits(s, 16)
end
end
btype = bits(s, 3)
local hi = bits(s, 16)
bsize = hi * 256 + bits(s, 8)
bremain = bsize
if s.over > s.cnt then
return nil, "truncated input"
end
if bsize == 0 then
return nil, "empty block"
end
if btype == 2 then
for i = 0, 7 do
writeu8(alignLens, i, bits(s, 3))
end
alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP)
if alignS < 0 then
return nil, "bad aligned offset tree"
end
end
if btype == 1 or btype == 2 then
if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then
return nil, "bad main tree"
end
mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP)
if mainS < 0 then
return nil, "bad main tree"
end
if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then
return nil, "bad length tree"
end
lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP)
if lenS < 0 then
return nil, "bad length tree"
end
elseif btype == 3 then
-- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes
local k = s.cnt % 16
if k == 0 then
k = 16
end
local p = s.pos - (s.cnt - k) // 8
s.bb, s.cnt = 0, 0
if s.over > 0 or p + 12 > s.stop then
return nil, "truncated uncompressed block"
end
R0 = readu32(src, p)
R1 = readu32(src, p + 4)
R2 = readu32(src, p + 8)
s.pos = p + 12
else
return nil, "bad block type " .. btype
end
if s.over > s.cnt then
return nil, "truncated input"
end
end
local runEnd = op + math.min(bremain, frameEnd - op)
if btype == 3 then
local n = runEnd - op
local p = s.pos
if p + n > s.stop then
return nil, "truncated uncompressed block"
end
bcopy(out, op, src, p, n)
s.pos = p + n
op += n
bremain -= n
else
local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over
local stop = s.stop
local aligned = btype == 2
local start = op
while op < runEnd do
-- refill to at least 17 bits
while cnt <= 16 do
local w = 0
if pos + 2 <= stop then
w = readu16(src, pos)
pos += 2
elseif pos < stop then
w = readu8(src, pos)
pos += 1
over += 8
else
over += 16
end
bb = bor(bb, lshift(w, 16 - cnt))
cnt += 16
end
local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "bad main code"
end
e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "bad main code"
end
end
bb = lshift(bb, l)
cnt -= l
local m = rshift(e, 5)
if m < 256 then
writeu8(out, op, m)
op += 1
else
m -= 256
local len = band(m, 7)
if len == 7 then
while cnt <= 16 do
local w = 0
if pos + 2 <= stop then
w = readu16(src, pos)
pos += 2
else
over += 16
end
bb = bor(bb, lshift(w, 16 - cnt))
cnt += 16
end
local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4)
local ll = band(le, 31)
if ll == 0 then
if le == 0 then
return nil, "bad length code"
end
le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4)
ll = band(le, 31)
if ll == 0 then
return nil, "bad length code"
end
end
bb = lshift(bb, ll)
cnt -= ll
len += rshift(le, 5)
end
len += 2
local slot = rshift(m, 3)
local dist: number
if slot == 0 then
dist = R0
elseif slot == 1 then
dist = R1
R1 = R0
R0 = dist
elseif slot == 2 then
dist = R2
R2 = R0
R0 = dist
else
local ex = EXTRA[slot + 1]
dist = BASE[slot + 1] - 2
if ex > 0 then
while cnt <= 16 do
local w = 0
if pos + 2 <= stop then
w = readu16(src, pos)
pos += 2
else
over += 16
end
bb = bor(bb, lshift(w, 16 - cnt))
cnt += 16
end
if aligned and ex >= 3 then
if ex > 3 then
dist += lshift(rshift(bb, 35 - ex), 3)
bb = lshift(bb, ex - 3)
cnt -= ex - 3
while cnt <= 16 do
local w = 0
if pos + 2 <= stop then
w = readu16(src, pos)
pos += 2
else
over += 16
end
bb = bor(bb, lshift(w, 16 - cnt))
cnt += 16
end
end
local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4)
local al = band(ae, 31)
if al == 0 then
return nil, "bad aligned offset code"
end
bb = lshift(bb, al)
cnt -= al
dist += rshift(ae, 5)
else
dist += rshift(bb, 32 - ex)
bb = lshift(bb, ex)
cnt -= ex
end
end
R2 = R1
R1 = R0
R0 = dist
end
if dist < 1 or dist > op or dist > windowSize then
return nil, "match offset before the start of the data"
end
if op + len > runEnd then
return nil, "match past the end of its block or 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
end
s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over
bremain -= op - start
end
end
-- the end of a frame: realign to 16 bits
local k = s.cnt % 16
s.bb = lshift(s.bb, k)
s.cnt -= k
if s.over > s.cnt then
return nil, "truncated input"
end
end
if intel ~= 0 then
translate(out, outSize, intel)
end
return out, nil
end
return Lzx
+251
View File
@@ -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