ws-m4a: merge ws/absorb (audio/opus, containers/Ogg, ...) for the CELT encoder; m4a fixtures load their helper by path (tools/fixtures/ on sys.path shadowed the xml package)

This commit is contained in:
4DBug committed 2026-10-31 09:07:22 -05:00
commit 29a95ce24f
215 files changed
+24209 -61

No files matched your search

+208
View File
@@ -0,0 +1,208 @@
--!strict
--!native
--!optimize 2
-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in formats-luau.
-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or
-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last
-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages
-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other.
--
-- local mux = Mux.new({ pageSize = 4096 })
-- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...)
-- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page
-- s:packet(tags, 0, { flush = true })
-- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate)
-- local out = mux:finish() -- closes every stream with an eos page
--
-- Never throws: a bad argument returns false, Err.
local Err = require("@formats/core/Err")
local Page = require("@formats/containers/Ogg/Page")
local CRC = Page.CRC_TABLE
local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32
local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift
local Mux = {}
Mux.__index = Mux
local Stream = {}
Stream.__index = Stream
export type Options = {
pageSize: number?, -- close a page once its data reaches this many bytes (default 4096; at most 255 * 255)
}
export type PacketOptions = {
flush: boolean?, -- close the page after this packet (headers; default false)
eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed)
}
-- new(opts?) -> Mux
function Mux.new(opts: Options?): any
local size = opts and opts.pageSize or 4096
if type(size) ~= "number" or size < 1 then
size = 4096
end
return setmetatable({
pageSize = math.min(size, 255 * 255),
chunks = {} :: { buffer },
total = 0,
streams = {} :: { any },
nextSerial = 1,
}, Mux)
end
-- stream(serial?) -> Stream (serials must be unique in the file)
function Mux.stream(self: any, serial: number?): any
local sr = serial or self.nextSerial
self.nextSerial = math.max(self.nextSerial, sr + 1)
local s = setmetatable({
mux = self,
serial = sr % 4294967296,
seq = 0,
lacing = {} :: { number },
parts = {} :: { any }, -- buffer, offset, length triples of the page data
dataLen = 0,
granule = -1,
continued = false, -- the page being built starts with the tail of a packet
first = true,
ended = false,
lastGranule = -1,
}, Stream)
table.insert(self.streams, s)
return s
end
-- the CRC of a page (the crc field written as zero)
local function crc(b: buffer, n: number): number
local c = 0
for i = 0, n - 1 do
c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1])
end
return c
end
-- close the page being built (also when empty, for eos)
function Stream._flush(self: any, eos: boolean)
local nseg = #self.lacing
local n = 27 + nseg + self.dataLen
local b = buffer.create(n)
buffer.writestring(b, 0, "OggS")
local flags = (if self.continued then 1 else 0) + (if self.first then 2 else 0) + (if eos then 4 else 0)
writeu8(b, 5, flags)
local g = self.granule
if g < 0 then
writeu32(b, 6, 0xFFFFFFFF)
writei32(b, 10, -1)
else
writeu32(b, 6, g % 4294967296)
writeu32(b, 10, (g // 4294967296) % 4294967296)
end
writeu32(b, 14, self.serial)
writeu32(b, 18, self.seq % 4294967296)
writeu8(b, 26, nseg)
for i = 1, nseg do
writeu8(b, 26 + i, self.lacing[i])
end
local o = 27 + nseg
local parts = self.parts
for i = 1, #parts, 3 do
buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2])
o += parts[i + 2]
end
writeu32(b, 22, crc(b, n))
local m = self.mux
table.insert(m.chunks, b)
m.total += n
self.seq += 1
self.first = false
self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1
self.continued = false
if eos then
self.ended = true
end
end
-- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet
-- (-1: unknown, not recommended); offset / length select a range of data.
function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?)
if self.ended then
return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial)
end
local b: buffer
if type(data) == "string" then
b = buffer.fromstring(data)
elseif type(data) == "buffer" then
b = data
else
return false, Err.new(Err.ARG, "packet: data must be a buffer or a string")
end
if type(granule) ~= "number" then
return false, Err.new(Err.ARG, "packet: granule must be a number")
end
local off = offset or 0
local len = length or (buffer.len(b) - off)
if off < 0 or len < 0 or off + len > buffer.len(b) then
return false, Err.new(Err.ARG, "packet: range outside the buffer")
end
local pageSize = self.mux.pageSize
local left = len
local pos = off
-- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255)
while true do
if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then
self:_flush(false)
self.continued = pos > off -- the next page starts inside this packet
end
local seg = math.min(left, 255)
table.insert(self.lacing, seg)
if seg > 0 then
table.insert(self.parts, b)
table.insert(self.parts, pos)
table.insert(self.parts, seg)
end
self.dataLen += seg
pos += seg
left -= seg
if seg < 255 then
break
end
end
if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page
self.granule = granule
self.lastGranule = granule
end
local eos = opts and opts.eos or false
if eos then
self:_flush(true)
elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then
self:_flush(false)
end
return true, nil
end
-- flush(): close the current page now (if it holds anything)
function Stream.flush(self: any)
if not self.ended and #self.lacing > 0 then
self:_flush(false)
end
end
-- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written)
function Mux.finish(self: any): buffer
for _, s in self.streams do
if not s.ended then
if #s.lacing == 0 then
s.granule = s.lastGranule
end
s:_flush(true)
end
end
local out = buffer.create(self.total)
local o = 0
for _, c in self.chunks do
buffer.copy(out, o, c, 0, buffer.len(c))
o += buffer.len(c)
end
return out
end
return Mux
+185
View File
@@ -0,0 +1,185 @@
--!strict
--!native
--!optimize 2
-- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header
-- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset,
-- forwards or backwards). Nothing here throws: invalid or truncated data gives nil.
--
-- A page header (27 bytes + segment table):
-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32)
-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data
local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32
local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift
local Page = {}
export type Info = {
offset: number, -- byte offset of "OggS"
size: number, -- header + segment table + data
headerSize: number, -- 27 + segment count
nsegs: number,
flags: number,
continued: boolean,
bos: boolean,
eos: boolean,
granule: number, -- -1 when no packet finishes on this page
serial: number,
sequence: number,
}
-- CRC table, MSB-first
local CRC = table.create(256, 0)
for i = 0, 255 do
local r = lshift(i, 24)
for _ = 1, 8 do
if band(r, 0x80000000) ~= 0 then
r = bxor(lshift(r, 1), 0x04C11DB7)
else
r = lshift(r, 1)
end
end
CRC[i + 1] = r
end
Page.CRC_TABLE = CRC
-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc
local function crcRange(b: buffer, from: number, to: number, crc: number): number
for i = from, to - 1 do
crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1])
end
return crc
end
-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data)
function Page.crc32(b: buffer, offset: number?, len: number?): number
local o = offset or 0
local n = len or (buffer.len(b) - o)
if o < 0 or n < 0 or o + n > buffer.len(b) then
return 0
end
return crcRange(b, o, o + n, 0)
end
-- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic",
-- "version", "crc"). verify = false skips the CRC check.
function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?)
local size = buffer.len(b)
if pos < 0 or pos + 27 > size then
return nil, "short"
end
if readu32(b, pos) ~= 0x5367674F then -- "OggS"
return nil, "magic"
end
if readu8(b, pos + 4) ~= 0 then
return nil, "version"
end
local nsegs = readu8(b, pos + 26)
local hsize = 27 + nsegs
if pos + hsize > size then
return nil, "short"
end
local dlen = 0
for i = pos + 27, pos + hsize - 1 do
dlen += readu8(b, i)
end
local total = hsize + dlen
if pos + total > size then
return nil, "short"
end
if verify ~= false then
local c = crcRange(b, pos, pos + 22, 0)
for _ = 1, 4 do
c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1])
end
c = crcRange(b, pos + 26, pos + total, c)
if c ~= readu32(b, pos + 22) then
return nil, "crc"
end
end
local flags = readu8(b, pos + 5)
return {
offset = pos,
size = total,
headerSize = hsize,
nsegs = nsegs,
flags = flags,
continued = band(flags, 1) ~= 0,
bos = band(flags, 2) ~= 0,
eos = band(flags, 4) ~= 0,
granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6),
serial = readu32(b, pos + 14),
sequence = readu32(b, pos + 18),
}, nil
end
-- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the
-- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped.
function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info?
local size = buffer.len(b)
local lim = math.min(limit or size, size - 27 + 1)
if pos < 0 then
pos = 0
end
while pos < lim do
if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then
local p = Page.parse(b, pos, verify)
if p then
return p
end
end
pos += 1
end
return nil
end
-- The last valid page starting at an offset in [floor, pos] (searching backwards).
function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info?
local size = buffer.len(b)
local lo = math.max(floor or 0, 0)
if pos > size - 27 then
pos = size - 27
end
while pos >= lo do
if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then
local p = Page.parse(b, pos, verify)
if p then
return p
end
end
pos -= 1
end
return nil
end
-- The identification of a codec from a stream's first packet (the bos page's packet)
function Page.codec(b: buffer, off: number, len: number): string
local function is(s: string, at: number): boolean
if at + #s > len then
return false
end
for i = 1, #s do
if readu8(b, off + at + i - 1) ~= string.byte(s, i) then
return false
end
end
return true
end
if is("OpusHead", 0) then
return "opus"
elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then
return "flac"
elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then
return "vorbis"
elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then
return "theora"
elseif is("Speex ", 0) then
return "speex"
elseif is("fishead", 0) then
return "skeleton"
elseif is("fLaC", 0) then
return "flac-old" -- pre-1.1.1 Ogg FLAC mapping
end
return "unknown"
end
return Page
+456
View File
@@ -0,0 +1,456 @@
--!strict
--!native
--!optimize 2
-- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604
-- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and
-- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture
-- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial);
-- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad
-- input gives nil, err).
--
-- local demux, err = Ogg.open(buf)
-- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end
-- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator
-- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil
-- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target)
--
-- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux)
-- local s = mux:stream(serial?) -- one logical stream
-- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages
-- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes
-- local file = mux:finish() -- every stream ends with an eos page
local Err = require("@formats/core/Err")
local Page = require("@formats/containers/Ogg/Page")
local Mux = require("@formats/containers/Ogg/Mux")
local readu8 = buffer.readu8
type PageInfo = any -- Page.Info (the sibling module is untyped here: required through `script` in Roblox)
local Ogg = {}
Ogg.Page = Page
Ogg.Mux = Mux
Ogg.muxer = Mux.new
export type Packet = {
data: buffer, -- the packet bytes are data[offset .. offset + size - 1]
offset: number,
size: number,
granule: number, -- the page granule if this is the last packet finishing on its page, else -1
pageGranule: number, -- the granule of the page the packet finishes on (may be -1)
bos: boolean, -- first packet of the stream
eos: boolean, -- last packet of the stream (last packet finishing on an eos page)
pageOffset: number, -- byte offset of the page the packet finishes on
gap: boolean, -- data was lost before this packet (a missing page / bad CRC in between)
}
export type Stream = {
serial: number,
codec: string, -- "opus" | "flac" | "vorbis" | "theora" | "speex" | "skeleton" | "flac-old" | "unknown"
firstPacket: buffer, -- a copy of the identification packet
bosOffset: number, -- byte offset of the bos page
lastGranule: number, -- the last known granule of the stream (-1 if none)
}
-- Reader: the packet cursor of one logical stream
local Reader = {}
Reader.__index = Reader
local function newReader(d: any, serial: number, start: number): any
return setmetatable({
demux = d,
buf = d.buf,
serial = serial,
start = start, -- the bos page offset
pagePos = start, -- where to look for the next page
page = nil :: PageInfo?,
seg = 0, -- next segment index on the page
dataPos = 0, -- byte offset of the next segment's data
lastComplete = -1, -- index of the last segment ending a packet on this page
firstPacketOnPage = true,
parts = {} :: { number }, -- pending partial packet: offset, len pairs
partLen = 0,
lastSeq = -1,
gap = false,
ended = false,
total = 0,
}, Reader)
end
-- Load the next page of this serial; false at the end of the data
function Reader._nextPage(self: any): boolean
local b, d = self.buf, self.demux
while true do
local p = Page.find(b, self.pagePos, nil, d.verify)
if not p then
return false
end
self.pagePos = p.offset + p.size
if p.serial == self.serial then
if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then
-- a page is missing: drop the partial packet
self.parts, self.partLen = {}, 0
self.gap = true
end
self.lastSeq = p.sequence
self.page = p
self.seg = 0
self.dataPos = p.offset + p.headerSize
self.firstPacketOnPage = true
local lc = -1
local base = p.offset + 27
for i = 0, p.nsegs - 1 do
if readu8(b, base + i) < 255 then
lc = i
end
end
self.lastComplete = lc
if p.continued then
if self.partLen == 0 and #self.parts == 0 then
-- the start of this packet is not ours (after a seek or a loss): skip its tail
local s = 0
while s < p.nsegs do
local l = readu8(b, base + s)
self.dataPos += l
s += 1
if l < 255 then
break
end
end
self.seg = s
self.firstPacketOnPage = false
end
elseif #self.parts > 0 then
-- a fresh packet while one was pending: the pending one is lost
self.parts, self.partLen = {}, 0
self.gap = true
end
return true
end
end
end
-- The next packet, or nil at the end of the stream
function Reader.nextPacket(self: any): Packet?
if self.ended then
return nil
end
local b = self.buf
while true do
local p = self.page
if p and self.seg < p.nsegs then
local base = p.offset + 27
local start = self.dataPos
local len = 0
local s = self.seg
local complete = false
while s < p.nsegs do
local l = readu8(b, base + s)
s += 1
len += l
if l < 255 then
complete = true
break
end
end
self.seg = s
self.dataPos = start + len
if complete then
local data, off, size = b, start, len
local parts = self.parts
if #parts > 0 then
size = self.partLen + len
data = buffer.create(size)
off = 0
local o = 0
for i = 1, #parts, 2 do
buffer.copy(data, o, b, parts[i], parts[i + 1])
o += parts[i + 1]
end
buffer.copy(data, o, b, start, len)
self.parts, self.partLen = {}, 0
end
local last = (s - 1) == self.lastComplete
local pkt = {
data = data,
offset = off,
size = size,
granule = if last then p.granule else -1,
pageGranule = p.granule,
bos = p.bos and self.firstPacketOnPage,
eos = p.eos and last,
pageOffset = p.offset,
gap = self.gap,
}
self.firstPacketOnPage = false
self.gap = false
self.total += 1
if pkt.eos then
self.ended = true
end
return pkt
else
-- the packet continues on a later page
table.insert(self.parts, start)
table.insert(self.parts, len)
self.partLen += len
end
else
if p and p.eos then
self.ended = true
return nil
end
if not self:_nextPage() then
self.ended = true
return nil
end
end
end
end
-- Back to the start of the stream (the identification packet comes next)
function Reader.rewind(self: any)
self.pagePos = self.start
self.page = nil
self.seg = 0
self.parts, self.partLen = {}, 0
self.lastSeq = -1
self.gap = false
self.ended = false
end
-- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them
function Reader._at(self: any, p: PageInfo)
self:rewind()
self.pagePos = p.offset
self:_nextPage() -- loads p (it is a valid page of this serial)
local b = self.buf
local base = p.offset + 27
local dp = p.offset + p.headerSize
for i = 0, self.lastComplete do
dp += readu8(b, base + i)
end
self.seg = self.lastComplete + 1
self.dataPos = dp
self.parts, self.partLen = {}, 0
self.firstPacketOnPage = false
self.gap = false
self.ended = false
end
-- Seek so that the next packet is the first one that starts at or before granule g: positions after the last
-- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the
-- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start
-- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil).
function Reader.seekGranule(self: any, g: number): (number?, Err.Err?)
local b, d = self.buf, self.demux
local serial = self.serial
local verify = d.verify
local function nextOf(pos: number, limit: number?): PageInfo?
while true do
local p = Page.find(b, pos, limit, verify)
if not p then
return nil
end
if p.serial == serial and p.granule ~= -1 then
return p
end
pos = p.offset + p.size
end
end
local lo, hi = self.start, buffer.len(b)
local best: PageInfo? = nil
while hi - lo > 65536 do
local mid = (lo + hi) // 2
local p = nextOf(mid, hi)
if p and p.granule <= g then
best = p
lo = p.offset
else
hi = mid
end
end
local pos = lo
while true do
local p = nextOf(pos)
if not p or p.granule > g then
break
end
best = p
pos = p.offset + p.size
end
if not best then
self:rewind()
return -1, nil
end
self:_at(best)
return best.granule, nil
end
-- Demux
local Demux = {}
Demux.__index = Demux
-- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied
-- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll =
-- true lists every bos page in the file (chained streams), not just the first group
function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?)
local buf: buffer
if type(src) == "buffer" then
buf = src
elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then
if src.base == 0 and src.limit == buffer.len(src.buf) then
buf = src.buf
else
local n = math.max(0, src.limit - src.base)
buf = buffer.create(n)
buffer.copy(buf, 0, src.buf, src.base, n)
end
else
return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader")
end
local verify = not (opts and opts.verify == false)
local first = Page.find(buf, 0, nil, verify)
if not first then
return nil, Err.new(Err.CORRUPT, "no Ogg page found")
end
local d = setmetatable({
buf = buf,
size = buffer.len(buf),
verify = verify,
_streams = {} :: { Stream },
_bySerial = {} :: { [number]: Stream },
_readers = {} :: { [number]: any },
_lastDone = false,
}, Demux)
-- the bos pages (at the start of the file, and later ones for chains if scanAll)
local pos = first.offset
local scanAll = opts and opts.scanAll
while true do
local p = Page.find(buf, pos, nil, verify)
if not p then
break
end
if p.bos and not d._bySerial[p.serial] then
local st = {
serial = p.serial,
codec = "unknown",
firstPacket = buffer.create(0),
bosOffset = p.offset,
lastGranule = -1,
}
table.insert(d._streams, st)
d._bySerial[p.serial] = st
local r = newReader(d, p.serial, p.offset)
local pk = r:nextPacket()
if pk then
local c = buffer.create(pk.size)
buffer.copy(c, 0, pk.data, pk.offset, pk.size)
st.firstPacket = c
st.codec = Page.codec(c, 0, pk.size)
end
elseif not p.bos and not scanAll then
break
end
pos = p.offset + p.size
end
if #d._streams == 0 then
return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page")
end
return d, nil
end
-- Scan backwards from the end for each stream's last granule
function Demux._scanLast(self: any)
if self._lastDone then
return
end
self._lastDone = true
local b = self.buf
local need = #self._streams
local pos = self.size - 27
while need > 0 do
local p = Page.findBack(b, pos, 0, self.verify)
if not p then
break
end
local st = self._bySerial[p.serial]
if st and st.lastGranule == -1 and p.granule ~= -1 then
st.lastGranule = p.granule
need -= 1
end
pos = p.offset - 1
end
end
-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule }
function Demux.streams(self: any): { Stream }
self:_scanLast()
return self._streams
end
function Demux.stream(self: any, serial: number): Stream?
self:_scanLast()
return self._bySerial[serial]
end
-- The serial of the first stream of a codec, or nil
function Demux.find(self: any, codec: string): number?
for _, s in self._streams do
if s.codec == codec then
return s.serial
end
end
return nil
end
-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err
function Demux.reader(self: any, serial: number): (any, Err.Err?)
local r = self._readers[serial]
if r then
return r, nil
end
local st = self._bySerial[serial]
if not st then
return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial))
end
r = newReader(self, serial, st.bosOffset)
self._readers[serial] = r
return r, nil
end
function Demux.nextPacket(self: any, serial: number): Packet?
local r = self:reader(serial)
return if r then r:nextPacket() else nil
end
function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?)
local r, err = self:reader(serial)
if not r then
return nil, err
end
return r:seekGranule(g)
end
function Demux.rewind(self: any, serial: number)
local r = self:reader(serial)
if r then
r:rewind()
end
end
-- for p in demux:packets(serial) do ... end (continues from the stream's current position)
function Demux.packets(self: any, serial: number): () -> Packet?
local r = self:reader(serial)
return function()
return if r then r:nextPacket() else nil
end
end
-- Copy a packet's bytes into a fresh buffer of its own
function Ogg.copy(p: Packet): buffer
local c = buffer.create(p.size)
buffer.copy(c, 0, p.data, p.offset, p.size)
return c
end
return Ogg
+372
View File
@@ -0,0 +1,372 @@
--!strict
-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently
-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from
-- wav-luau fd9a909 (same author, no third-party code); the writer is new.
--
-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer
-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false
-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf
-- local c = Riff.find(f, "fmt ")
-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type)
--
-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX)
-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } })
-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB
-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB
--
-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past
-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a
-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of
-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
local Riff = {}
export type Chunk = {
id: string,
offset: number, -- absolute offset of the body in the file's buffer
size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks
declared: number, -- the raw size field
avail: number, -- body bytes present in the file (<= size)
truncated: boolean, -- declared past the end of the file
streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end)
}
export type File = {
container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64)
form: string, -- the form type: "WAVE", "AVI ", "WEBP", ...
bigEndian: boolean,
buf: buffer,
base: number, -- absolute offset of the file's first byte
limit: number, -- absolute offset past its last byte
size: number, -- the RIFF size field (ds64-resolved)
chunks: { Chunk },
ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?,
}
export type ReadOptions = {
openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data)
maxChunks: number?, -- stop after this many chunks (default 100000)
}
-- ------------------------------------------------------------------------------------------------ read
local function printable4(b: buffer, p: number, limit: number): boolean
if p + 4 > limit then
return false
end
for i = 0, 3 do
local c = readu8(b, p + i)
if c < 32 or c > 126 then
return false
end
end
return true
end
local function u32(b: buffer, o: number, be: boolean): number
local v = readu32(b, o)
return if be then bit32.byteswap(v) else v
end
-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil
function Riff.sniff(r: any): string?
local magic = r:peek(4)
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
return nil
end
local form = r:peek(4, 8)
return if #form == 4 then form else nil
end
-- walk the chunks of [p, limit) into list; returns the list
local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk }
local openEnded = opts and opts.openEnded
local maxChunks = opts and opts.maxChunks or 100000
while p + 8 <= limit and #list < maxChunks do
local id = readstring(b, p, 4)
local declared = u32(b, p + 4, be)
local size = declared
local body = p + 8
local avail = limit - body
if declared == 0xFFFFFFFF and ds64 then
if id == "data" then
size = ds64.dataSize
elseif ds64.table[id] then
size = ds64.table[id]
end
end
local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false }
table.insert(list, c)
if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then
c.streamed = size == 0 or size == 0xFFFFFFFF
c.truncated = not c.streamed
c.size, c.avail = avail, avail
break
end
if size > avail then
c.truncated = true
break
end
local nextPos = body + size + size % 2
-- an odd-sized chunk written without its pad byte: the next id starts right after the body
if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then
nextPos = body + size
end
p = nextPos
end
return list
end
-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer.
function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?)
local r = if type(src) == "buffer" then Bytes.reader(src) else src
if type(r) ~= "table" or type(r.buf) ~= "buffer" then
return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader")
end
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 12 then
return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base)
end
local magic = readstring(b, base, 4)
if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then
return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base)
end
local be = magic == "RIFX"
local f: File = {
container = if magic == "BW64" then "RF64" else magic,
form = readstring(b, base + 8, 4),
bigEndian = be,
buf = b,
base = base,
limit = limit,
size = u32(b, base + 4, be),
chunks = {},
ds64 = nil,
}
-- RF64: the ds64 chunk comes first
if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then
local sz = readu32(b, base + 16)
local o = base + 20
if sz >= 24 and o + 24 <= limit then
local d = {
riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296,
dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296,
sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296,
table = {} :: { [string]: number },
}
if sz >= 28 and o + 28 <= limit then
local n = readu32(b, o + 24)
local q = o + 28
for _ = 1, math.min(n, 1000) do
if q + 12 > limit or q + 12 > o + sz then
break
end
d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296
q += 12
end
end
f.ds64 = d
if f.size == 0xFFFFFFFF then
f.size = d.riffSize
end
end
end
walk(b, base + 12, limit, be, opts, f.ds64, f.chunks)
return f, nil
end
-- find(file, id, from?) -> the first chunk with that id (after index from), and its index
function Riff.find(f: File, id: string, from: number?): (Chunk?, number?)
for i = (from or 0) + 1, #f.chunks do
if f.chunks[i].id == id then
return f.chunks[i], i
end
end
return nil, nil
end
-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil
function Riff.listType(f: File, c: Chunk): string?
if c.avail < 4 then
return nil
end
return readstring(f.buf, c.offset, 4)
end
-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type)
function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk }
if c.avail < 4 then
return {}
end
return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil, {})
end
-- body(file, chunk) -> a Reader over the chunk's available body
function Riff.body(f: File, c: Chunk): Bytes.Reader
return Bytes.reader(f.buf, c.offset, c.avail)
end
-- u16 / u32 in the file's byte order (for chunk bodies)
function Riff.u16(f: File, o: number): number
if f.bigEndian then
return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1)
end
return readu16(f.buf, o)
end
function Riff.u32(f: File, o: number): number
return u32(f.buf, o, f.bigEndian)
end
-- ------------------------------------------------------------------------------------------------ write
local Writer = {}
Writer.__index = Writer
export type WriteOptions = {
bigEndian: boolean?, -- RIFX (default false)
rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto"
sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames)
rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF)
}
-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file
function Riff.writer(form: string, opts: WriteOptions?): any
return setmetatable({
form = string.sub(form .. " ", 1, 4),
be = opts and opts.bigEndian or false,
rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto",
sampleCount = opts and opts.sampleCount or 0,
threshold = opts and opts.rf64Threshold or 0xFFFFFFFF,
chunks = {} :: { any },
}, Writer)
end
-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a
-- list of buffers written one after the other (a data chunk bigger than one buffer)
function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?)
local parts = {}
local n = 0
if type(body) == "table" then
for _, b in body do
table.insert(parts, { b, 0, buffer.len(b) })
n += buffer.len(b)
end
else
local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body
local o = offset or 0
n = length or (buffer.len(b) - o)
parts[1] = { b, o, n }
end
table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n })
end
-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style)
function Writer.list(self: any, listType: string, items: { { any } })
local w = Bytes.writer()
w:string(string.sub(listType .. " ", 1, 4))
for _, it in items do
local v = it[2]
local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v
local n = buffer.len(data)
w:string(string.sub(it[1] .. " ", 1, 4))
if self.be then
w:u32be(n)
else
w:u32le(n)
end
w:bytes(data)
if n % 2 == 1 then
w:u8(0)
end
end
self:chunk("LIST", w:finish())
end
-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied)
function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?)
local total = 4 -- the form type
local big = false
local dataSize = 0
for _, c in self.chunks do
total += 8 + c.length + c.length % 2
if c.length > 0xFFFFFFFE then
big = true
end
if c.id == "data" then
dataSize = c.length
end
end
local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold))
if not rf64 and (big or total > 0xFFFFFFFF) then
return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64")
end
if rf64 and self.be then
return nil, Err.new(Err.ARG, "RF64 is little-endian only")
end
if rf64 then
total += 36 -- ds64
end
local asParts = opts and opts.parts
if not asParts and total + 8 > 0x40000000 then
return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })")
end
local out: { buffer } = {}
local w = Bytes.writer(if asParts then 256 else total + 8)
local function size32(v: number)
if self.be then
w:u32be(v)
else
w:u32le(v)
end
end
if rf64 then
w:string("RF64")
w:u32le(0xFFFFFFFF)
w:string(self.form)
w:string("ds64")
w:u32le(28)
w:u64le(total)
w:u64le(dataSize)
w:u64le(self.sampleCount)
w:u32le(0) -- no table: only data may be over 4 GiB
else
w:string(if self.be then "RIFX" else "RIFF")
size32(total)
w:string(self.form)
end
for _, c in self.chunks do
w:string(c.id)
if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then
w:u32le(0xFFFFFFFF)
else
size32(c.length)
end
for _, p in c.parts do
if asParts then
table.insert(out, w:finish())
w = Bytes.writer(64)
if p[2] == 0 and p[3] == buffer.len(p[1]) then
table.insert(out, p[1])
else
local cp = buffer.create(p[3])
buffer.copy(cp, 0, p[1], p[2], p[3])
table.insert(out, cp)
end
else
w:bytes(p[1], p[2], p[3])
end
end
if c.length % 2 == 1 then
w:u8(0)
end
end
if asParts then
if w:tell() > 0 then
table.insert(out, w:finish())
end
return out, nil
end
return w:finish(), nil
end
return Riff
+668
View File
@@ -0,0 +1,668 @@
--!strict
--!optimize 2
-- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from
-- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an
-- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor
-- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback,
-- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly
-- (codecs/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/Deflate compress, stored
-- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed.
--
-- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader
-- for _, e in zip:list() do print(e.name, e.size) end
-- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked
--
-- local w = Zip.writer()
-- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds
-- local file = w:finish({ comment = "..." })
--
-- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native
-- code it reaches (Deflate, Crc32) does not throw either.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/Deflate")
local Zip = {}
Zip.version = "1.1.0"
export type Entry = {
name: string, -- the path with "\" turned into "/"
rawName: string, -- the name bytes as stored
index: number, -- position in the central directory, 1-based
size: number, -- uncompressed size
compressedSize: number,
crc32: number,
method: number, -- 0 stored, 8 deflate (others are listed but not readable)
flags: number, -- general purpose bits (1 encrypted, 8 data descriptor, 2048 UTF-8 name)
offset: number, -- local header offset (already corrected for a prefix such as a self-extractor stub)
isDir: boolean,
utf8: boolean,
comment: string,
modified: { year: number, month: number, day: number, hour: number, min: number, sec: number },
mtime: number, -- the modification time as Unix seconds (the DOS time read as UTC)
time: number, -- the raw DOS time and date
date: number,
attributes: number, -- external attributes
-- central-directory lengths of the name and extra field (a fallback when the local header is wrong)
cdNameLen: number,
cdExtraLen: number,
}
-- ------------------------------------------------------------------------------------------------ read
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50
local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50
local function readu64(b: buffer, o: number): number
return readu32(b, o) + readu32(b, o + 4) * 4294967296
end
local function sigAt(b: buffer, o: number, sig: number): boolean
return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig
end
local function normalize(name: string): string
name = string.gsub(name, "\\", "/")
name = string.gsub(name, "^%./", "")
name = string.gsub(name, "^/+", "")
return name
end
local function basename(name: string): string
return string.match(name, "([^/]*)/*$") or name
end
-- junk that shares a basename with real files: macOS resource forks
local function isJunk(name: string): boolean
local l = string.lower(name)
return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._"
end
local Archive = {}
Archive.__index = Archive
-- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive)
function Zip.isZip(buf: buffer | string): boolean
local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf
return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD)
end
local function findEocd(b: buffer): number?
local n = buffer.len(b)
local fallback = nil
local stop = math.max(0, n - 22 - 65535)
for p = n - 22, stop, -1 do
if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then
if p + 22 + readu16(b, p + 20) == n then
return p
end
fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking
end
end
return fallback
end
local function parse(b: buffer): (any, Err.Err?)
local n = buffer.len(b)
if n < 22 then
return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record")
end
local eocd = findEocd(b)
if not eocd then
return nil, Err.new(Err.CORRUPT, "no end of central directory record")
end
local count = readu16(b, eocd + 10)
local cdSize = readu32(b, eocd + 12)
local cdOff = readu32(b, eocd + 16)
local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22)
local comment = buffer.readstring(b, eocd + 22, commentLen)
local cdEnd = eocd
-- ZIP64: the locator sits just before the end record
local zip64 = false
if sigAt(b, eocd - 20, SIG_Z64_LOC) then
local z = readu64(b, eocd - 20 + 8)
if not sigAt(b, z, SIG_Z64_EOCD) then
-- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data)
local guess = eocd - 20 - 56
if sigAt(b, guess, SIG_Z64_EOCD) then
z = guess
else
z = -1
end
end
if z >= 0 and z + 56 <= n then
zip64 = true
count = readu64(b, z + 32)
cdSize = readu64(b, z + 40)
cdOff = readu64(b, z + 48)
cdEnd = z
end
end
if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then
return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record")
end
-- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset
local delta = 0
if count > 0 and not sigAt(b, cdOff, SIG_CD) then
delta = cdEnd - (cdOff + cdSize)
if not sigAt(b, cdOff + delta, SIG_CD) then
return nil, Err.new(Err.CORRUPT, "central directory not found")
end
end
local entries: { any } = table.create(math.min(count, 65536))
local p = cdOff + delta
for i = 1, count do
if not sigAt(b, p, SIG_CD) or p + 46 > n then
return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p)
end
local flags = readu16(b, p + 8)
local method = readu16(b, p + 10)
local time, date = readu16(b, p + 12), readu16(b, p + 14)
local crc = readu32(b, p + 16)
local csize, usize = readu32(b, p + 20), readu32(b, p + 24)
local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32)
local disk = readu16(b, p + 34)
local off = readu32(b, p + 42)
if p + 46 + nameLen + extraLen + cmtLen > n then
return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p)
end
local raw = buffer.readstring(b, p + 46, nameLen)
-- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order
local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen
while q + 4 <= qe do
local id, sz = readu16(b, q), readu16(b, q + 2)
if id == 0x0001 then
local r, re = q + 4, math.min(q + 4 + sz, qe)
if usize == 0xFFFFFFFF and r + 8 <= re then
usize = readu64(b, r)
r += 8
end
if csize == 0xFFFFFFFF and r + 8 <= re then
csize = readu64(b, r)
r += 8
end
if off == 0xFFFFFFFF and r + 8 <= re then
off = readu64(b, r)
r += 8
end
if disk == 0xFFFF and r + 4 <= re then
disk = readu32(b, r)
end
end
q += 4 + sz
end
local name = normalize(raw)
entries[i] = {
name = name,
rawName = raw,
index = i,
size = usize,
compressedSize = csize,
crc32 = crc,
method = method,
flags = flags,
offset = off + delta,
isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\",
utf8 = bit32.band(flags, 0x800) ~= 0,
comment = buffer.readstring(b, qe, cmtLen),
modified = {
year = 1980 + bit32.rshift(date, 9),
month = bit32.band(bit32.rshift(date, 5), 15),
day = bit32.band(date, 31),
hour = bit32.rshift(time, 11),
min = bit32.band(bit32.rshift(time, 5), 63),
sec = bit32.band(time, 31) * 2,
},
mtime = Zip.unixTime(time, date),
time = time,
date = date,
attributes = readu32(b, p + 38),
cdNameLen = nameLen,
cdExtraLen = extraLen,
}
p = qe + cmtLen
end
local exact, lower, base = {}, {}, {}
for _, e in entries do
if not e.isDir then
exact[e.name] = exact[e.name] or e
local l = string.lower(e.name)
lower[l] = lower[l] or e
if not isJunk(e.name) then
local bn = basename(l)
local prev = base[bn]
-- prefer the shallowest path, then the first in directory order
if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then
base[bn] = e
end
end
end
end
return setmetatable({
buf = b,
entries = entries,
comment = comment,
zip64 = zip64,
_exact = exact,
_lower = lower,
_base = base,
}, Archive)
end
-- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a
-- part of a bigger buffer)
function Zip.open(src: any): (any, Err.Err?)
local b: buffer
if type(src) == "string" then
b = buffer.fromstring(src)
elseif type(src) == "buffer" then
b = src
elseif type(src) == "table" and type(src.buf) == "buffer" then
if src.base == 0 and src.limit == buffer.len(src.buf) then
b = src.buf
else
local n = math.max(0, src.limit - src.base)
b = buffer.create(n)
buffer.copy(b, 0, src.buf, src.base, n)
end
else
return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader")
end
local ok, res, err = pcall(parse, b)
if not ok then
return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")")
end
return res, err
end
-- every entry (directories included), in central directory order
function Archive.list(self: any): { Entry }
return self.entries
end
-- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename
-- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and
-- macOS "__MACOSX/" / "._" files never match by basename.
function Archive.find(self: any, name: string): Entry?
local n = normalize(name)
local e = self._exact[n]
if e then
return e
end
local l = string.lower(n)
e = self._lower[l]
if e then
return e
end
return self._base[basename(l)]
end
local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any)
local n = buffer.len(b)
if dataStart > n then
return nil, "data starts past the end"
end
if e.method == 0 then
if dataStart + e.size > n then
return nil, "truncated stored data"
end
local out = buffer.create(e.size)
buffer.copy(out, 0, b, dataStart, e.size)
return out
end
local len = math.min(e.compressedSize, n - dataStart)
local out, err = Deflate.inflate(b, dataStart, len, e.size)
if not out then
-- a wrong size in the directory: inflate without it and let the CRC decide
local out2 = Deflate.inflate(b, dataStart, n - dataStart)
if out2 then
return out2
end
return nil, if type(err) == "table" then err.message else tostring(err)
end
return out
end
-- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers
-- get the local extra length wrong)
function Zip._starts(b: buffer, e: Entry): { number }
local o = e.offset
local starts = {}
if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then
table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28))
end
local alt = o + 30 + e.cdNameLen + e.cdExtraLen
if alt ~= starts[1] then
table.insert(starts, alt)
end
if alt ~= o + 30 + e.cdNameLen then
table.insert(starts, o + 30 + e.cdNameLen)
end
return starts
end
-- read(entry | name, verify = true) -> buffer | nil, Err
function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?)
local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry
if not e then
return nil, Err.new(Err.ARG, "no entry " .. tostring(entry))
end
if e.isDir then
return buffer.create(0), nil
end
if bit32.band(e.flags, 1) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted")
end
if e.method ~= 0 and e.method ~= 8 then
return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method))
end
local b = self.buf
local n = buffer.len(b)
local o = e.offset
if o < 0 or o + 30 > n then
return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o)
end
local starts = Zip._starts(b, e)
local firstErr: string? = nil
local code = Err.CORRUPT
for _, s in starts do
local out, err = extract(b, e, s)
if out then
if verify == false then
return out, nil
end
if buffer.len(out) ~= e.size then
err = string.format("size %d, expected %d", buffer.len(out), e.size)
else
local c = Deflate.crc32(out)
if c == e.crc32 then
return out, nil
end
err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32)
end
end
firstErr = firstErr or err
end
return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr))
end
-- readString(entry | name, verify?) -> string | nil, Err
function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?)
local out, err = self:read(entry, verify)
if not out then
return nil, err
end
return buffer.tostring(out), nil
end
-- ------------------------------------------------------------------------------------------------ write
local Writer = {}
Writer.__index = Writer
export type AddOptions = {
method: ("deflate" | "store")?, -- default "deflate" (stored instead when deflate does not make it smaller)
level: number?, -- deflate level 0..9 (default 6)
mtime: number?, -- modification time, Unix seconds (UTC); default 1980-01-01 00:00:00 (reproducible output)
comment: string?,
utf8: boolean?, -- set the UTF-8 name flag (default: when the name is not plain ASCII)
attributes: number?, -- external attributes (default: Unix 0644 for files, 0755 + MS-DOS directory for dirs)
}
export type FinishOptions = {
comment: string?, -- the archive comment
zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them)
}
-- writer() -> Writer
function Zip.writer(): any
return setmetatable({ files = {} :: { any } }, Writer)
end
-- days from 1970-01-01 to y-m-d (proleptic Gregorian)
local function civil(z: number): (number, number, number)
z += 719468
local era = (if z >= 0 then z else z - 146096) // 146097
local doe = z - era * 146097
local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
local y = yoe + era * 400
local doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
local mp = (5 * doy + 2) // 153
local d = doy - (153 * mp + 2) // 5 + 1
local m = if mp < 10 then mp + 3 else mp - 9
return (if m <= 2 then y + 1 else y), m, d
end
local function daysFrom(y: number, m: number, d: number): number
y = if m <= 2 then y - 1 else y
local era = (if y >= 0 then y else y - 399) // 400
local yoe = y - era * 400
local mp = if m > 2 then m - 3 else m + 9
local doy = (153 * mp + 2) // 5 + d - 1
local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
return era * 146097 + doe - 719468
end
-- Unix seconds -> DOS time, date (clamped to 1980..2107)
function Zip.dosTime(t: number?): (number, number)
if type(t) ~= "number" or t ~= t then
return 0, 0x21
end
local s = math.floor(t)
local days = s // 86400
local rem = s - days * 86400
local y, m, d = civil(days)
if y < 1980 then
return 0, 0x21
elseif y > 2107 then
y, m, d, rem = 2107, 12, 31, 86399
end
local time = (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2
return time, (y - 1980) * 512 + m * 32 + d
end
-- DOS time, date -> Unix seconds (UTC)
function Zip.unixTime(time: number, date: number): number
local y = 1980 + bit32.rshift(date, 9)
local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12)
local d = math.clamp(bit32.band(date, 31), 1, 31)
return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2
end
local function isAscii(s: string): boolean
return string.find(s, "[\128-\255]") == nil
end
-- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string)
function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?)
if type(name) ~= "string" or name == "" or #name > 65535 then
return false, Err.new(Err.ARG, "add: bad entry name")
end
local b: buffer
if type(data) == "string" then
b = buffer.fromstring(data)
elseif type(data) == "buffer" then
b = data
elseif data == nil and string.sub(name, -1) == "/" then
b = buffer.create(0)
else
return false, Err.new(Err.ARG, "add: data must be a buffer or a string")
end
local o: AddOptions = opts or {}
local method = o.method or "deflate"
if method ~= "deflate" and method ~= "store" then
return false, Err.new(Err.ARG, "add: method must be deflate or store")
end
local isDir = string.sub(name, -1) == "/"
local n = buffer.len(b)
local comp, code = b, 0
if method == "deflate" and n > 0 and not isDir then
local z, zerr = Deflate.compress(b, { level = o.level or 6 })
if not z then
return false, zerr
end
if buffer.len(z) < n then
comp, code = z, 8
end
end
local time, date = Zip.dosTime(o.mtime)
table.insert(self.files, {
name = name,
method = code,
crc = if n > 0 then Crc32.of(b) else 0,
size = n,
data = comp,
dataOffset = 0,
dataLength = buffer.len(comp),
time = time,
date = date,
comment = o.comment or "",
utf8 = if o.utf8 ~= nil then o.utf8 else not isAscii(name),
attributes = o.attributes or (if isDir then 0x41ED0010 else 0x81A40000),
})
return true, nil
end
-- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err
function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?)
local b = archive.buf
local start: number? = nil
for _, s in Zip._starts(b, e) do
if s >= 0 and s + e.compressedSize <= buffer.len(b) then
start = s
break
end
end
if not start or bit32.band(e.flags, 1) ~= 0 then
return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data")
end
local name = newName or e.name
table.insert(self.files, {
name = name,
method = e.method,
crc = e.crc32,
size = e.size,
data = b,
dataOffset = start,
dataLength = e.compressedSize,
time = e.time or 0,
date = e.date or 0x21,
comment = e.comment or "",
utf8 = e.utf8 or not isAscii(name),
attributes = e.attributes or (if e.isDir then 0x41ED0010 else 0x81A40000),
})
return true, nil
end
-- finish(opts?) -> the archive | nil, Err
function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?)
local comment = opts and opts.comment or ""
if #comment > 65535 then
return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes")
end
local force = opts and opts.zip64 or false
local total = 22 + #comment + 98
for _, f in self.files do
total += 30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment
end
if total > 0x3FFFFFFF then
return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB")
end
local w = Bytes.writer(total)
local offsets = {}
for i, f in self.files do
local off = w:tell()
offsets[i] = off
local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF
local flags = if f.utf8 then 0x800 else 0
w:u32le(SIG_LOCAL)
w:u16le(if big then 45 else 20)
w:u16le(flags)
w:u16le(f.method)
w:u16le(f.time)
w:u16le(f.date)
w:u32le(f.crc)
w:u32le(if big then 0xFFFFFFFF else f.dataLength)
w:u32le(if big then 0xFFFFFFFF else f.size)
w:u16le(#f.name)
w:u16le(if big then 20 else 0)
w:string(f.name)
if big then
w:u16le(1)
w:u16le(16)
w:u64le(f.size)
w:u64le(f.dataLength)
end
w:bytes(f.data, f.dataOffset, f.dataLength)
end
local cdOff = w:tell()
for i, f in self.files do
local off = offsets[i]
local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF
local bigOff = force or off >= 0xFFFFFFFF
local extra = (if bigSize then 16 else 0) + (if bigOff then 8 else 0)
local version = if bigSize or bigOff then 45 else 20
w:u32le(SIG_CD)
w:u16le(0x0300 + version) -- made by: Unix
w:u16le(version)
w:u16le(if f.utf8 then 0x800 else 0)
w:u16le(f.method)
w:u16le(f.time)
w:u16le(f.date)
w:u32le(f.crc)
w:u32le(if bigSize then 0xFFFFFFFF else f.dataLength)
w:u32le(if bigSize then 0xFFFFFFFF else f.size)
w:u16le(#f.name)
w:u16le(if extra > 0 then extra + 4 else 0)
w:u16le(#f.comment)
w:u16le(0) -- disk
w:u16le(0) -- internal attributes
w:u32le(f.attributes)
w:u32le(if bigOff then 0xFFFFFFFF else off)
w:string(f.name)
if extra > 0 then
w:u16le(1)
w:u16le(extra)
if bigSize then
w:u64le(f.size)
w:u64le(f.dataLength)
end
if bigOff then
w:u64le(off)
end
end
w:string(f.comment)
end
local cdSize = w:tell() - cdOff
local count = #self.files
local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF
if z64 then
local rec = w:tell()
w:u32le(SIG_Z64_EOCD)
w:u64le(44)
w:u16le(0x032D)
w:u16le(45)
w:u32le(0)
w:u32le(0)
w:u64le(count)
w:u64le(count)
w:u64le(cdSize)
w:u64le(cdOff)
w:u32le(SIG_Z64_LOC)
w:u32le(0)
w:u64le(rec)
w:u32le(1)
end
w:u32le(SIG_EOCD)
w:u16le(0)
w:u16le(0)
w:u16le(if z64 then 0xFFFF else count)
w:u16le(if z64 then 0xFFFF else count)
w:u32le(if z64 then 0xFFFFFFFF else cdSize)
w:u32le(if z64 then 0xFFFFFFFF else cdOff)
w:u16le(#comment)
w:string(comment)
return w:finish(), nil
end
return Zip