rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+291
View File
@@ -0,0 +1,291 @@
--!strict
-- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data
-- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder
-- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be
-- encoded by any writable archive format through its list() / read().
--
-- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err
-- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 })
-- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end })
-- a:list() a:read("a.txt") a:add("c.txt", "text") a:write()
--
-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them
-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Tar = require("@rosetta/containers/Tar")
local Archive = {}
-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source
export type Entry = {
name: string,
size: number,
compressedSize: number?,
method: string?,
mtime: number?,
dir: boolean,
data: buffer?,
load: (() -> (buffer?, Err.Err?))?,
[string]: any,
}
export type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?)
local Methods = {}
Methods.__index = Methods
-- the public fields of an entry (no data / loader)
local function public(e: Entry): Types.ArchiveEntry
local out: any = {}
for k, v in e :: any do
if k ~= "data" and k ~= "load" then
out[k] = v
end
end
return out
end
function Methods.list(self: any): { Types.ArchiveEntry }
local out = table.create(#self._entries) :: { Types.ArchiveEntry }
for i, e in self._entries do
out[i] = public(e)
end
return out
end
-- read(name) -> buffer | nil, Err (directories read as an empty buffer)
function Methods.read(self: any, name: string): (buffer?, Err.Err?)
local e: Entry? = self._byName[name]
if not e then
return nil, Err.new(Err.ARG, "no entry named " .. tostring(name))
end
if e.data then
return e.data, nil
end
if e.load then
local ok, b, err = pcall(e.load)
if not ok then
return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b))
end
if not b then
return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed")
end
return b, nil
end
return buffer.create(0), nil
end
-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name
function Methods.add(self: any, name: string, data: buffer | string, opts: any?)
local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0)
local o = opts or {}
local e: Entry = {
name = name,
size = buffer.len(b),
dir = o.dir == true,
mtime = o.mtime,
mode = o.mode,
data = b,
}
Archive.put(self, e)
end
-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api)
function Methods.write(self: any, opts: any?): (buffer?, Err.Err?)
local enc: Encoder? = self._encode
if not enc then
return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only")
end
return enc(self, opts)
end
-- new(format, encode?) -> an empty Archive
function Archive.new(format: string, encode: Encoder?): any
return setmetatable({
kind = "archive",
format = format,
meta = {},
_entries = {} :: { Entry },
_byName = {} :: { [string]: Entry },
_encode = encode,
}, Methods)
end
-- put(archive, entry): append (or replace by name) an entry
function Archive.put(a: any, e: Entry)
local old = a._byName[e.name]
if old then
local i = table.find(a._entries, old)
if i then
a._entries[i] = e
end
else
table.insert(a._entries, e)
end
a._byName[e.name] = e
end
-- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another
-- format's): what encoders iterate. nil when the value is not an archive.
function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }?
if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then
return nil
end
local ok, list = pcall(value.list, value)
if not ok or type(list) ~= "table" then
return nil
end
local out = {}
for _, e in list do
if type(e) == "table" and type(e.name) == "string" then
table.insert(out, {
entry = e,
read = function(): (buffer?, Err.Err?)
local rok, b, err = pcall(value.read, value, e.name)
if not rok then
return nil, Err.new(Err.CORRUPT, tostring(b))
end
return b, err
end,
})
end
end
return out
end
-- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives)
function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
return function(): (buffer?, Err.Err?)
local out = buffer.create(n)
buffer.copy(out, 0, buf, at, n)
return out, nil
end
end
-- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read
-- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...)
function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?)
local items = Archive.entries(value)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive")
end
local out: { { entry: Types.ArchiveEntry, data: buffer } } = {}
for _, it in items do
local b: buffer = buffer.create(0)
if not it.entry.dir then
local d, err = it.read()
if not d then
return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed")
end
b = d
end
table.insert(out, { entry = it.entry, data = b })
end
return out, nil
end
-- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value,
-- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take.
function Archive.files(value: any, name: string?): ({ { name: string, data: buffer, entry: any } }?, Err.Err?)
if type(value) == "buffer" or type(value) == "string" then
local b = if type(value) == "string" then buffer.fromstring(value) else value
return { { name = name or "data", data = b, entry = { name = name or "data", size = buffer.len(b), dir = false } } }, nil
end
local items = Archive.entries(value)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
end
local out = {}
for _, it in items do
if not it.entry.dir then
local b, err = it.read()
if not b then
return nil, err
end
table.insert(out, { name = it.entry.name, data = b, entry = it.entry })
end
end
return out, nil
end
-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or
-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err
function Archive.streamData(value: any): (buffer?, Err.Err?)
if type(value) == "buffer" then
return value, nil
elseif type(value) == "string" then
return buffer.fromstring(value), nil
end
local items = Archive.entries(value)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
end
if #items == 1 and not items[1].entry.dir then
return items[1].read()
end
local list = {}
for _, it in items do
local e: any = it.entry
local data: buffer? = nil
if not e.dir and (e.type == nil or e.type == "0") then
local b, err = it.read()
if not b then
return nil, err
end
data = b
end
local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil
table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode })
end
return Tar.write(list)
end
-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store
-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date
function Archive.fromDos(stamp: number): number?
local time, date = stamp % 65536, stamp // 65536
local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31)
if date == 0 or m < 1 or m > 12 or d < 1 then
return nil
end
local secs = bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2
return Types.Date.daysFromCivil(y, m, d) * 86400 + secs
end
-- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31)
function Archive.toDos(t: number?): number
if type(t) ~= "number" or t ~= t or t < 315532800 then
return 0x210000 -- 1980-01-01 00:00
end
local s = math.floor(t)
local days = s // 86400
local rem = s - days * 86400
local y, m, d = Types.Date.civilFromDays(days)
if y > 2107 then
y, m, d, rem = 2107, 12, 31, 86398
end
return ((y - 1980) * 512 + m * 32 + d) * 65536 + (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2
end
-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension
-- (".tgz" -> ".tar"), else "data"
function Archive.streamName(opts: any?, exts: { string }): string
local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil
if not name then
return "data"
end
local base = string.match(name, "([^/\\]+)$") or name
local stem, ext = string.match(base, "^(.+)%.([%w]+)$")
if stem and ext then
local e = string.lower(ext)
if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then
return stem .. ".tar"
end
if table.find(exts, e) then
return stem
end
end
return base
end
return Archive
+519
View File
@@ -0,0 +1,519 @@
--!strict
-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone
-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another
-- format). New in rosetta.
-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped);
-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk;
-- adpcm_swf (Flash ADPCM, FLV SoundFormat 1) -> decoded through codecs/audio/Adpcm into a float WAV;
-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3");
-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames;
-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations);
-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout);
-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac;
-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED).
--
-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format })
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Mux = require("@rosetta/containers/Ogg/Mux")
local Adpcm = require("@rosetta/codecs/audio/Adpcm")
local AudioWrap = {}
type PacketSource = {
count: ((self: any, track: number) -> number)?,
get: ((self: any, track: number, k: number) -> Types.Packet?)?,
}
local function allPackets(dmx: PacketSource, track: Types.Track): { Types.Packet }
local out: { Types.Packet } = {}
local n = if dmx.count then dmx:count(track.id) else 0
if n > 0 and dmx.get then
for k = 1, n do
local p = dmx:get(track.id, k)
if p then
table.insert(out, p)
end
end
end
return out
end
local function concat(packets: { Types.Packet }, prefix: buffer?): buffer
local total = if prefix then buffer.len(prefix) else 0
for _, p in packets do
total += buffer.len(p.data)
end
local out = buffer.create(total)
local o = 0
if prefix then
buffer.copy(out, 0, prefix)
o = buffer.len(prefix)
end
for _, p in packets do
buffer.copy(out, o, p.data)
o += buffer.len(p.data)
end
return out
end
-- ------------------------------------------------------------------------------------------------ WAV
local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source)
pcm_u8 = { 1, 8, 0 },
pcm_s8 = { 1, 8, 0 },
pcm_s16le = { 1, 16, 0 },
pcm_s24le = { 1, 24, 0 },
pcm_s32le = { 1, 32, 0 },
pcm_s16be = { 1, 16, 1 },
pcm_s24be = { 1, 24, 1 },
pcm_s32be = { 1, 32, 1 },
pcm_f32le = { 3, 32, 0 },
pcm_f64le = { 3, 64, 0 },
pcm_f32be = { 3, 32, 1 },
pcm_f64be = { 3, 64, 1 },
pcm_alaw = { 6, 8, 0 },
pcm_mulaw = { 7, 8, 0 },
}
local function wav(fmt: buffer, data: buffer): buffer
local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64)
local fl = buffer.len(fmt)
local dl = buffer.len(data)
w:string("RIFF")
w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2))
w:string("WAVE")
w:string("fmt ")
w:u32le(fl)
w:bytes(fmt)
if fl % 2 == 1 then
w:u8(0)
end
w:string("data")
w:u32le(dl)
w:bytes(data)
if dl % 2 == 1 then
w:u8(0)
end
return w:finish()
end
local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
local spec = PCM[track.codec]
local ch = track.channels or 1
local rate = math.floor((track.sampleRate or 0) + 0.5)
if ch < 1 or rate <= 0 then
return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate")
end
local bits = spec[2]
local data = concat(packets)
if spec[3] == 1 then
local bps = bits // 8
for i = 0, buffer.len(data) - bps, bps do
for k = 0, bps // 2 - 1 do
local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k)
buffer.writeu8(data, i + k, b)
buffer.writeu8(data, i + bps - 1 - k, a)
end
end
end
if track.codec == "pcm_s8" then
for i = 0, buffer.len(data) - 1 do
buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256)
end
end
local f = Bytes.writer(16)
local align = ch * bits // 8
f:u16le(spec[1])
f:u16le(ch)
f:u32le(rate)
f:u32le(rate * align)
f:u16le(align)
f:u16le(bits)
return wav(f:finish(), data), nil
end
-- Flash ADPCM packets decode on their own (each starts with its code size and block headers): f32 samples in a WAV
local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
local ch = track.channels or 1
local rate = math.floor((track.sampleRate or 0) + 0.5)
if ch < 1 or ch > 2 or rate <= 0 then
return nil, Err.new(Err.CORRUPT, "Flash ADPCM track without channels / sample rate")
end
local frames = 0
for _, pk in packets do
frames += Adpcm.swfFrames(pk.data, 0, buffer.len(pk.data), ch)
end
local data = buffer.create(frames * ch * 4)
local d = 0
for _, pk in packets do
d += Adpcm.swf(pk.data, 0, buffer.len(pk.data), ch, data, d) * ch
end
local f = Bytes.writer(16)
f:u16le(3)
f:u16le(ch)
f:u32le(rate)
f:u32le(rate * ch * 4)
f:u16le(ch * 4)
f:u16le(32)
return wav(f:finish(), data), nil
end
-- ------------------------------------------------------------------------------------------------ Ogg
-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1)
local function opusSamples(b: buffer): number
local n = buffer.len(b)
if n < 1 then
return 0
end
local toc = buffer.readu8(b, 0)
local config = toc // 8
local fs: number
if config < 12 then
fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1]
elseif config < 16 then
fs = if config % 2 == 0 then 480 else 960
else
fs = ({ 120, 240, 480, 960 })[config % 4 + 1]
end
local c = toc % 4
local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2
return fs * frames
end
local function opusHead(track: Types.Track): buffer
local c = track.config
if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then
return c
end
local w = Bytes.writer(19)
w:string("OpusHead")
w:u8(1)
w:u8(math.clamp(track.channels or 2, 1, 2))
w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5))
w:u32le(math.floor(track.sampleRate or 48000))
w:u16le(0)
w:u8(0)
return w:finish()
end
local function opusTags(): buffer
local w = Bytes.writer(32)
w:string("OpusTags")
local vendor = "rosetta"
w:u32le(#vendor)
w:string(vendor)
w:u32le(0)
return w:finish()
end
local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer
local mux = Mux.new({ pageSize = 4096 })
local s = mux:stream(1)
for i, h in headers do
s:packet(h, 0, { flush = i == 1 or i == #headers })
end
for i, p in packets do
s:packet(p.data, granuleOf(p, i), { eos = i == #packets })
end
return mux:finish()
end
-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data)
local function xiphHeaders(c: buffer): { buffer }?
local n = buffer.len(c)
if n < 3 then
return nil
end
local count = buffer.readu8(c, 0) + 1
local p = 1
local sizes = {}
local total = 0
for k = 1, count - 1 do
local s = 0
while true do
if p >= n then
return nil
end
local b = buffer.readu8(c, p)
p += 1
s += b
if b ~= 255 then
break
end
end
sizes[k] = s
total += s
end
sizes[count] = n - p - total
if sizes[count] < 0 then
return nil
end
local out = {}
for k = 1, count do
local b = buffer.create(sizes[k])
buffer.copy(b, 0, c, p, sizes[k])
p += sizes[k]
out[k] = b
end
return out
end
-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the
-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0,
-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4
-- samples (the first one as if its previous block had its own size, as ffmpeg times it).
local function bit(b: buffer, k: number): number
return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1)
end
local function bits(b: buffer, k: number, n: number): number
local v = 0
for i = n - 1, 0, -1 do
v = v * 2 + bit(b, k + i)
end
return v
end
local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?)
if buffer.len(id) < 30 or buffer.len(setup) < 8 then
return nil, nil
end
local bs = buffer.readu8(id, 28)
local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) }
-- the framing bit: the highest set bit of the last non-zero byte
local last = buffer.len(setup) - 1
while last > 0 and buffer.readu8(setup, last) == 0 do
last -= 1
end
local v = buffer.readu8(setup, last)
local hb = 7
while hb > 0 and bit32.extract(v, hb, 1) == 0 do
hb -= 1
end
local f = last * 8 + hb
local flags: { boolean } = {}
local pos = f
while #flags < 64 and pos - 41 >= 7 * 8 do
local s0 = pos - 41
if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then
break
end
table.insert(flags, 1, bit(setup, s0) == 1)
pos = s0
end
-- the largest count whose 6-bit field matches
for n = #flags, 1, -1 do
local start = f - 41 * n
if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then
local out = {}
for i = #flags - n + 1, #flags do
table.insert(out, flags[i])
end
return sizes, out
end
end
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ ADTS
local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?)
local c = track.config
local profile, rateIndex, chanConfig
if c and buffer.len(c) >= 2 then
local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1)
profile = b0 // 8 -- audio object type
rateIndex = (b0 % 8) * 2 + b1 // 128
chanConfig = (b1 // 8) % 16
else
local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }
profile = 2
rateIndex = 4
for i, r in rates do
if r == math.floor((track.sampleRate or 44100) + 0.5) then
rateIndex = i - 1
end
end
chanConfig = track.channels or 2
end
if profile < 1 or profile > 4 or rateIndex > 12 then
return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS")
end
local w = Bytes.writer(64)
for _, p in packets do
local len = buffer.len(p.data) + 7
w:u8(0xFF)
w:u8(0xF1)
w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4)
w:u8((chanConfig % 4) * 64 + (len // 2048) % 4)
w:u8((len // 8) % 256)
w:u8((len % 8) * 32 + 0x1F)
w:u8(0xFC)
w:bytes(p.data)
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ trim
-- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's
-- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus
-- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding)
function AudioWrap.trim(dec: any, skip: number, length: number?): any
if skip <= 0 and length == nil then
return dec
end
skip = math.max(0, skip)
local rate = dec.sampleRate
local w: any = setmetatable({}, { __index = dec })
w.frames = math.max(0, (dec.frames or 0) - skip)
if length then
w.frames = if (dec.frames or 0) > 0 then math.min(w.frames, length) else length
end
w.duration = w.frames / rate
local cap = length or math.huge
local delivered = 0
local function drop()
local left = skip
while left > 0 do
local _, n = dec:read(math.min(left, 4096))
if not n or n <= 0 then
break
end
left -= n
end
end
local started = false
function w.read(_: any, n: number, out: buffer?): (buffer, number)
if not started then
started = true
drop()
end
local want = math.min(n, cap - delivered)
if want <= 0 then
return out or buffer.create(0), 0
end
local b, got = dec:read(want, out)
delivered += got
return b, got
end
function w.seek(_: any, seconds: number)
started = true
if seconds <= 0 then
dec:seek(0)
drop()
delivered = 0
else
dec:seek(seconds + skip / rate)
delivered = math.floor(seconds * rate + 0.5)
end
end
function w.position(_: any): number
return math.max(0, dec:position() - skip / rate)
end
return w
end
-- ------------------------------------------------------------------------------------------------ wrap
-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err
function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?)
if type(track) ~= "table" or track.kind ~= "audio" then
return nil, nil, Err.new(Err.ARG, "not an audio track")
end
if track.unsupported then
return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported)
end
local codec = track.codec
local packets = allPackets(dmx, track)
if #packets == 0 then
return nil, nil, Err.new(Err.CORRUPT, "audio track without packets")
end
if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then
return wav(track.waveFormat, concat(packets)), "wav", nil
end
if codec == "adpcm_swf" then
local b, err = swfWav(track, packets)
return b, if b then "wav" else nil, err
end
if PCM[codec] then
local b, err = pcmWav(track, packets)
return b, if b then "wav" else nil, err
end
if codec == "mp3" or codec == "mp2" or codec == "mp1" then
return concat(packets), "mp3", nil
end
if codec == "ac3" then
return concat(packets), "ac3", nil
end
if codec == "flac" then
local c = track.config
local prefix: buffer? = nil
if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then
prefix = c
elseif c and buffer.len(c) >= 34 then
-- metadata blocks without the marker (MP4 dfLa payload after version / flags)
local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0
local b = buffer.create(4 + buffer.len(c) - start)
buffer.writestring(b, 0, "fLaC")
buffer.copy(b, 4, c, start)
prefix = b
else
return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO")
end
return concat(packets, prefix), "flac", nil
end
if codec == "opus" then
local head = opusHead(track)
local pre = buffer.readu16(head, 10)
local g = pre
local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number
g += opusSamples(p.data)
local d = (p :: any).discardPadding
if type(d) == "number" and d > 0 then
return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding)
end
return g
end)
return out, "opus", nil
end
if codec == "vorbis" then
local c = track.config
local headers = c and xiphHeaders(c)
if not headers or #headers ~= 3 then
return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers")
end
local sizes, modes = vorbisModes(headers[1], headers[3])
local granule, prev = 0, nil :: number?
local rate = track.sampleRate or 44100
local scale = track.timescale
local out = ogg(headers, packets, function(p: Types.Packet): number
if not sizes or not modes then
return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times
end
local d = p.data
if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then
return granule
end
local mb = 0
while 2 ^ mb < #(modes :: { boolean }) do
mb += 1
end
local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0
local cur = sizes[if (modes :: { boolean })[m + 1] then 2 else 1]
if prev then
granule += (prev + cur) // 4
end
prev = cur
return granule
end)
return out, "vorbis", nil
end
if codec == "aac" then
if track.adts then
return concat(packets), "aac", nil -- already ADTS (MPEG-TS)
end
local b, err = adts(track, packets)
return b, if b then "aac" else nil, err
end
return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec))
end
return AudioWrap
+570
View File
@@ -0,0 +1,570 @@
--!strict
-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in rosetta.
-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk
-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets
-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included).
-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given.
--
-- local avi, err = Avi.read(buf, base, limit)
-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf
-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute
-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish()
-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW)
--
-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning).
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
local Avi = {}
export type Chunk = { offset: number, size: number, key: boolean }
export type Stream = {
index: number, -- 0-based stream number (the "##" of the chunk ids)
type: string, -- strh fccType: "vids", "auds", "txts", "mids"
handler: string,
flags: number,
scale: number,
rate: number,
start: number,
length: number,
suggestedBufferSize: number,
sampleSize: number,
frame: { number }, -- rcFrame left, top, right, bottom
strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...)
name: string?,
chunks: { Chunk },
}
export type File = {
avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number },
streams: { Stream },
odml: { totalFrames: number }?,
info: { [string]: string },
index: string, -- "odml" | "idx1" | "scan"
}
local function u32(b: buffer, o: number): number
return readu32(b, o)
end
-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not
-- entered); returns where it stopped
local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number
while p + 8 <= limit do
local id = readstring(b, p, 4)
local size = u32(b, p + 4)
local data = p + 8
local ltype: string? = nil
if (id == "LIST" or id == "RIFF") and data + 4 <= limit then
ltype = readstring(b, data, 4)
end
if data + size > limit then
size = limit - data
end
if fn(id, data, size, ltype) == false then
return p
end
p = data + size + (size % 2)
end
return p
end
local function streamNumber(id: string): number?
local a, b = string.byte(id, 1, 2)
if not a or not b then
return nil
end
local function hex(c: number): number?
if c >= 48 and c <= 57 then
return c - 48
elseif c >= 65 and c <= 70 then
return c - 55
elseif c >= 97 and c <= 102 then
return c - 87
end
return nil
end
local h, l = hex(a), hex(b)
if h and l then
return h * 16 + l
end
return nil
end
Avi.streamNumber = streamNumber
local function parseStrl(b: buffer, data: number, size: number, index: number): Stream
local s: Stream = {
index = index,
type = "",
handler = "",
flags = 0,
scale = 1,
rate = 1,
start = 0,
length = 0,
suggestedBufferSize = 0,
sampleSize = 0,
frame = { 0, 0, 0, 0 },
strf = buffer.create(0),
chunks = {},
}
local indx: { number }? = nil
walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean?
if id == "strh" and n >= 48 then
s.type = readstring(b, d, 4)
s.handler = readstring(b, d + 4, 4)
s.flags = u32(b, d + 8)
s.scale = u32(b, d + 20)
s.rate = u32(b, d + 24)
s.start = u32(b, d + 28)
s.length = u32(b, d + 32)
s.suggestedBufferSize = u32(b, d + 36)
s.sampleSize = u32(b, d + 44)
if n >= 56 then
s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) }
end
elseif id == "strf" then
local f = buffer.create(n)
buffer.copy(f, 0, b, d, n)
s.strf = f
elseif id == "strn" then
local str = readstring(b, d, n)
s.name = string.match(str, "^[^%z]*")
elseif id == "indx" and n >= 24 then
indx = { d, n }
end
return nil
end)
;(s :: any)._indx = indx
return s
end
-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s
local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean
if n < 24 or depth > 2 then
return false
end
local longsPerEntry = readu16(b, d)
local subType = readu8(b, d + 2)
local indexType = readu8(b, d + 3)
local entries = u32(b, d + 4)
if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration }
if longsPerEntry ~= 4 then
return false
end
local p = d + 24
for _ = 1, entries do
if p + 16 > d + n then
break
end
local off = u32(b, p) + u32(b, p + 4) * 4294967296
local size = u32(b, p + 8)
p += 16
if off > 0 and off + 8 <= limit then
local sz = math.min(u32(b, off + 4), limit - off - 8)
readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1)
end
end
return #s.chunks > 0
elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs)
if n < 24 then
return false
end
local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296
local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD
local p = d + 24
for _ = 1, entries do
if p + per > d + n then
break
end
local off = u32(b, p)
local size = u32(b, p + 4)
p += per
local key = size < 0x80000000
size %= 0x80000000
local at = base + off
if at >= 0 and at + size <= limit then
table.insert(s.chunks, { offset = at, size = size, key = key })
end
end
return true
end
return false
end
-- read(buf, base, limit) -> File | nil, Err
function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then
return nil, Err.new(Err.CORRUPT, "not an AVI file", base)
end
local file: File = {
avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 },
streams = {},
odml = nil,
info = {},
index = "scan",
}
local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end }
local idx1: { number }? = nil
local hdrl = false
-- every RIFF piece (AVI, then AVIX for OpenDML files)
walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean?
if id ~= "RIFF" then
return nil
end
walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean?
if cid == "LIST" and cltype == "hdrl" and not hdrl then
hdrl = true
local si = 0
walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean?
if hid == "avih" and hn >= 40 then
file.avih = {
microSecPerFrame = u32(b, hd),
flags = u32(b, hd + 12),
totalFrames = u32(b, hd + 16),
streams = u32(b, hd + 24),
width = u32(b, hd + 32),
height = u32(b, hd + 36),
}
elseif hid == "LIST" and hltype == "strl" then
table.insert(file.streams, parseStrl(b, hd, hn, si))
si += 1
elseif hid == "LIST" and hltype == "odml" then
walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean?
if oid == "dmlh" and on >= 4 then
file.odml = { totalFrames = u32(b, od) }
end
return nil
end)
end
return nil
end)
elseif cid == "LIST" and cltype == "movi" then
table.insert(movis, { cd, cd + cn })
elseif cid == "LIST" and cltype == "INFO" then
walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean?
file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or ""
return nil
end)
elseif cid == "idx1" and not idx1 then
idx1 = { cd, cn }
end
return nil
end)
return nil
end)
if not hdrl then
return nil, Err.new(Err.CORRUPT, "no hdrl list")
end
if #file.streams == 0 then
return nil, Err.new(Err.CORRUPT, "no streams")
end
-- 1. OpenDML indexes
local odml = true
for _, s in file.streams do
local ix = (s :: any)._indx
if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then
odml = false
end
end
if odml then
file.index = "odml"
else
for _, s in file.streams do
table.clear(s.chunks)
end
-- 2. idx1
local ok = false
if idx1 and movis[1] then
local d, n = idx1[1], idx1[2]
local count = n // 16
local moviBase = movis[1][1] -- the 'movi' fourcc
-- relative or absolute offsets: check the first entry that points at a chunk id
local rel = true
if count > 0 then
local off = u32(b, d + 8)
local ckid = readstring(b, d, 4)
local relAt, absAt = moviBase + off, base + off
if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then
rel = true
elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then
rel = false
end
end
for k = 0, count - 1 do
local e = d + k * 16
local ckid = readstring(b, e, 4)
local flags = u32(b, e + 4)
local off = u32(b, e + 8)
local size = u32(b, e + 12)
local sn = streamNumber(ckid)
local s = sn and file.streams[sn + 1]
if s and string.sub(ckid, 3, 4) ~= "pc" then
local at = (if rel then moviBase else base) + off + 8
if at + size <= limit then
table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 })
ok = true
end
end
end
end
if ok then
file.index = "idx1"
else
for _, s in file.streams do
table.clear(s.chunks)
end
-- 3. scan the movi lists
local function scan(d0: number, e0: number)
walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean?
if id == "LIST" and ltype == "rec " then
scan(d + 4, d + n)
return nil
end
local sn = streamNumber(id)
local s = sn and file.streams[sn + 1]
if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then
table.insert(s.chunks, { offset = d, size = n, key = true })
end
return nil
end)
end
for _, m in movis do
scan(m[1] + 4, m[2])
end
file.index = "scan"
end
end
for _, s in file.streams do
(s :: any)._indx = nil
end
return file, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WStream = {
type: string, -- "vids" | "auds"
handler: string, -- fccHandler (4 chars)
scale: number,
rate: number,
sampleSize: number, -- 0 = every chunk one sample (video, VBR audio)
strf: buffer,
name: string?,
width: number?,
height: number?,
quality: number?,
ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio)
}
export type WOptions = {
streams: { WStream },
microSecPerFrame: number,
width: number,
height: number,
software: string?,
}
-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order
function Avi.write(opts: WOptions, chunks: { { any } }): buffer
local ns = #opts.streams
local lengths = table.create(ns, 0)
local maxChunk = table.create(ns, 0)
local bytes = table.create(ns, 0)
local total = 0
for _, c in chunks do
local si, data = c[1], c[2]
local n = buffer.len(data)
local s = opts.streams[si]
if s.sampleSize > 0 then
lengths[si] += n // s.sampleSize
else
lengths[si] += 1
end
bytes[si] += n
if n > maxChunk[si] then
maxChunk[si] = n
end
total += n + 8 + (n % 2)
end
local frames = 0
for si, s in opts.streams do
if s.type == "vids" and frames == 0 then
frames = lengths[si]
end
end
local w = Bytes.writer(total + 4096 + #chunks * 16)
w:string("RIFF")
local riffSize = w:tell()
w:u32le(0)
w:string("AVI ")
-- hdrl
w:string("LIST")
local hdrlSize = w:tell()
w:u32le(0)
w:string("hdrl")
w:string("avih")
w:u32le(56)
local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1
local maxBytes = 0
for si = 1, ns do
maxBytes += bytes[si]
end
w:u32le(math.floor(opts.microSecPerFrame + 0.5))
w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0)
w:u32le(0) -- padding granularity
w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED
w:u32le(frames)
w:u32le(0) -- initial frames
w:u32le(ns)
local suggested = 0
for si = 1, ns do
suggested = math.max(suggested, maxChunk[si] + 8)
end
w:u32le(suggested)
w:u32le(opts.width)
w:u32le(opts.height)
for _ = 1, 4 do
w:u32le(0)
end
for si, s in opts.streams do
w:string("LIST")
local strlSize = w:tell()
w:u32le(0)
w:string("strl")
w:string("strh")
w:u32le(56)
w:string(s.type)
w:string(s.handler)
w:u32le(0) -- flags
w:u16le(0) -- priority
w:u16le(0) -- language
w:u32le(0) -- initial frames
w:u32le(s.scale)
w:u32le(s.rate)
w:u32le(0) -- start
w:u32le(lengths[si])
w:u32le(maxChunk[si])
w:u32le(if s.quality then s.quality else 0xFFFFFFFF)
w:u32le(s.sampleSize)
w:u16le(0)
w:u16le(0)
w:u16le(s.width or 0)
w:u16le(s.height or 0)
w:string("strf")
w:u32le(buffer.len(s.strf))
w:bytes(s.strf)
if buffer.len(s.strf) % 2 == 1 then
w:u8(0)
end
if s.name then
local nm = s.name .. "\0"
w:string("strn")
w:u32le(#nm)
w:string(nm)
if #nm % 2 == 1 then
w:u8(0)
end
end
w:setU32le(strlSize, w:tell() - strlSize - 4)
end
-- OpenDML extended header (total frames)
w:string("LIST")
w:u32le(16)
w:string("odml")
w:string("dmlh")
w:u32le(4)
w:u32le(frames)
w:setU32le(hdrlSize, w:tell() - hdrlSize - 4)
-- INFO
local sw = (opts.software or "rosetta") .. "\0"
if #sw % 2 == 1 then
sw ..= "\0"
end
w:string("LIST")
w:u32le(4 + 8 + #sw)
w:string("INFO")
w:string("ISFT")
w:u32le(#sw)
w:string(sw)
-- movi
w:string("LIST")
local moviSize = w:tell()
w:u32le(0)
local moviBase = w:tell()
w:string("movi")
local index = table.create(#chunks) :: { { any } }
for _, c in chunks do
local si, data, key = c[1], c[2], c[3]
local s = opts.streams[si]
local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb"))
local at = w:tell()
local n = buffer.len(data)
w:string(id)
w:u32le(n)
w:bytes(data)
if n % 2 == 1 then
w:u8(0)
end
table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n })
end
w:setU32le(moviSize, w:tell() - moviSize - 4)
-- idx1
w:string("idx1")
w:u32le(#index * 16)
for _, e in index do
w:string(e[1])
w:u32le(e[2])
w:u32le(e[3])
w:u32le(e[4])
end
w:setU32le(riffSize, w:tell() - 8)
return w:finish()
end
-- ------------------------------------------------------------------------------------------------ BITMAPINFO
export type BitmapInfo = {
width: number,
height: number, -- signed: > 0 = bottom-up rows
bits: number, -- biBitCount
compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB)
palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0
extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none
}
-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) |
-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries;
-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it.
function Avi.bitmapInfo(f: buffer): BitmapInfo?
local n = buffer.len(f)
if n < 40 then
return nil
end
local bits = readu16(f, 14)
local info: BitmapInfo = {
width = buffer.readi32(f, 4),
height = buffer.readi32(f, 8),
bits = bits,
compression = readstring(f, 16, 4),
}
if n > 40 then
local e = buffer.create(n - 40)
buffer.copy(e, 0, f, 40)
info.extra = e
if bits >= 1 and bits <= 8 then
local count = math.min(2 ^ bits, (n - 40) // 4)
local at = n - count * 4
if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then
at -= 9
end
local pal = buffer.create(1024)
for i = 0, count - 1 do
local o = at + i * 4
buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000)
end
info.palette = pal
end
end
return info
end
return Avi
+142
View File
@@ -0,0 +1,142 @@
--!strict
-- containers/Chunks: the generic walker for chunked files (a 4-byte id and a byte size per chunk, the body, optional
-- trailer and padding): RIFF / RIFX / RF64 (containers/Riff builds on it), IFF / AIFF / AIFC, PNG (size first, a
-- CRC trailer), CAF (64-bit sizes). Formats list their chunk handlers over the walked list instead of each writing
-- the loop. New in rosetta (the RIFF leniency comes from containers/Riff, absorbed from wav-luau).
--
-- local list = Chunks.walk(buf, from, limit, Chunks.IFF) -- { Chunk } (offsets absolute in buf)
-- local list = Chunks.walk(buf, from, limit, { sizeFirst = true, bigEndian = true, trailer = 4 }) -- PNG
-- for _, c in list do if c.id == "COMM" then ... c.offset, c.size, c.avail ... end end
-- local c = Chunks.find(list, "SSND")
--
-- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in
-- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers).
-- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one
-- byte earlier). layout.resize(id, declared) can replace a declared size (RF64's ds64). Never throws.
local Chunks = {}
export type Chunk = {
id: string,
start: number, -- the chunk header's offset
offset: number, -- the body's offset
size: number, -- the body size (after layout.resize / open-ended handling)
declared: number, -- the size field as written
avail: number, -- body bytes actually present (= size unless truncated)
truncated: boolean,
streamed: boolean, -- an open-ended chunk with size 0 / 0xFFFFFFFF
}
export type Layout = {
bigEndian: boolean?, -- size fields big-endian (default little)
sizeFirst: boolean?, -- the size comes before the id (PNG)
sizeBytes: number?, -- 4 (default) or 8
trailer: number?, -- bytes after the body that belong to the chunk (PNG: the 4-byte CRC)
pad: number?, -- bodies are padded to a multiple of this (RIFF / IFF: 2; default 1)
lenientPad: boolean?, -- detect odd bodies written without their pad byte
openEnded: { [string]: boolean }?,
resize: ((id: string, declared: number) -> number?)?,
maxChunks: number?, -- default 100000
}
Chunks.RIFF = table.freeze({ pad = 2, lenientPad = true }) :: Layout
Chunks.RIFX = table.freeze({ pad = 2, lenientPad = true, bigEndian = true }) :: Layout
Chunks.IFF = table.freeze({ pad = 2, bigEndian = true }) :: Layout
Chunks.PNG = table.freeze({ sizeFirst = true, bigEndian = true, trailer = 4 }) :: Layout
Chunks.CAF = table.freeze({ bigEndian = true, sizeBytes = 8 }) :: Layout
local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring
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
Chunks.printable4 = printable4
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
-- walk(b, p, limit, layout?) -> { Chunk } of [p, limit)
function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Chunk }
local L: Layout = layout or Chunks.RIFF
local be = L.bigEndian == true
local sizeBytes = L.sizeBytes or 4
local head = 4 + sizeBytes
local trailer = L.trailer or 0
local pad = L.pad or 1
local openEnded = L.openEnded
local resize = L.resize
local maxChunks = L.maxChunks or 100000
local list: { Chunk } = {}
limit = math.min(limit, buffer.len(b))
while p + head <= limit and #list < maxChunks do
local idAt = if L.sizeFirst then p + sizeBytes else p
local sizeAt = if L.sizeFirst then p else p + 4
local id = readstring(b, idAt, 4)
local declared
if sizeBytes == 8 then
local hi, lo = u32(b, sizeAt, be), u32(b, sizeAt + 4, be)
if not be then
hi, lo = lo, hi
end
declared = hi * 4294967296 + lo
else
declared = u32(b, sizeAt, be)
end
local size = declared
if resize then
size = resize(id, declared) or declared
end
local body = p + head
local avail = limit - body
local c: Chunk = {
id = id,
start = p,
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 + trailer > avail then
c.truncated = true -- (the body or its trailer runs past the end)
break
end
local rem = size % pad
local nextPos = body + size + trailer + (if rem > 0 then pad - rem else 0)
if L.lenientPad and rem > 0 and not printable4(b, nextPos, limit) and printable4(b, body + size + trailer, limit) then
nextPos = body + size + trailer
end
p = nextPos
end
return list
end
-- find(list, id, from?) -> the first chunk with that id at index >= from (default 1), its index
function Chunks.find(list: { Chunk }, id: string, from: number?): (Chunk?, number?)
for i = from or 1, #list do
if list[i].id == id then
return list[i], i
end
end
return nil, nil
end
return Chunks
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment),
-- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the
-- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the
-- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar
-- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks
-- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as
-- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The
-- archive formats (archive/cpio, archive/rpm's payload) build on it.
--
-- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err
-- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" })
--
-- Never throws: bad data returns nil, Err.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Cpio = {}
export type Entry = {
name: string,
size: number, -- data bytes (a symlink's target length; a hard link: the shared data's size)
mode: number, -- the whole st_mode (file type bits included)
type: string, -- tar type letters: "0" file, "5" directory, "2" symlink, "3" char device, "4" block device, "6" fifo, "s" socket
dir: boolean,
uid: number,
gid: number,
nlink: number,
mtime: number,
ino: number,
devmajor: number,
devminor: number,
rdevmajor: number,
rdevminor: number,
link: string?, -- symlink target
hardlink: string?, -- the first entry of this entry's hard link group (for the later links)
offset: number, -- absolute offset of the data in the buffer
check: number?, -- crc format: the stored byte sum
}
export type ReadOptions = {
maxEntries: number?, -- default 1e6
verify: boolean?, -- crc format: check the byte sums (default true)
}
export type Info = { format: string } -- "newc" | "crc" | "odc" | "bin" | "binbe"
local S_IFMT = 0xF000
local TYPES: { [number]: string } = {
[0x8000] = "0",
[0x4000] = "5",
[0xA000] = "2",
[0x2000] = "3",
[0x6000] = "4",
[0x1000] = "6",
[0xC000] = "s",
}
local MODES: { [string]: number } = {}
for m, t in TYPES do
MODES[t] = m
end
Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits
Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter
local TRAILER = "TRAILER!!!"
-- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset
function Cpio.format(b: buffer, o: number): string?
local n = buffer.len(b)
if o + 6 <= n then
local m = buffer.readstring(b, o, 6)
if m == "070701" then
return "newc"
elseif m == "070702" then
return "crc"
elseif m == "070707" then
return "odc"
end
end
if o + 2 <= n then
local v = buffer.readu16(b, o)
if v == 0x71C7 then
return "bin"
elseif v == 0xC771 then
return "binbe"
end
end
return nil
end
-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits
local function num(b: buffer, o: number, n: number, base: number): number?
local s = buffer.readstring(b, o, n)
if base == 16 then
if not string.find(s, "^%x+$") then
return nil
end
elseif not string.find(s, "^[0-7]+$") then
return nil
end
return tonumber(s, base)
end
-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32)
function Cpio.checksum(b: buffer, o: number, n: number): number
local s = 0
local i = o
local e = o + n
while i + 4 <= e do
local v = buffer.readu32(b, i)
s += bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24)
i += 4
end
while i < e do
s += buffer.readu8(b, i)
i += 1
end
return s % 4294967296
end
-- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err
local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?)
local h: any = {}
local nameAt
if fmt == "newc" or fmt == "crc" then
if p + 110 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
local f = {} :: { number }
for i = 1, 13 do
local v = num(b, p + 6 + (i - 1) * 8, 8, 16)
if not v then
return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8)
end
f[i] = v
end
h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7]
h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13]
nameAt = p + 110
elseif fmt == "odc" then
if p + 76 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 }
local f = {} :: { number }
local q = p + 6
for i, w in widths do
local v = num(b, q, w, 8)
if not v then
return nil, Err.new(Err.CORRUPT, "bad header field", q)
end
f[i] = v
q += w
end
h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10]
h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255)
h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255)
nameAt = p + 76
else
if p + 26 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
local be = fmt == "binbe"
local function u16(i: number): number
local v = buffer.readu16(b, p + i * 2)
return if be then bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) else v
end
local dev, rdev = u16(1), u16(7)
h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6)
h.mtime = u16(8) * 65536 + u16(9)
h.namesize = u16(10)
h.size = u16(11) * 65536 + u16(12)
h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255)
h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255)
nameAt = p + 26
end
if h.namesize < 1 or nameAt + h.namesize > e then
return nil, Err.new(if h.namesize < 1 then Err.CORRUPT else Err.TRUNCATED, "bad name size", nameAt)
end
h.nameAt = nameAt
return h, nil
end
-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
local o = offset or 0
local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
local maxEntries = (opts and opts.maxEntries) or 1e6
local verify = not (opts and opts.verify == false)
local fmt = Cpio.format(b, o)
if not fmt or o >= e then
return nil, Err.new(Err.CORRUPT, "not a cpio archive", o)
end
local align = if fmt == "newc" or fmt == "crc" then 4 elseif fmt == "odc" then 1 else 2
local out: { Entry } = {}
local groups: { [string]: { Entry } } = {}
local p = o
while true do
if p >= e then
return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p)
end
if Cpio.format(b, p) ~= fmt then
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
end
local h, herr = header(b, p, e, fmt)
if not h then
return nil, herr
end
local name = buffer.readstring(b, h.nameAt, h.namesize)
local z = string.find(name, "\0", 1, true)
if z then
name = string.sub(name, 1, z - 1)
end
local data = h.nameAt + h.namesize
data = o + (data - o + align - 1) // align * align
if name == TRAILER then
break
end
if data + h.size > e then
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data)
end
local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0"
local entry: Entry = {
name = name,
size = h.size,
mode = h.mode,
type = typ,
dir = typ == "5",
uid = h.uid,
gid = h.gid,
nlink = h.nlink,
mtime = h.mtime,
ino = h.ino,
devmajor = h.devmajor,
devminor = h.devminor,
rdevmajor = h.rdevmajor,
rdevminor = h.rdevminor,
link = if typ == "2" then buffer.readstring(b, data, h.size) else nil,
hardlink = nil,
offset = data,
check = if fmt == "crc" then h.check else nil,
}
if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then
return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data)
end
if typ == "0" and h.nlink > 1 then
local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino
local g = groups[key]
if not g then
g = {}
groups[key] = g
else
entry.hardlink = g[1].name
end
table.insert(g, entry)
end
table.insert(out, entry)
if #out > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
p = data + h.size
p = o + (p - o + align - 1) // align * align
end
-- hard links: the links stored without data read the group's data (newc / crc keep it on the last link)
for _, g in groups do
local holder: Entry? = nil
for _, x in g do
if x.size > 0 then
holder = x
end
end
if holder then
for _, x in g do
if x.size == 0 then
x.size, x.offset = holder.size, holder.offset
end
end
end
end
return out, { format = fmt }
end
-- ------------------------------------------------------------------------------------------------ writing
export type WriteEntry = {
name: string,
data: buffer?, -- file data (a symlink: its target, else taken from link)
mode: number?, -- st_mode; permission bits alone get the type bits from type / dir (default 0o644 / 0o755)
type: string?, -- a type letter (see Entry.type); default "0" ("5" for dir)
dir: boolean?,
link: string?, -- symlink target
uid: number?,
gid: number?,
nlink: number?, -- default 1 (2 for directories)
mtime: number?, -- unix seconds (default 0)
ino: number?, -- default: the entry's index (1, 2, ...); hard links share one
devmajor: number?,
devminor: number?,
rdevmajor: number?,
rdevminor: number?,
}
export type WriteOptions = {
format: ("newc" | "crc" | "odc")?, -- default "newc"
block: number?, -- pad the archive to a multiple of this many bytes (default 512; 1 = no padding)
}
local function hex8(v: number): string?
if v < 0 or v % 1 ~= 0 or v >= 4294967296 then
return nil
end
return string.format("%08X", v)
end
local function oct(v: number, w: number): string?
if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then
return nil
end
local s = string.format("%o", v)
return string.rep("0", w - #s) .. s
end
-- write(entries, opts?) -> buffer | nil, Err
function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
local fmt = (opts and opts.format) or "newc"
if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then
return nil, Err.new(Err.ARG, "format must be newc, crc or odc")
end
local block = (opts and opts.block) or 512
if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then
return nil, Err.new(Err.ARG, "block must be a positive integer")
end
-- newc / crc: a hard link group's data goes on its last link only
local last: { [string]: number } = {}
local prepared: { any } = table.create(#entries)
for i, e in entries do
if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
end
local typ = e.type or (if e.dir then "5" else "0")
local tbits = MODES[typ]
if not tbits then
return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ))
end
local mode = e.mode or (if typ == "5" then 0x1ED elseif typ == "2" then 0x1FF else 0x1A4)
if bit32.band(mode, S_IFMT) == 0 then
mode = bit32.bor(mode, tbits)
end
local data = e.data
if typ == "2" and not data then
data = buffer.fromstring(e.link or "")
elseif typ ~= "0" and typ ~= "2" then
data = nil
end
local nlink = e.nlink or (if typ == "5" then 2 else 1)
local ino = e.ino or i
local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ }
prepared[i] = p
if typ == "0" and nlink > 1 then
last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i
end
end
local w = Bytes.writer(1024)
local function put(name: string, p: any, data: buffer): Err.Err?
local e = p.e
local namesize = #name + 1
local size = buffer.len(data)
if fmt == "odc" then
local dev = (e.devmajor or 0) * 256 + (e.devminor or 0)
local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0)
local fields = {
oct(dev, 6),
oct(p.ino, 6),
oct(p.mode, 6),
oct(e.uid or 0, 6),
oct(e.gid or 0, 6),
oct(p.nlink, 6),
oct(rdev, 6),
oct(math.floor(e.mtime or 0), 11),
oct(namesize, 6),
oct(size, 11),
}
for k = 1, 10 do
if not fields[k] then
return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header")
end
end
w:string("070707" .. table.concat(fields :: { string }))
w:string(name)
w:u8(0)
w:bytes(data)
else
local check = if fmt == "crc" and p.typ == "0" then Cpio.checksum(data, 0, size) else 0
local fields = {
hex8(p.ino),
hex8(p.mode),
hex8(e.uid or 0),
hex8(e.gid or 0),
hex8(p.nlink),
hex8(math.floor(e.mtime or 0)),
hex8(size),
hex8(e.devmajor or 0),
hex8(e.devminor or 0),
hex8(e.rdevmajor or 0),
hex8(e.rdevminor or 0),
hex8(namesize),
hex8(check),
}
for k = 1, 13 do
if not fields[k] then
return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header")
end
end
w:string((if fmt == "crc" then "070702" else "070701") .. table.concat(fields :: { string }))
w:string(name)
w:u8(0)
w:fill(0, (4 - (110 + namesize) % 4) % 4)
w:bytes(data)
w:fill(0, (4 - size % 4) % 4)
end
return nil
end
for i, p in prepared do
local data = p.data
if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then
local e = p.e
if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then
data = buffer.create(0)
end
end
local err = put(p.e.name, p, data)
if err then
return nil, err
end
end
local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0))
if err then
return nil, err
end
w:fill(0, (block - w.pos % block) % block)
return w:finish(), nil
end
return Cpio
+296
View File
@@ -0,0 +1,296 @@
--!strict
-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4).
-- New in rosetta. A container parses its file once into an index of packets (track, pts, dts, duration,
-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives
-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file
-- independently), a file-order cursor, keyframe seeking, packet copies on demand.
--
-- local d = Demux.new("mkv", tracks, src, meta)
-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order
-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src
-- d:finish() -- durations, per-track indexes
-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i)
local Types = require("@rosetta/Types")
local Demux = {}
local D = {}
D.__index = D
export type Demux = typeof(setmetatable(
{} :: {
kind: "demuxer",
format: string,
tracks: { Types.Track },
duration: number,
startTime: number,
meta: { [string]: any },
src: buffer,
n: number,
tr: { number },
pts: { number },
dts: { number },
dur: { number },
key: { boolean },
off: { number },
len: { number },
data: { [number]: buffer },
extra: { [number]: { [string]: any } },
byTrack: { [number]: { number } },
cur: { [number]: number },
gcur: number,
},
D
))
-- new(format, tracks, src, meta?) -> an empty index
function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux
return setmetatable({
kind = "demuxer" :: "demuxer",
format = format,
tracks = tracks,
duration = 0,
startTime = 0,
meta = meta or {},
src = src,
n = 0,
tr = {},
pts = {},
dts = {},
dur = {},
key = {},
off = {},
len = {},
data = {},
extra = {},
byTrack = {},
cur = {},
gcur = 1,
}, D)
end
-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length)
function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number)
local i = self.n + 1
self.n = i
self.tr[i] = track
self.pts[i] = pts
self.dts[i] = dts or pts
self.dur[i] = duration or 0
self.key[i] = keyframe
self.off[i] = offset
self.len[i] = length
end
-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes
function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer)
self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data))
self.data[self.n] = data
end
-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...)
function D.setExtra(self: Demux, key: string, value: any)
local e = self.extra[self.n]
if not e then
e = {}
self.extra[self.n] = e
end
e[key] = value
end
-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's
-- frame rate), and the track / file durations (seconds) where the container gave none
function D.finish(self: Demux)
local byTrack: { [number]: { number } } = {}
for _, t in self.tracks do
byTrack[t.id] = {}
end
for i = 1, self.n do
local list = byTrack[self.tr[i]]
if list then
table.insert(list, i)
end
end
self.byTrack = byTrack
local total = self.duration
local start = math.huge
for _, t in self.tracks do
local list = byTrack[t.id]
local scale = if t.timescale and t.timescale > 0 then t.timescale else 1
t.timescale = scale
local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0
-- durations from the next packet in presentation order
if #list > 0 then
local order = table.clone(list)
table.sort(order, function(a: number, b: number): boolean
return self.pts[a] < self.pts[b]
end)
for k = 1, #order do
local i = order[k]
if self.dur[i] <= 0 then
local nx = order[k + 1]
if nx and self.pts[nx] > self.pts[i] then
self.dur[i] = self.pts[nx] - self.pts[i]
elseif frameTicks > 0 then
self.dur[i] = frameTicks
elseif k > 1 then
self.dur[i] = self.dur[order[k - 1]]
end
end
end
local first, last = order[1], order[#order]
if t.kind == "video" or t.kind == "audio" then
start = math.min(start, self.pts[first] / scale)
end
local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale
if not t.duration or t.duration <= 0 then
t.duration = d
end
t.frames = t.frames or #list
end
if t.duration and t.duration > total then
total = t.duration
end
self.cur[t.id] = 1
end
self.duration = total
-- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count
-- frame times from it
self.startTime = if start ~= math.huge and start > 0 then start else 0
end
-- the Packet for index entry i (a copy of its bytes)
function D._packet(self: Demux, i: number): Types.Packet
local data = self.data[i]
if not data then
local o, l = self.off[i], self.len[i]
local src = self.src
local n = buffer.len(src)
if o < 0 or o > n then
o, l = n, 0
elseif o + l > n then
l = n - o
end
data = buffer.create(l)
buffer.copy(data, 0, src, o, l)
end
local p: any = {
track = self.tr[i],
pts = self.pts[i],
dts = self.dts[i],
duration = self.dur[i],
keyframe = self.key[i],
data = data :: buffer,
}
local e = self.extra[i]
if e then
for k, v in e do
p[k] = v
end
end
return p
end
-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end
function D.read(self: Demux, track: number?): Types.Packet?
if track == nil then
local i = self.gcur
if i > self.n then
return nil
end
self.gcur = i + 1
return self:_packet(i)
end
local list = self.byTrack[track]
if not list then
return nil
end
local c = self.cur[track] or 1
local i = list[c]
if not i then
return nil
end
self.cur[track] = c + 1
return self:_packet(i)
end
-- packets(track?) -> an iterator of Packets from the current position (advancing it)
function D.packets(self: Demux, track: number?): () -> Types.Packet?
return function(): Types.Packet?
return self:read(track)
end
end
-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors
function D.count(self: Demux, track: number): number
local list = self.byTrack[track]
return if list then #list else 0
end
function D.get(self: Demux, track: number, k: number): Types.Packet?
local list = self.byTrack[track]
local i = list and list[k]
if not i then
return nil
end
return self:_packet(i)
end
-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy)
function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?)
local list = self.byTrack[track]
local i = list and list[k]
if not i then
return nil, nil, nil, nil, nil
end
return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i]
end
-- rewind(track?): a track's cursor (or every cursor) back to the start
function D.rewind(self: Demux, track: number?)
if track then
self.cur[track] = 1
return
end
for id in self.cur do
self.cur[id] = 1
end
self.gcur = 1
end
-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest)
function D.seek(self: Demux, seconds: number)
local g = self.n + 1
for _, t in self.tracks do
local list = self.byTrack[t.id]
if list and #list > 0 then
local target = seconds * t.timescale
local best = 1
for k = 1, #list do
local i = list[k]
if self.key[i] and self.pts[i] <= target + 1e-6 then
best = k
end
end
self.cur[t.id] = best
if list[best] < g then
g = list[best]
end
end
end
self.gcur = if g > self.n then 1 else g
end
-- track(kind) -> the first default track of the kind, else the first of the kind
function D.track(self: Demux, kind: string): Types.Track?
local first = nil
for _, t in self.tracks do
if t.kind == kind then
if t.default then
return t
end
first = first or t
end
end
return first
end
return Demux
+335
View File
@@ -0,0 +1,335 @@
--!strict
-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in rosetta.
-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it;
-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats,
-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and
-- minimal-length value elements.
--
-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated
-- for id, off, size in Ebml.children(buf, off, limit) do ... end
-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish()
--
-- Never throws: malformed input gives nil (readers) or stops iteration.
local Bytes = require("@rosetta/core/Bytes")
local readu8 = buffer.readu8
local Ebml = {}
Ebml.UNKNOWN = -1
-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1.
function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?)
if pos >= limit then
return nil, nil
end
local b = readu8(buf, pos)
if b == 0 then
return nil, nil
end
local len = 1
local mask = 0x80
while bit32.band(b, mask) == 0 do
len += 1
mask = mask // 2
end
if pos + len > limit then
return nil, nil
end
local v = bit32.band(b, mask - 1)
local allOnes = v == mask - 1
for i = 1, len - 1 do
local c = readu8(buf, pos + i)
v = v * 256 + c
if c ~= 255 then
allOnes = false
end
end
if allOnes then
return -1, len
end
return v, len
end
-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil
function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?)
local v, len = Ebml.vint(buf, pos, limit)
if v == nil or len == nil then
return nil, nil
end
if v == -1 then
return nil, nil
end
return v - (2 ^ (7 * len - 1) - 1), len
end
-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes)
function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?)
if pos >= limit then
return nil, nil
end
local b = readu8(buf, pos)
local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0
if len == 0 or pos + len > limit then
return nil, nil
end
local v = b
for i = 1, len - 1 do
v = v * 256 + readu8(buf, pos + i)
end
return v, len
end
-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil
function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?)
local id, il = Ebml.id(buf, pos, limit)
if not id or not il then
return nil, nil, nil
end
local size, sl = Ebml.vint(buf, pos + il, limit)
if not size or not sl then
return nil, nil, nil
end
return id, size, pos + il + sl
end
-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the
-- limit is clipped; a malformed header ends the iteration)
function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number)
local pos = off
return function(): (number?, number, number)
if pos >= limit then
return nil, 0, 0
end
local id, size, data = Ebml.header(buf, pos, limit)
if not id or not size or not data then
pos = limit
return nil, 0, 0
end
if size < 0 or data + size > limit then
size = limit - data
end
pos = data + size
return id, data, size
end
end
-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements)
function Ebml.uint(buf: buffer, off: number, len: number): number
local v = 0
for i = 0, math.min(len, 8) - 1 do
v = v * 256 + readu8(buf, off + i)
end
return v
end
function Ebml.int(buf: buffer, off: number, len: number): number
if len <= 0 then
return 0
end
local v = Ebml.uint(buf, off, len)
local n = math.min(len, 8)
if readu8(buf, off) >= 0x80 then
v -= 2 ^ (8 * n)
end
return v
end
function Ebml.float(buf: buffer, off: number, len: number): number
local r = Bytes.reader(buf, off, len)
if len == 4 then
return r:f32be()
elseif len == 8 then
return r:f64be()
end
return 0
end
function Ebml.string(buf: buffer, off: number, len: number): string
local s = buffer.readstring(buf, off, len)
local z = string.find(s, "\0", 1, true)
if z then
s = string.sub(s, 1, z - 1)
end
return s
end
function Ebml.binary(buf: buffer, off: number, len: number): buffer
local b = buffer.create(len)
buffer.copy(b, 0, buf, off, len)
return b
end
-- ------------------------------------------------------------------------------------------------ writing
local W = {}
W.__index = W
export type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W))
-- writer(capacity?) -> an EBML byte builder
function Ebml.writer(capacity: number?): Writer
return setmetatable({ w = Bytes.writer(capacity or 65536) }, W)
end
-- idBytes(id) -> the ID's bytes as written
local function writeId(w: Bytes.Writer, id: number)
if id >= 0x1000000 then
w:u32be(id)
elseif id >= 0x10000 then
w:u24be(id)
elseif id >= 0x100 then
w:u16be(id)
else
w:u8(id)
end
end
-- size as a minimal vint (n bytes: force a length)
local function writeSize(w: Bytes.Writer, size: number, n: number?)
local len = n or 1
if not n then
while size >= 2 ^ (7 * len) - 1 do
len += 1
end
end
local v = size + 2 ^ (7 * len) -- the marker bit
local bytes = table.create(len, 0)
for i = len, 1, -1 do
bytes[i] = v % 256
v = v // 256
end
for i = 1, len do
w:u8(bytes[i])
end
end
Ebml.writeSize = writeSize
-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers)
function Ebml.vintString(v: number, n: number?): string
local w = Bytes.writer(8)
writeSize(w, v, n)
return buffer.readstring(w:finish(), 0, w:tell())
end
function W.tell(self: Writer): number
return self.w:tell()
end
-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder
function W.open(self: Writer, id: number): number
writeId(self.w, id)
local at = self.w:tell()
for _ = 1, 8 do
self.w:u8(0)
end
return at
end
-- close(handle): patches the size of the element opened at handle
function W.close(self: Writer, at: number)
local w = self.w
local v = w:tell() - at - 8
w:setU8(at, 0x01)
for i = 7, 1, -1 do
w:setU8(at + i, v % 256)
v = v // 256
end
end
-- unknownSize(id): a master element with an unknown size (live streams)
function W.openUnknown(self: Writer, id: number)
writeId(self.w, id)
self.w:u8(0x01)
for _ = 1, 7 do
self.w:u8(0xFF)
end
end
function W.uint(self: Writer, id: number, v: number)
local n = 1
while v >= 2 ^ (8 * n) and n < 8 do
n += 1
end
writeId(self.w, id)
writeSize(self.w, n)
local bytes = table.create(n, 0)
local x = v
for i = n, 1, -1 do
bytes[i] = x % 256
x = x // 256
end
for i = 1, n do
self.w:u8(bytes[i])
end
end
function W.int(self: Writer, id: number, v: number)
local n = 1
while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do
n += 1
end
local u = if v < 0 then v + 2 ^ (8 * n) else v
writeId(self.w, id)
writeSize(self.w, n)
local bytes = table.create(n, 0)
for i = n, 1, -1 do
bytes[i] = u % 256
u = u // 256
end
for i = 1, n do
self.w:u8(bytes[i])
end
end
function W.float(self: Writer, id: number, v: number)
writeId(self.w, id)
writeSize(self.w, 8)
self.w:f64be(v)
end
function W.string(self: Writer, id: number, s: string)
writeId(self.w, id)
writeSize(self.w, #s)
self.w:string(s)
end
-- binary(id, buf, off?, len?)
function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?)
local o = off or 0
local n = len or (buffer.len(b) - o)
writeId(self.w, id)
writeSize(self.w, n)
self.w:bytes(b, o, n)
end
-- raw bytes (a pre-built element, block headers)
function W.raw(self: Writer, s: string)
self.w:string(s)
end
function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?)
local o = off or 0
self.w:bytes(b, o, len or (buffer.len(b) - o))
end
-- element header for a binary element whose payload follows in pieces: id + size
function W.header(self: Writer, id: number, size: number)
writeId(self.w, id)
writeSize(self.w, size)
end
-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space
function W.void(self: Writer, n: number)
self.w:u8(0xEC)
if n - 2 < 127 then
writeSize(self.w, n - 2, 1)
for _ = 1, n - 2 do
self.w:u8(0)
end
else
writeSize(self.w, n - 9, 8)
for _ = 1, n - 9 do
self.w:u8(0)
end
end
end
function W.finish(self: Writer): buffer
return self.w:finish()
end
return Ebml
+707
View File
@@ -0,0 +1,707 @@
--!strict
-- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories
-- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names,
-- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images
-- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from
-- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout.
--
-- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message
-- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/")
-- local data, err = Fat.read(vol, entry) -- buffer | nil, message
-- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image
--
-- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by
-- the cluster count (loops are errors).
local Archive = require("@rosetta/containers/Archive")
local Fat = {}
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
export type Volume = {
b: buffer,
base: number, -- byte offset of the volume (partition) in b
limit: number,
bps: number, -- bytes per sector
spc: number, -- sectors per cluster
fatOffset: number, -- byte offset of the first FAT (relative to base)
fatSize: number, -- bytes per FAT
rootOffset: number, -- FAT12 / 16: the fixed root directory
rootEntries: number,
rootCluster: number, -- FAT32
dataOffset: number, -- byte offset of cluster 2
clusters: number, -- data clusters
bits: number, -- 12 / 16 / 32
label: string?,
oem: string,
media: number,
partition: number?,
}
export type Entry = {
name: string,
dir: boolean,
size: number,
mtime: number?,
cluster: number,
attr: number,
shortName: string,
}
-- ------------------------------------------------------------------------------------------------ open
local function bpbAt(b: buffer, o: number, len: number): (Volume?, string?)
if len < 512 then
return nil, "truncated: smaller than a boot sector"
end
local jump = readu8(b, o)
local bps = readu16(b, o + 11)
local spc = readu8(b, o + 13)
if (jump ~= 0xEB and jump ~= 0xE9 and jump ~= 0xE8) or (bps ~= 512 and bps ~= 1024 and bps ~= 2048 and bps ~= 4096) then
return nil, "no FAT boot sector"
end
if spc == 0 or bit32.band(spc, spc - 1) ~= 0 then
return nil, "bad sectors per cluster"
end
local reserved, nfats, rootEntries = readu16(b, o + 14), readu8(b, o + 16), readu16(b, o + 17)
local total = readu16(b, o + 19)
if total == 0 then
total = readu32(b, o + 32)
end
local fatSectors = readu16(b, o + 22)
local fat32 = fatSectors == 0
if fat32 then
fatSectors = readu32(b, o + 36)
end
if reserved == 0 or nfats == 0 or fatSectors == 0 or total == 0 then
return nil, "bad BPB"
end
local rootSectors = math.ceil(rootEntries * 32 / bps)
local dataSector = reserved + nfats * fatSectors + rootSectors
if dataSector >= total then
return nil, "bad BPB: no data area"
end
local clusters = (total - dataSector) // spc
local bits = if clusters < 4085 then 12 elseif clusters < 65525 then 16 else 32
if fat32 and bits ~= 32 then
bits = 32 -- some small FAT32 volumes (mkfs.fat -F 32 on tiny images) are FAT32 regardless of the count
end
if total * bps > len then
-- images cut short at the last used sector are common: allow, reads past the end fail
total = len // bps
end
local labelAt = if bits == 32 then 71 else 43
local sig = readu8(b, o + (if bits == 32 then 66 else 38))
local label: string? = if sig == 0x29 then (string.gsub(buffer.readstring(b, o + labelAt, 11), " +$", "")) else nil
if label == "NO NAME" or label == "" then
label = nil
end
return {
b = b,
base = o,
limit = o + len,
bps = bps,
spc = spc,
fatOffset = reserved * bps,
fatSize = fatSectors * bps,
rootOffset = (reserved + nfats * fatSectors) * bps,
rootEntries = rootEntries,
rootCluster = if bits == 32 then readu32(b, o + 44) else 0,
dataOffset = dataSector * bps,
clusters = clusters,
bits = bits,
label = label,
oem = buffer.readstring(b, o + 3, 8),
media = readu8(b, o + 21),
}, nil
end
export type OpenOptions = { partition: number? } -- 1..4: the MBR partition (default: the first FAT one)
local FAT_TYPES = { [0x01] = true, [0x04] = true, [0x06] = true, [0x0B] = true, [0x0C] = true, [0x0E] = true, [0x11] = true, [0x14] = true, [0x16] = true, [0x1B] = true, [0x1C] = true, [0x1E] = true }
function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Volume?, string?)
local o: OpenOptions = opts or {}
off = math.max(0, off)
len = math.min(len, buffer.len(b) - off)
if len < 512 then
return nil, "truncated: smaller than a boot sector"
end
if not o.partition then
local v = bpbAt(b, off, len)
if v then
return v, nil
end
end
-- an MBR: 0x55AA and four partition entries
if readu8(b, off + 510) ~= 0x55 or readu8(b, off + 511) ~= 0xAA then
return nil, "no FAT boot sector and no partition table"
end
for i = 1, 4 do
local e = off + 446 + (i - 1) * 16
local ptype = readu8(b, e + 4)
local lba, count = readu32(b, e + 8), readu32(b, e + 12)
if (o.partition == i or (not o.partition and FAT_TYPES[ptype])) and ptype ~= 0 then
if lba * 512 >= len then
return nil, "truncated: partition " .. i .. " starts past the end"
end
local v, err = bpbAt(b, off + lba * 512, math.min(count * 512, len - lba * 512))
if v then
v.partition = i
end
return v, err
end
end
return nil, if o.partition then "no partition " .. o.partition else "no FAT partition"
end
-- ------------------------------------------------------------------------------------------------ chains
local function nextCluster(v: Volume, c: number): number
local f = v.base + v.fatOffset
if v.bits == 12 then
local p = f + c + c // 2
if p + 1 >= v.limit then
return 0xFFFFFFF
end
local w = readu16(v.b, p)
local n = if c % 2 == 0 then bit32.band(w, 0xFFF) else bit32.rshift(w, 4)
return if n >= 0xFF8 then 0xFFFFFFF elseif n == 0xFF7 then 0xFFFFFF7 else n
elseif v.bits == 16 then
local p = f + c * 2
if p + 2 > v.limit then
return 0xFFFFFFF
end
local n = readu16(v.b, p)
return if n >= 0xFFF8 then 0xFFFFFFF elseif n == 0xFFF7 then 0xFFFFFF7 else n
end
local p = f + c * 4
if p + 4 > v.limit then
return 0xFFFFFFF
end
return bit32.band(readu32(v.b, p), 0x0FFFFFFF)
end
-- the clusters of a chain (nil, message when it leaves the volume or loops)
local function chainOf(v: Volume, first: number, maxClusters: number): ({ number }?, string?)
local out = {}
local c = first
while c >= 2 and c < 0xFFFFFF7 do
if c >= v.clusters + 2 then
return nil, "cluster " .. c .. " outside the volume"
end
table.insert(out, c)
if #out > maxClusters then
return nil, "cluster chain loops"
end
c = nextCluster(v, c)
end
if c == 0xFFFFFF7 then
return nil, "bad cluster in a chain"
end
return out, nil
end
local function clusterOffset(v: Volume, c: number): number
return v.base + v.dataOffset + (c - 2) * v.spc * v.bps
end
-- the bytes of a chain, up to size bytes (nil = the whole chain)
local function readChain(v: Volume, first: number, size: number?): (buffer?, string?)
local csize = v.spc * v.bps
local maxClusters = if size then math.ceil(size / csize) + 1 else v.clusters
local list, err = chainOf(v, first, math.min(maxClusters, v.clusters + 1))
if not list then
return nil, err
end
local total = if size then size else #list * csize
if #list * csize < total then
return nil, "file data ends early (chain of " .. #list .. " clusters for " .. total .. " bytes)"
end
local out = buffer.create(total)
local o = 0
for _, c in list do
local n = math.min(csize, total - o)
if n <= 0 then
break
end
local at = clusterOffset(v, c)
if at + n > v.limit then
return nil, "truncated: cluster " .. c .. " past the end of the image"
end
buffer.copy(out, o, v.b, at, n)
o += n
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ directories
local function latin1(s: string): string
if not string.find(s, "[\128-\255]") then
return s
end
local out = table.create(#s)
for i = 1, #s do
out[i] = utf8.char(string.byte(s, i))
end
return table.concat(out)
end
local function shortChecksum(raw: string): number
local sum = 0
for i = 1, 11 do
sum = (bit32.rshift(sum, 1) + bit32.lshift(bit32.band(sum, 1), 7) + string.byte(raw, i)) % 256
end
return sum
end
local function ucs2(b: buffer, o: number, n: number, out: { number })
for k = 0, n - 1 do
table.insert(out, readu16(b, o + k * 2))
end
end
-- the entries of one directory's bytes
local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry }
local lfn: { [number]: { number } } = {}
local lfnSum, lfnCount = -1, 0
local subdirs = {}
for p = 0, buffer.len(d) - 32, 32 do
local first = readu8(d, p)
if first == 0 then
break
end
local attr = readu8(d, p + 11)
if first == 0xE5 then
lfn, lfnSum, lfnCount = {}, -1, 0
elseif attr == 0x0F then
local seq = bit32.band(first, 0x3F)
if bit32.band(first, 0x40) ~= 0 then
lfn, lfnCount = {}, seq
lfnSum = readu8(d, p + 13)
end
if seq >= 1 and seq <= 20 and readu8(d, p + 13) == lfnSum then
local chars = {}
ucs2(d, p + 1, 5, chars)
ucs2(d, p + 14, 6, chars)
ucs2(d, p + 28, 2, chars)
lfn[seq] = chars
end
else
local raw = buffer.readstring(d, p, 11)
if first == 0x05 then
raw = "\229" .. string.sub(raw, 2)
end
local long: string? = nil
if lfnCount > 0 and lfnSum == shortChecksum(buffer.readstring(d, p, 11)) then
local cps = {}
local complete = true
for s = 1, lfnCount do
if not lfn[s] then
complete = false
break
end
for _, c in lfn[s] do
if c == 0 or c == 0xFFFF then
break
end
table.insert(cps, c)
end
end
if complete then
local parts = table.create(#cps)
for i, c in cps do
parts[i] = utf8.char(if c >= 0xD800 and c < 0xE000 then 0xFFFD else c)
end
long = table.concat(parts)
end
end
lfn, lfnSum, lfnCount = {}, -1, 0
local nt = readu8(d, p + 12)
local base = string.gsub(string.sub(raw, 1, 8), " +$", "")
local ext = string.gsub(string.sub(raw, 9, 11), " +$", "")
if bit32.band(nt, 0x08) ~= 0 then
base = string.lower(base)
end
if bit32.band(nt, 0x10) ~= 0 then
ext = string.lower(ext)
end
local short = latin1(if ext ~= "" then base .. "." .. ext else base)
local isDir = bit32.band(attr, 0x10) ~= 0
local isLabel = bit32.band(attr, 0x08) ~= 0
if not isLabel and short ~= "." and short ~= ".." then
local name = prefix .. (long or short)
local cluster = readu16(d, p + 26) + readu16(d, p + 20) * 65536
local e: Entry = {
name = if isDir then name .. "/" else name,
dir = isDir,
size = if isDir then 0 else readu32(d, p + 28),
mtime = Archive.fromDos(readu16(d, p + 24) * 65536 + readu16(d, p + 22)),
cluster = cluster,
attr = attr,
shortName = short,
}
table.insert(out, e)
if isDir then
table.insert(subdirs, e)
end
end
end
end
return subdirs
end
-- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents)
function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?)
local out: { Entry } = {}
local limit = maxEntries or 65536
local root: buffer?, err: string?
if v.bits == 32 then
root, err = readChain(v, v.rootCluster, nil)
else
local n = v.rootEntries * 32
if v.base + v.rootOffset + n > v.limit then
return nil, "truncated: root directory past the end"
end
root = buffer.create(n)
buffer.copy(root :: buffer, 0, v.b, v.base + v.rootOffset, n)
end
if not root then
return nil, err
end
local seen: { [number]: boolean } = {}
local function walk(d: buffer, prefix: string, depth: number): string?
if depth > 64 then
return "directories nested too deep"
end
local start = #out
local subdirs = parseDir(d, prefix, out)
if #out > limit then
return "limit: more than maxEntries entries"
end
local _ = start
for _, s in subdirs do
if s.cluster >= 2 then
if seen[s.cluster] then
return "directory loop at cluster " .. s.cluster
end
seen[s.cluster] = true
local sd, serr = readChain(v, s.cluster, nil)
if not sd then
return s.name .. ": " .. tostring(serr)
end
local werr = walk(sd, s.name, depth + 1)
if werr then
return werr
end
end
end
return nil
end
local werr = walk(root :: buffer, "", 0)
if werr then
return nil, werr
end
return out, nil
end
-- read(vol, entry) -> the file's bytes
function Fat.read(v: Volume, e: Entry): (buffer?, string?)
if e.dir or e.size == 0 then
return buffer.create(0), nil
end
if e.cluster < 2 then
return nil, "file without clusters"
end
return readChain(v, e.cluster, e.size)
end
-- ------------------------------------------------------------------------------------------------ write
export type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? }
export type WriteOptions = {
size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440)
label: string?, -- volume label (default none)
serial: number?, -- volume serial number (default 0x12345678)
}
local GEOMETRY = {
[360] = { sectors = 720, spc = 2, root = 112, media = 0xFD, fat = 2, spt = 9, heads = 2 },
[720] = { sectors = 1440, spc = 2, root = 112, media = 0xF9, fat = 3, spt = 9, heads = 2 },
[1200] = { sectors = 2400, spc = 1, root = 224, media = 0xF9, fat = 7, spt = 15, heads = 2 },
[1440] = { sectors = 2880, spc = 1, root = 224, media = 0xF0, fat = 9, spt = 18, heads = 2 },
[2880] = { sectors = 5760, spc = 2, root = 240, media = 0xF0, fat = 9, spt = 36, heads = 2 },
}
local VALID83 = "^[%w!#%$%%&'%(%)%-@%^_`{}~]+$"
local function toDos(t: number?): (number, number)
local v = Archive.toDos(t)
return v // 65536, v % 65536
end
type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number }
-- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed
local function shortName(name: string, used: { [string]: boolean }): (string, number, boolean)
local base, ext = string.match(name, "^(.*)%.([^%.]*)$")
if not base or base == "" then
base, ext = name, ""
end
local b, e = base :: string, ext :: string
-- a plain 8.3 name, all upper or all lower case per part: no long name needed
if #b <= 8 and #e <= 3 and string.match(b, VALID83) and (e == "" or string.match(e, VALID83)) then
local bu, eu = string.upper(b), string.upper(e)
local nt = 0
local ok = true
if b ~= bu then
if b == string.lower(b) then
nt = bit32.bor(nt, 0x08)
else
ok = false
end
end
if e ~= eu then
if e == string.lower(e) then
nt = bit32.bor(nt, 0x10)
else
ok = false
end
end
local raw = bu .. string.rep(" ", 8 - #bu) .. eu .. string.rep(" ", 3 - #eu)
if ok and not used[raw] then
used[raw] = true
return raw, nt, false
end
end
local function clean(s: string): string
s = string.upper((string.gsub(s, "[%s%.]", "")))
return (string.gsub(s, "[^%w!#%$%%&'%(%)%-@%^_`{}~]", "_"))
end
local cb, ce = clean(b), string.sub(clean(e), 1, 3)
if cb == "" then
cb = "_"
end
for n = 1, 999999 do
local tail = "~" .. n
local raw = string.sub(cb, 1, 8 - #tail) .. tail
raw = raw .. string.rep(" ", 8 - #raw) .. ce .. string.rep(" ", 3 - #ce)
if not used[raw] then
used[raw] = true
return raw, 0, true
end
end
return " ___", 0, true
end
-- the directory entries (32 bytes each) of a node's children
local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label: string?): buffer
local w = {}
local function entry(raw: string, attr: number, nt: number, cluster: number, size: number, mtime: number?)
local e = buffer.create(32)
buffer.writestring(e, 0, raw)
buffer.writeu8(e, 11, attr)
buffer.writeu8(e, 12, nt)
local date, time = toDos(mtime)
buffer.writeu16(e, 14, time)
buffer.writeu16(e, 16, date)
buffer.writeu16(e, 18, date)
buffer.writeu16(e, 22, time)
buffer.writeu16(e, 24, date)
buffer.writeu16(e, 26, cluster)
buffer.writeu32(e, 28, size)
table.insert(w, e)
end
if isRoot and label then
local l = string.sub(string.upper(label), 1, 11)
entry(l .. string.rep(" ", 11 - #l), 0x08, 0, 0, 0, n.mtime)
end
if not isRoot then
entry(". ", 0x10, 0, n.cluster, 0, n.mtime)
entry(".. ", 0x10, 0, parentCluster, 0, n.mtime)
end
local used: { [string]: boolean } = {}
for _, c in n.children do
local raw, nt, needLong = shortName(c.name, used)
if needLong then
local cps = {}
if utf8.len(c.name) then
for _, cp in utf8.codes(c.name) do
table.insert(cps, if cp > 0xFFFF then 0x5F else cp)
end
else
for i = 1, #c.name do
table.insert(cps, (string.byte(c.name, i)))
end
end
local count = math.ceil(#cps / 13)
local sum = shortChecksum(raw)
for s = count, 1, -1 do
local e = buffer.create(32)
buffer.writeu8(e, 0, if s == count then bit32.bor(s, 0x40) else s)
buffer.writeu8(e, 11, 0x0F)
buffer.writeu8(e, 13, sum)
local slots = { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 }
for k = 1, 13 do
local i = (s - 1) * 13 + k
local v = if i <= #cps then cps[i] elseif i == #cps + 1 then 0 else 0xFFFF
buffer.writeu16(e, slots[k], v)
end
table.insert(w, e)
end
end
entry(raw, if c.dir then 0x10 else 0x20, nt, c.cluster, if c.dir then 0 else buffer.len(c.data or buffer.create(0)), c.mtime)
end
local out = buffer.create(#w * 32)
for i, e in w do
buffer.copy(out, (i - 1) * 32, e)
end
return out
end
-- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths)
function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?)
local o: WriteOptions = opts or {}
local g = GEOMETRY[o.size or 1440]
if not g then
return nil, "size must be 360, 720, 1200, 1440 or 2880"
end
local bps = 512
local root: Node = { name = "", dir = true, children = {}, byName = {}, cluster = 0 }
local function node(path: string, isDir: boolean): (Node?, string?)
local cur = root
local parts = string.split(path, "/")
for i, p in parts do
if p ~= "" and p ~= "." then
if p == ".." then
return nil, "'..' in a path"
end
local last = i == #parts or (i == #parts - 1 and parts[#parts] == "")
local child: Node? = cur.byName[string.lower(p)]
if not child then
local nc: Node = { name = p, dir = isDir or not last, children = {}, byName = {}, cluster = 0 }
cur.byName[string.lower(p)] = nc
table.insert(cur.children, nc)
child = nc
elseif not child.dir and (not last or isDir) then
return nil, p .. " is both a file and a directory"
end
cur = child :: Node
end
end
return cur, nil
end
for _, f in files do
local n, err = node(f.name, f.dir == true)
if not n then
return nil, err
end
if n ~= root then
n.mtime = f.mtime
if not n.dir then
n.data = f.data or buffer.create(0)
end
end
end
local csize = g.spc * bps
local dataSector = 1 + 2 * g.fat + g.root * 32 // bps
local clusters = (g.sectors - dataSector) // g.spc
local img = buffer.create(g.sectors * bps)
local fat = buffer.create(g.fat * bps)
local nextFree = 2
local function setFat(c: number, v: number)
local p = c + c // 2
local w = buffer.readu16(fat, p)
if c % 2 == 0 then
w = bit32.bor(bit32.band(w, 0xF000), v)
else
w = bit32.bor(bit32.band(w, 0x000F), bit32.lshift(v, 4))
end
buffer.writeu16(fat, p, w)
end
local function alloc(bytes: number): number?
local n = math.max(1, math.ceil(bytes / csize))
if nextFree + n - 1 > clusters + 1 then
return nil
end
local first = nextFree
for k = 0, n - 1 do
setFat(first + k, if k == n - 1 then 0xFFF else first + k + 1)
end
nextFree += n
return first
end
-- clusters: files get theirs first; a directory's size depends on its entries (long names), so measure first
local function place(n: Node): string?
for _, c in n.children do
if c.dir then
local size = buffer.len(dirEntries(c, 0, false, nil))
local cl = alloc(size)
if not cl then
return "disk full"
end
c.cluster = cl
local err = place(c)
if err then
return err
end
elseif c.data and buffer.len(c.data) > 0 then
local cl = alloc(buffer.len(c.data))
if not cl then
return "disk full"
end
c.cluster = cl
local at = (dataSector + (cl - 2) * g.spc) * bps
buffer.copy(img, at, c.data)
end
end
return nil
end
local perr = place(root)
if perr then
return nil, "limit: " .. perr
end
local function writeDirs(n: Node, parent: number): string?
for _, c in n.children do
if c.dir then
local d = dirEntries(c, parent, false, nil)
buffer.copy(img, (dataSector + (c.cluster - 2) * g.spc) * bps, d)
local err = writeDirs(c, c.cluster)
if err then
return err
end
end
end
return nil
end
writeDirs(root, 0)
local rootDir = dirEntries(root, 0, true, o.label)
if buffer.len(rootDir) > g.root * 32 then
return nil, "limit: too many entries in the root directory"
end
buffer.copy(img, (1 + 2 * g.fat) * bps, rootDir)
setFat(0, 0xF00 + g.media)
setFat(1, 0xFFF)
buffer.copy(img, bps, fat)
buffer.copy(img, (1 + g.fat) * bps, fat)
-- boot sector
buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU")
buffer.writeu16(img, 11, bps)
buffer.writeu8(img, 13, g.spc)
buffer.writeu16(img, 14, 1)
buffer.writeu8(img, 16, 2)
buffer.writeu16(img, 17, g.root)
buffer.writeu16(img, 19, g.sectors)
buffer.writeu8(img, 21, g.media)
buffer.writeu16(img, 22, g.fat)
buffer.writeu16(img, 24, g.spt)
buffer.writeu16(img, 26, g.heads)
buffer.writeu8(img, 36, 0)
buffer.writeu8(img, 38, 0x29)
buffer.writeu32(img, 39, o.serial or 0x12345678)
local label = string.upper(string.sub(o.label or "NO NAME", 1, 11))
buffer.writestring(img, 43, label .. string.rep(" ", 11 - #label) .. "FAT12 ")
buffer.writestring(img, 62, "\244\235\253") -- hlt; jmp $ (no boot code)
buffer.writeu8(img, 510, 0x55)
buffer.writeu8(img, 511, 0xAA)
return img, nil
end
return Fat
+525
View File
@@ -0,0 +1,525 @@
--!strict
-- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary,
-- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross
-- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is
-- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names
-- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the
-- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE
-- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock
-- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog
-- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet
-- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns
-- the stored bytes), UDF, writing.
--
-- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err
-- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents)
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Text = require("@rosetta/codecs/text/Text")
local Iso9660 = {}
export type Extent = { at: number, size: number } -- byte offset (from the image start) and length
export type Entry = {
name: string, -- the path, "/" separated, no leading "/"
dir: boolean,
size: number,
extents: { Extent },
mtime: number?, -- unix seconds
type: string, -- tar letters: "0" file, "5" directory, "2" symlink, "3" / "4" devices, "6" fifo, "s" socket
mode: number?, -- Rock Ridge: the permission bits
uid: number?,
gid: number?,
nlink: number?,
link: string?, -- Rock Ridge symlink target
rdev: number?, -- Rock Ridge PN: high * 2^32 + low
hidden: boolean?,
interleaved: boolean?,
zisofs: boolean?,
}
export type ReadOptions = {
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
maxEntries: number?, -- default 1e6
}
local SECTOR = 2048
local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" }
-- ------------------------------------------------------------------------------------------------ fields
local function u16(b: buffer, o: number): number
return buffer.readu16(b, o)
end
local function u32(b: buffer, o: number): number
return buffer.readu32(b, o)
end
local function str(b: buffer, o: number, n: number): string
return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", ""))
end
-- a 7-byte directory record date -> unix seconds
local function recDate(b: buffer, o: number): number?
local y = buffer.readu8(b, o)
local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2)
if m < 1 or m > 12 or d < 1 or d > 31 then
return nil
end
local off = buffer.readi8(b, o + 6)
return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 })
end
-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds
local function longDate(b: buffer, o: number): number?
local s = buffer.readstring(b, o, 16)
local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$")
if not y or tonumber(y) == 0 then
return nil
end
local off = buffer.readi8(b, o + 16)
return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 })
end
-- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge
type Susp = { [string]: any }
-- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } }
local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } }
local out = {}
while o + 4 <= e do
local sig = buffer.readstring(b, o, 2)
local len = buffer.readu8(b, o + 2)
if len < 4 or o + len > e then
break
end
if sig == "ST" then
break
elseif sig == "CE" and len >= 28 then
local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20)
local at = base + blk * bs + off
budget[1] -= 1
if budget[1] < 0 or at < base or at + n > limit or n > 65536 then
break
end
-- the rest of this area first, then the continuation (it holds what did not fit)
local rest = suspEntries(b, base, limit, o + len, e, bs, budget)
for _, x in rest do
table.insert(out, x)
end
local cont = suspEntries(b, base, limit, at, at + n, bs, budget)
for _, x in cont do
table.insert(out, x)
end
return out
end
table.insert(out, { sig, o, len })
o += len
end
return out
end
-- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs }
local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp
local rr: Susp = {}
local name: { string }? = nil
local slParts: { string }? = nil
local slRoot = false
local slCont = false
for _, x in suspEntries(b, base, limit, o, e, bs, { 32 }) do
local sig, at, len = x[1], x[2], x[3]
if sig == "NM" and len >= 5 then
local flags = buffer.readu8(b, at + 4)
if bit32.band(flags, 6) == 0 then
name = name or {}
table.insert(name :: { string }, buffer.readstring(b, at + 5, len - 5))
end
elseif sig == "PX" and len >= 36 then
rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28)
elseif sig == "PN" and len >= 20 then
rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12)
elseif sig == "TF" and len >= 5 then
local flags = buffer.readu8(b, at + 4)
local w = if bit32.band(flags, 0x80) ~= 0 then 17 else 7
local q = at + 5
for bit = 0, 6 do
if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then
if q + w > at + len then
break
end
if bit == 1 then
rr.mtime = if w == 17 then longDate(b, q) else recDate(b, q)
end
q += w
end
end
elseif sig == "SL" and len >= 5 then
slParts = slParts or {}
local parts = slParts :: { string }
local q = at + 5
while q + 2 <= at + len do
local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1)
if q + 2 + cl > at + len then
break
end
local piece = if bit32.band(cf, 2) ~= 0 then "." elseif bit32.band(cf, 4) ~= 0 then ".." else buffer.readstring(b, q + 2, cl)
if bit32.band(cf, 8) ~= 0 then
slRoot = #parts == 0
piece = ""
end
if slCont and #parts > 0 then
parts[#parts] ..= piece
elseif bit32.band(cf, 8) == 0 or #parts > 0 then
table.insert(parts, piece)
end
slCont = bit32.band(cf, 1) ~= 0
q += 2 + cl
end
elseif sig == "CL" and len >= 12 then
rr.child = u32(b, at + 4)
elseif sig == "RE" then
rr.relocated = true
elseif sig == "ZF" then
rr.zisofs = true
end
end
if name then
rr.name = table.concat(name)
end
if slParts then
rr.link = (if slRoot then "/" else "") .. table.concat(slParts, "/")
end
return rr
end
-- ------------------------------------------------------------------------------------------------ directories
type Record = {
name: string,
dir: boolean,
lba: number,
size: number,
ear: number,
flags: number,
interleave: boolean,
mtime: number?,
rr: Susp?,
}
-- the records of a directory extent (without "." and "..") | nil, Err
local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?)
if at + size > limit then
return nil, Err.new(Err.TRUNCATED, "directory past the end", at)
end
local out: { Record } = {}
local p = at
local e = at + size
while p < e do
local len = buffer.readu8(b, p)
if len == 0 then
p = at + ((p - at) // SECTOR + 1) * SECTOR -- the rest of the sector is padding
continue
end
if len < 34 or p + len > e then
return nil, Err.new(Err.CORRUPT, "bad directory record", p)
end
local nl = buffer.readu8(b, p + 32)
if 33 + nl > len then
return nil, Err.new(Err.CORRUPT, "bad name length", p + 32)
end
local raw = buffer.readstring(b, p + 33, nl)
if raw ~= "\0" and raw ~= "\1" then
local flags = buffer.readu8(b, p + 25)
local name
if joliet then
name = Text.utf16(b, p + 33, nl, true)
else
name = raw
end
name = string.gsub(name, ";%d*$", "")
if not joliet and bit32.band(flags, 2) == 0 then
name = string.gsub(name, "%.$", "")
end
local r: Record = {
name = name,
dir = bit32.band(flags, 2) ~= 0,
lba = u32(b, p + 2),
size = u32(b, p + 10),
ear = buffer.readu8(b, p + 1),
flags = flags,
interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0,
mtime = recDate(b, p + 18),
rr = nil,
}
if rrSkip then
local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + rrSkip
r.rr = rockRidge(b, base, limit, su, p + len, bs)
end
table.insert(out, r)
end
p += len
end
return out, nil
end
-- the root record of a volume descriptor at vd -> lba, size
local function root(b: buffer, vd: number): (number, number)
return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10)
end
-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length
local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number, bs: number): number?
local p = base + lba * bs
if p + 34 > limit then
return nil
end
local len = buffer.readu8(b, p)
local nl = buffer.readu8(b, p + 32)
local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0)
if len < 34 or su + 7 > p + len or p + len > limit then
return nil
end
if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then
return buffer.readu8(b, su + 6)
end
return nil
end
-- ------------------------------------------------------------------------------------------------ El Torito
local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }?
if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then
return nil
end
local cat = u32(b, vd + 0x47)
local p = base + cat * bs
local info: { [string]: any } = { catalog = cat }
if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then
return info
end
local sum = 0
for i = 0, 30, 2 do
sum += u16(b, p + i)
end
info.valid = sum % 65536 == 0
info.platform = buffer.readu8(b, p + 1)
info.id = str(b, p + 4, 24)
local d = p + 32
info.bootable = buffer.readu8(b, d) == 0x88
info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk
info.loadSegment = u16(b, d + 2)
info.systemType = buffer.readu8(b, d + 4)
info.sectors = u16(b, d + 6) -- 512-byte virtual sectors
info.lba = u32(b, d + 8)
return info
end
-- ------------------------------------------------------------------------------------------------ read
-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
local base = offset or 0
local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base)))
local o: ReadOptions = opts or {}
local maxEntries = o.maxEntries or 1e6
local pvd: number? = nil
local svd: number? = nil
local jolietLevel: number? = nil
local bootInfo = nil
local p = base + 16 * SECTOR
for _ = 1, 64 do
if p + SECTOR > limit then
return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p)
end
if buffer.readstring(b, p + 1, 5) ~= "CD001" then
return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p)
end
local t = buffer.readu8(b, p)
if t == 255 then
break
elseif t == 1 and not pvd then
pvd = p
elseif t == 2 then
local esc = buffer.readstring(b, p + 88, 3)
if esc == "%/@" or esc == "%/C" or esc == "%/E" then
svd = p
jolietLevel = if esc == "%/@" then 1 elseif esc == "%/C" then 2 else 3
end
elseif t == 0 then
bootInfo = bootInfo or { vd = p }
end
p += SECTOR
end
if not pvd then
return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR)
end
local pv = pvd :: number
local bs = u16(b, pv + 128)
if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then
return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128)
end
local info: { [string]: any } = {
blockSize = bs,
blocks = u32(b, pv + 80),
systemId = str(b, pv + 8, 32),
volumeId = str(b, pv + 40, 32),
volumeSet = str(b, pv + 190, 128),
publisher = str(b, pv + 318, 128),
preparer = str(b, pv + 446, 128),
application = str(b, pv + 574, 128),
created = longDate(b, pv + 813),
modified = longDate(b, pv + 830),
joliet = jolietLevel,
}
if bootInfo then
info.boot = boot(b, base, limit, bootInfo.vd, bs)
end
local rlba, rsize = root(b, pv)
local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs)
info.rockRidge = rrSkip ~= nil
local tree = o.prefer or (if rrSkip then "rockridge" elseif svd then "joliet" else "iso9660")
if tree == "joliet" and not svd then
tree = "iso9660"
elseif tree == "rockridge" and not rrSkip then
tree = "iso9660"
end
info.tree = tree
local joliet = tree == "joliet"
local useRR = if tree == "rockridge" then rrSkip else nil
if joliet then
rlba, rsize = root(b, svd :: number)
end
if tree == "joliet" then
info.volumeId = (string.gsub(Text.utf16(b, (svd :: number) + 40, 32, true), "[ %z]+$", ""))
end
local out: { Entry } = {}
local visited: { [number]: boolean } = {}
local stack = { { lba = rlba, size = rsize, path = "" } }
local relocatedDirs: { [string]: boolean } = {}
while #stack > 0 do
local d = table.remove(stack) :: any
if visited[d.lba] then
continue
end
visited[d.lba] = true
local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR)
if not list then
return nil, err
end
local i = 1
local subdirs = {}
while i <= #list do
local r = list[i]
-- multi-extent: this record and the following ones of the same name
local extents: { Extent } = { { at = base + (r.lba + r.ear) * bs, size = r.size } }
local total = r.size
local last = r
while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do
i += 1
last = list[i]
table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size })
total += last.size
end
i += 1
if bit32.band(r.flags, 4) ~= 0 then
continue -- an associated file (resource fork)
end
local rr: any = r.rr
if rr and rr.relocated then
continue -- shown where its CL placeholder is
end
local name = if rr and rr.name then rr.name else r.name
local path = d.path .. name
local isDir = r.dir
local lba: number, size: number = r.lba, r.size
if rr and rr.child then
-- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's
isDir = true
lba = rr.child
local q = base + lba * bs
size = if q + 14 <= limit then u32(b, q + 10) else 0
end
local typ = if isDir then "5" else "0"
if rr and rr.mode then
typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ
end
local e: Entry = {
name = path,
dir = isDir,
size = if isDir or typ ~= "0" then 0 else total,
extents = if isDir or typ ~= "0" then {} else extents,
mtime = if rr and rr.mtime then rr.mtime else r.mtime,
type = typ,
mode = if rr and rr.mode then bit32.band(rr.mode, 0xFFF) else nil,
uid = rr and rr.uid,
gid = rr and rr.gid,
nlink = rr and rr.nlink,
link = if rr and typ == "2" then rr.link else nil,
rdev = rr and rr.rdev,
hidden = if bit32.band(r.flags, 1) ~= 0 then true else nil,
interleaved = if r.interleave then true else nil,
zisofs = if rr and rr.zisofs then true else nil,
}
table.insert(out, e)
if #out > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
if isDir then
table.insert(subdirs, { lba = lba, size = size, path = path .. "/" })
end
end
for k = #subdirs, 1, -1 do
table.insert(stack, subdirs[k])
end
if useRR then
for _, r in list do
if r.rr and r.rr.relocated then
relocatedDirs[d.path] = true
end
end
end
end
-- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it
if useRR then
for dirPath in relocatedDirs do
local name = string.sub(dirPath, 1, -2)
local holds = false
for _, e in out do
if string.sub(e.name, 1, #dirPath) == dirPath then
holds = true
break
end
end
if not holds then
for k, e in out do
if e.name == name then
table.remove(out, k)
break
end
end
end
end
end
-- archive order: depth-first walk order is kept; directories sorted as the image stores them
return out, info
end
-- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err
function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?)
if e.interleaved then
return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name)
end
local lim = limit or buffer.len(b)
local out = buffer.create(e.size)
local q = 0
for _, x in e.extents do
if x.at < 0 or x.at + x.size > lim then
return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at)
end
buffer.copy(out, q, b, x.at, x.size)
q += x.size
end
return out, nil
end
-- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16
function Iso9660.valid(b: buffer, offset: number?): boolean
local p = (offset or 0) + 16 * SECTOR
return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001"
end
return Iso9660
+193
View File
@@ -0,0 +1,193 @@
--!strict
-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit
-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container
-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...).
-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws.
local Err = require("@rosetta/core/Err")
local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring
local byteswap = bit32.byteswap
local Box = {}
export type Box = {
type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid`
start: number, -- absolute offset of the box in the buffer
size: number, -- the whole box, header included
data: number, -- absolute offset of the payload (after size / type / largesize / uuid)
stop: number, -- absolute offset just past the box (start + size, clamped to the parent)
uuid: string?,
children: { Box }?, -- container boxes
truncated: boolean?, -- the box claims more bytes than its parent has (clamped)
}
-- plain container boxes: their payload is a list of boxes
local CONTAINERS = {
moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true,
mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true,
schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true,
strk = true, strd = true, grpl = true, meco = true, mere = true,
}
-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes
local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 }
Box.CONTAINERS = CONTAINERS
local function be32(b: buffer, o: number): number
return byteswap(readu32(b, o))
end
Box.be32 = be32
-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes
local function isIlstItem(parentType: string?): boolean
return parentType == "ilst"
end
-- header(buf, p, limit) -> Box (without children) | nil, Err
function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?)
if p + 8 > limit then
return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p)
end
local size = be32(b, p)
local typ = readstring(b, p + 4, 4)
local data = p + 8
if size == 1 then
if p + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p)
end
size = be32(b, p + 8) * 4294967296 + be32(b, p + 12)
data = p + 16
elseif size == 0 then
size = limit - p
end
local uuid: string? = nil
if typ == "uuid" then
if data + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p)
end
uuid = readstring(b, data, 16)
data += 16
end
if size < data - p then
return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p)
end
local stop = p + size
local truncated: boolean? = nil
if stop > limit then
stop = limit
truncated = true
end
return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil
end
-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A
-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any.
function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?)
local d = depth or 0
local out: { Box } = {}
local firstErr: Err.Err? = nil
if d > 32 then
return out, Err.new(Err.CORRUPT, "boxes nested too deep", p)
end
while p + 8 <= limit do
local box, err = Box.header(b, p, limit)
if not box then
firstErr = firstErr or err
break
end
if box.truncated then
firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p)
end
local t = box.type
local kids: { Box }? = nil
local kerr: Err.Err? = nil
if CONTAINERS[t] or isIlstItem(parentType) then
kids, kerr = Box.list(b, box.data, box.stop, t, d + 1)
elseif FULL_CONTAINERS[t] then
local q = box.data + 4 + FULL_CONTAINERS[t]
-- QuickTime writes udta/meta as a plain container: its first child box follows directly
if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then
q = box.data
end
if q <= box.stop then
kids, kerr = Box.list(b, q, box.stop, t, d + 1)
end
elseif t == "iinf" then
if box.data + 4 <= box.stop then
local v = readu8(b, box.data)
local q = box.data + 4 + (if v == 0 then 2 else 4)
if q <= box.stop then
kids, kerr = Box.list(b, q, box.stop, t, d + 1)
end
end
end
box.children = kids
if kerr then
firstErr = firstErr or kerr
end
table.insert(out, box)
if box.stop <= p then
break
end
p = box.stop
end
return out, firstErr
end
-- child(box, type) -> the first child of that type
function Box.child(box: Box?, typ: string): Box?
if not box or not box.children then
return nil
end
for _, c in box.children :: { Box } do
if c.type == typ then
return c
end
end
return nil
end
-- children(box, type) -> every child of that type
function Box.childrenOf(box: Box?, typ: string): { Box }
local out = {}
if box and box.children then
for _, c in box.children :: { Box } do
if c.type == typ then
table.insert(out, c)
end
end
end
return out
end
-- path(boxes or box, "moov/trak/mdia") -> the first box along the path
function Box.path(root: any, path: string): Box?
local cur: any = root
for part in string.gmatch(path, "[^/]+") do
if cur == nil then
return nil
end
local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur
local found = nil
if list then
for _, c in list do
if c.type == part then
found = c
break
end
end
end
cur = found
end
return cur
end
-- version / flags of a full box
function Box.fullHeader(b: buffer, box: Box): (number, number)
if box.data + 4 > box.stop then
return -1, 0
end
local v = be32(b, box.data)
return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF)
end
return Box
+862
View File
@@ -0,0 +1,862 @@
--!strict
-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8):
-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration
-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 /
-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun).
-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the
-- reader's buffer. Never throws.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Box = require("@rosetta/containers/IsoBmff/Box")
local QtPalette = require("@rosetta/containers/IsoBmff/QtPalette")
local readstring = buffer.readstring
local function readu16be(b: buffer, o: number): number
return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1)
end
local Demux = {}
export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty)
-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the
-- sample tables and the ISO facts
export type Track = {
id: number,
kind: "video" | "audio" | "subtitle" | "data",
codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc
entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...)
handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...)
timescale: number,
duration: number, -- seconds (media duration; the edit list may shorten it)
mediaDuration: number, -- ticks
language: string?, -- ISO 639-2 ("und", "eng", ...)
width: number?,
height: number?,
sampleRate: number?,
channels: number?,
bitsPerSample: number?,
config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...)
bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...)
palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF)
objectType: number?, -- esds objectTypeIndication
pcm: { bits: number, float: boolean, little: boolean }?,
entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...)
edits: { Edit }?,
skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming)
delay: number, -- movie ticks of an initial empty edit
playDuration: number?, -- media ticks the edit list plays (nil: all)
-- samples
sampleCount: number,
offsets: { number }, -- absolute offsets in the buffer
sizes: { number },
dts: { number }, -- decode times in ticks
durations: { number },
cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets
sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample)
sampleDescription: { number }?, -- stsd index per sample when there are several entries
[string]: any,
}
export type Options = { maxSamples: number? }
local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = {
soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle",
sbtl = "subtitle", clcp = "subtitle",
}
local CODEC: { [string]: string } = {
mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3",
lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm",
ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb",
avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9",
mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1",
["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text",
}
-- esds objectTypeIndication -> codec
local OTI: { [number]: string } = {
[0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1",
[0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3",
[0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis",
}
-- the box holding each video / audio codec's configuration
local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" }
local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true }
local function payload(b: buffer, box: Box.Box, skip: number?): buffer
local o = box.data + (skip or 0)
local n = math.max(0, box.stop - o)
local out = buffer.create(n)
if n > 0 then
buffer.copy(out, 0, b, o, n)
end
return out
end
local function reader(b: buffer, box: Box.Box): Bytes.Reader
return Bytes.reader(b, box.data, box.stop - box.data)
end
-- expandable descriptor length (ISO 14496-1 8.3.3)
local function descLen(r: Bytes.Reader): number
local n = 0
for _ = 1, 4 do
local c = r:u8()
n = n * 128 + bit32.band(c, 127)
if c < 128 then
break
end
end
return n
end
-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate
function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?)
local r = reader(b, box)
r:skip(4) -- version / flags
if r:u8() ~= 3 then
return nil, nil, nil
end
descLen(r)
r:skip(2) -- ES_ID
local flags = r:u8()
if bit32.band(flags, 0x80) ~= 0 then
r:skip(2)
end
if bit32.band(flags, 0x40) ~= 0 then
r:skip(r:u8())
end
if bit32.band(flags, 0x20) ~= 0 then
r:skip(2)
end
if r:u8() ~= 4 then
return nil, nil, nil
end
local dlen = descLen(r)
local dstart = r.pos
local oti = r:u8()
r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate
local avg = r:u32be()
local dsi: buffer? = nil
if r.pos < dstart + dlen and r:u8() == 5 then
local n = descLen(r)
if n > 0 and r:need(n) then
dsi = r:bytes(n)
end
end
if r.err then
return oti, nil, nil
end
return oti, dsi, avg
end
-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t
local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track)
local r = reader(b, e)
r:skip(6)
r:skip(2) -- data reference index
local typ = e.type
t.entry = typ
t.codec = CODEC[typ] or typ
local kind = t.kind
local childStart
if kind == "audio" then
local version = r:u16be()
r:skip(2 + 4) -- revision, vendor
local channels = r:u16be()
local bits = r:u16be()
r:skip(4) -- compression id, packet size
local rate = r:u32be() / 65536
if version == 1 then
r:skip(16)
elseif version == 2 then
r:skip(4)
rate = r:f64be()
channels = r:u32be()
r:skip(4)
bits = r:u32be()
local lpcmFlags = r:u32be()
r:skip(8)
if typ == "lpcm" then
t.pcm = {
bits = bits,
float = bit32.band(lpcmFlags, 1) ~= 0,
little = bit32.band(lpcmFlags, 2) == 0,
}
end
end
t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits
if not t.pcm and t.codec == "pcm" then
local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 }
t.pcm = {
bits = B[typ] or bits,
float = typ == "fl32" or typ == "fl64",
little = typ == "sowt",
}
end
childStart = r.pos
elseif kind == "video" then
r:skip(16)
t.width = r:u16be()
t.height = r:u16be()
r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2)
childStart = r.pos
-- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...)
local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ)
t.bitsPerPixel = depth
t.palette = pal
if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then
childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8)
end
else
childStart = r.pos
end
if r.err then
t.entryBoxes = {}
return
end
local kids = Box.list(b, childStart, e.stop, typ)
t.entryBoxes = kids
-- QuickTime puts the codec boxes inside 'wave'
local all = table.clone(kids)
local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave")
if wave and wave.children then
for _, c in wave.children :: { Box.Box } do
table.insert(all, c)
end
end
local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any
local esds = Box.child(holder, "esds")
if esds then
local oti, dsi, avg = Demux.esds(b, esds)
t.objectType = oti
if oti and OTI[oti] then
t.codec = OTI[oti]
end
t.config = dsi
if avg and avg > 0 then
t.bitrate = avg
end
end
if typ == "alac" then
local a = Box.child(holder, "alac")
if a then
t.config = payload(b, a, 4)
end
end
for _, name in CONFIG_BOX do
local c = Box.child(holder, name)
if c then
t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0)
break
end
end
end
-- media handler / header / sample tables of one trak -> Track | nil, Err
local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?)
local tkhd = Box.child(trak, "tkhd")
local mdia = Box.child(trak, "mdia")
if not tkhd or not mdia then
return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start)
end
local t: Track = {
id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0,
entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {},
}
do
local r = reader(b, tkhd)
local v = r:u8()
r:skip(3)
if v == 1 then
r:skip(16)
t.id = r:u32be()
r:skip(4 + 8)
else
r:skip(8)
t.id = r:u32be()
r:skip(4 + 4)
end
r:skip(8 + 2 + 2 + 2 + 2 + 36)
local w, h = r:u32be() / 65536, r:u32be() / 65536
if r.err then
return nil, r.err
end
if w > 0 and h > 0 then
t.width, t.height = math.floor(w), math.floor(h)
end
end
local mdhd = Box.child(mdia, "mdhd")
if mdhd then
local r = reader(b, mdhd)
local v = r:u8()
r:skip(3)
if v == 1 then
r:skip(16)
t.timescale = r:u32be()
t.mediaDuration = r:u64be()
else
r:skip(8)
t.timescale = r:u32be()
t.mediaDuration = r:u32be()
end
local lang = r:u16be()
if not r.err and lang ~= 0 and lang ~= 0x7FFF then
t.language = string.char(
96 + bit32.band(bit32.rshift(lang, 10), 31),
96 + bit32.band(bit32.rshift(lang, 5), 31),
96 + bit32.band(lang, 31)
)
end
if t.timescale == 0 then
t.timescale = 1
end
end
local hdlr = Box.child(mdia, "hdlr")
if hdlr and hdlr.data + 12 <= hdlr.stop then
t.handler = readstring(b, hdlr.data + 8, 4)
end
t.kind = HANDLER_KIND[t.handler] or "data"
local stbl = Box.path(mdia, "minf/stbl")
if not stbl then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start)
end
-- sample descriptions
local stsd = Box.child(stbl, "stsd")
if stsd and stsd.data + 8 <= stsd.stop then
local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd")
if entries[1] then
sampleEntry(b, entries[1], t.handler, t)
end
t.sampleEntries = entries
end
-- edit list
local elst = Box.path(trak, "edts/elst")
if elst then
local r = reader(b, elst)
local v = r:u8()
r:skip(3)
local n = r:u32be()
if n <= (elst.stop - elst.data) // 12 then
local edits: { Edit } = {}
for _ = 1, n do
local dur: number, mt: number
if v == 1 then
dur, mt = r:u64be(), r:i64be() :: number
else
dur, mt = r:u32be(), r:i32be() :: number
end
local rate = r:i32be() / 65536
if r.err then
break
end
table.insert(edits, { duration = dur, mediaTime = mt, rate = rate })
end
t.edits = edits
local play = 0
local started = false
for _, ed in edits do
if ed.mediaTime == -1 then
if not started then
t.delay += ed.duration
end
else
if not started then
t.skip = ed.mediaTime
started = true
end
play += ed.duration * t.timescale / math.max(1, movieTimescale)
end
end
if started and play > 0 then
t.playDuration = math.floor(play + 0.5)
end
end
end
-- sample sizes
local maxSamples = o.maxSamples or 2 ^ 25
local sizes = t.sizes
local count = 0
local stsz = Box.child(stbl, "stsz")
local stz2 = Box.child(stbl, "stz2")
if stsz then
local r = reader(b, stsz)
r:skip(4)
local fixed = r:u32be()
count = r:u32be()
if r.err then
return nil, r.err
end
if count > maxSamples then
return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start)
end
if fixed ~= 0 then
for i = 1, count do
sizes[i] = fixed
end
else
if count * 4 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start)
end
for i = 1, count do
sizes[i] = r:u32be()
end
end
elseif stz2 then
local r = reader(b, stz2)
r:skip(4 + 3)
local fieldSize = r:u8()
count = r:u32be()
if r.err then
return nil, r.err
end
if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then
return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start)
end
if count * fieldSize / 8 > r:remaining() + 1 then
return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start)
end
for i = 1, count do
if fieldSize == 16 then
sizes[i] = r:u16be()
elseif fieldSize == 8 then
sizes[i] = r:u8()
else
local byte = r:peekU8()
if i % 2 == 1 then
sizes[i] = bit32.rshift(math.max(byte, 0), 4)
else
sizes[i] = bit32.band(math.max(byte, 0), 15)
r:skip(1)
end
end
end
end
-- decode times
local dts, durs = t.dts, t.durations
local stts = Box.child(stbl, "stts")
if stts and count > 0 then
local r = reader(b, stts)
r:skip(4)
local n = r:u32be()
if n * 8 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start)
end
local i, time = 1, 0
for _ = 1, n do
local c, d = r:u32be(), r:u32be()
for _ = 1, c do
if i > count then
break
end
dts[i], durs[i] = time, d
time += d
i += 1
end
end
-- fewer stts entries than samples: repeat the last duration
local last = if i > 1 then durs[i - 1] else 0
while i <= count do
dts[i], durs[i] = time, last
time += last
i += 1
end
else
for i = 1, count do
dts[i], durs[i] = 0, 0
end
end
-- composition offsets
local ctts = Box.child(stbl, "ctts")
if ctts and count > 0 then
local r = reader(b, ctts)
local v = r:u8()
r:skip(3)
local n = r:u32be()
if n * 8 <= r:remaining() then
local cts = table.create(count, 0)
local i = 1
for _ = 1, n do
local c = r:u32be()
local off = if v == 1 then r:i32be() else r:u32be()
if v == 0 and off >= 2147483648 then
off -= 4294967296 -- writers put negative offsets in version 0 too
end
for _ = 1, c do
if i > count then
break
end
cts[i] = off
i += 1
end
end
t.cts = cts
end
end
-- sync samples
local stss = Box.child(stbl, "stss")
if stss then
local r = reader(b, stss)
r:skip(4)
local n = r:u32be()
if n * 4 <= r:remaining() then
local sync = {}
for _ = 1, n do
sync[r:u32be()] = true
end
t.sync = sync
end
end
-- chunk offsets + sample-to-chunk -> sample offsets
local stco = Box.child(stbl, "stco")
local co64 = Box.child(stbl, "co64")
local chunks: { number } = {}
if stco or co64 then
local box = (stco or co64) :: Box.Box
local r = reader(b, box)
r:skip(4)
local n = r:u32be()
local w = if co64 then 8 else 4
if n * w > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start)
end
for i = 1, n do
chunks[i] = if co64 then r:u64be() else r:u32be()
end
end
local stsc = Box.child(stbl, "stsc")
local offsets = t.offsets
if count > 0 then
if not stsc or #chunks == 0 then
return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start)
end
local r = reader(b, stsc)
r:skip(4)
local n = r:u32be()
if n * 12 > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start)
end
local first: { number }, per: { number }, desc: { number } = {}, {}, {}
for k = 1, n do
first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be()
end
local sdi: { number }? = nil
if n > 0 then
for k = 1, n do
if desc[k] ~= desc[1] then
sdi = table.create(count, 1)
end
end
end
local i = 1
local base = 0 -- added by the caller (the file's offset in the buffer)
for k = 1, n do
local c0 = first[k]
local c1 = if k < n then first[k + 1] - 1 else #chunks
if c0 < 1 then
return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start)
end
for c = c0, math.min(c1, #chunks) do
local off = chunks[c] + base
for _ = 1, per[k] do
if i > count then
break
end
offsets[i] = off
if sdi then
sdi[i] = desc[k]
end
off += sizes[i]
i += 1
end
if i > count then
break
end
end
if i > count then
break
end
end
if i <= count then
return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start)
end
t.sampleDescription = sdi
end
t.sampleCount = count
-- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024
-- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio.
if t.kind == "audio" and count > 1 and not t.cts and not t.sync then
local fixed = sizes[1]
local uniform = fixed > 0
for i = 1, count do
if sizes[i] ~= fixed or durs[i] ~= 1 then
uniform = false
break
end
end
if uniform then
local no, ns, nd, nu = {}, {}, {}, {}
local i = 1
while i <= count do
local k = 1
while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do
k += 1
end
table.insert(no, offsets[i])
table.insert(ns, k * fixed)
table.insert(nd, dts[i])
table.insert(nu, k)
i += k
end
t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu
t.sampleCount = #no
t.frameSize = fixed
t.sampleDescription = nil
end
end
-- fragment defaults
t.trex = trex[t.id]
return t, nil
end
-- the movie fragments (moof) after the moov: appends their samples to the tracks
local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err?
local maxSamples = o.maxSamples or 2 ^ 25
for _, moof in top do
if moof.type ~= "moof" then
continue
end
local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end)
local prevEnd = moofStart
for _, traf in Box.childrenOf(moof, "traf") do
local tfhd = Box.child(traf, "tfhd")
if not tfhd then
continue
end
local r = reader(b, tfhd)
r:skip(1)
local flags = r:u24be()
local id = r:u32be()
local t = byId[id]
if r.err or not t then
continue
end
local trex = t.trex or {}
local base
if bit32.band(flags, 0x1) ~= 0 then
base = r:u64be()
elseif bit32.band(flags, 0x20000) ~= 0 then
base = moofStart
else
base = prevEnd
end
if bit32.band(flags, 0x2) ~= 0 then
r:skip(4)
end
local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0)
local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0)
local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0)
if r.err then
return r.err
end
local n0 = t.sampleCount
local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0
local tfdt = Box.child(traf, "tfdt")
if tfdt then
local q = reader(b, tfdt)
local v = q:u8()
q:skip(3)
local bt = if v == 1 then q:u64be() else q:u32be()
if not q.err then
time = bt
end
end
local dataPos = base
for _, trun in Box.childrenOf(traf, "trun") do
local q = reader(b, trun)
local v = q:u8()
local tf = q:u24be()
local n = q:u32be()
if q.err then
return q.err
end
if t.sampleCount + n > maxSamples then
return Err.new(Err.LIMIT, "too many fragment samples", trun.start)
end
if bit32.band(tf, 0x1) ~= 0 then
dataPos = base + q:i32be()
end
local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil
local per = 0
for _, bit in { 0x100, 0x200, 0x400, 0x800 } do
if bit32.band(tf, bit) ~= 0 then
per += 4
end
end
if n * per > q:remaining() then
return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start)
end
for k = 1, n do
local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur
local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize
local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags)
local cto = 0
if bit32.band(tf, 0x800) ~= 0 then
cto = if v == 1 then q:i32be() else q:u32be()
end
local i = t.sampleCount + 1
t.sampleCount = i
t.offsets[i] = dataPos
t.sizes[i] = size
t.dts[i] = time
t.durations[i] = dur
if cto ~= 0 or t.cts then
if not t.cts then
t.cts = table.create(i - 1, 0)
end
(t.cts :: { number })[i] = cto
end
-- sample_is_non_sync_sample (bit 16)
local nonSync = bit32.band(sf, 0x10000) ~= 0
if nonSync then
if not t.sync then
local s = {}
for j = 1, i - 1 do
s[j] = true
end
t.sync = s
end
elseif t.sync then
(t.sync :: any)[i] = true
end
time += dur
dataPos += size
end
prevEnd = dataPos
end
end
end
return nil
end
export type Movie = {
brand: string?,
minor: number?,
compatible: { string },
timescale: number,
duration: number, -- seconds
tracks: { Track },
boxes: { Box.Box },
moov: Box.Box?,
fragmented: boolean,
}
-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included)
function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?)
local o: Options = opts or {}
local b = r.buf
local top, terr = Box.list(b, r.base, r.limit)
if #top == 0 then
return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base)
end
local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false }
local ftyp = Box.child({ children = top } :: any, "ftyp")
if ftyp and ftyp.data + 8 <= ftyp.stop then
m.brand = readstring(b, ftyp.data, 4)
m.minor = Box.be32(b, ftyp.data + 4)
local p = ftyp.data + 8
while p + 4 <= ftyp.stop do
table.insert(m.compatible, readstring(b, p, 4))
p += 4
end
end
local moov = Box.child({ children = top } :: any, "moov")
m.moov = moov
if not moov then
return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks
end
local mvhd = Box.child(moov, "mvhd")
local movieDuration = 0
if mvhd then
local q = reader(b, mvhd)
local v = q:u8()
q:skip(3)
if v == 1 then
q:skip(16)
m.timescale = q:u32be()
movieDuration = q:u64be()
else
q:skip(8)
m.timescale = q:u32be()
movieDuration = q:u32be()
end
if q.err or m.timescale == 0 then
m.timescale = 1000
end
end
local trex = {}
local mvex = Box.child(moov, "mvex")
if mvex then
m.fragmented = true
for _, x in Box.childrenOf(mvex, "trex") do
local q = reader(b, x)
q:skip(4)
local id = q:u32be()
q:skip(4)
local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() }
if not q.err then
trex[id] = d
end
end
end
local byId = {}
for _, trak in Box.childrenOf(moov, "trak") do
local t, err = track(b, trak, m.timescale, trex, o)
if not t then
return nil, err
end
table.insert(m.tracks, t)
byId[t.id] = t
end
if m.fragmented then
local ferr = fragments(b, r.base, top, byId, o)
if ferr then
return nil, ferr
end
end
-- durations; drop samples outside the buffer (a truncated file) but keep what is there
for _, t in m.tracks do
local n = t.sampleCount
local ticks = t.mediaDuration
if n > 0 then
ticks = math.max(ticks, t.dts[n] + t.durations[n])
end
t.mediaDuration = ticks
t.duration = ticks / t.timescale
for i = 1, n do
local off = t.offsets[i]
if off < 0 or off + t.sizes[i] > r.limit - r.base then
t.sampleCount = i - 1
t.truncated = true
break
end
end
-- the tables hold file offsets; make them buffer offsets
local base = r.base
if base ~= 0 then
local offs = t.offsets
for i = 1, t.sampleCount do
offs[i] += base
end
end
end
m.duration = movieDuration / m.timescale
if m.duration == 0 then
for _, t in m.tracks do
m.duration = math.max(m.duration, t.duration)
end
end
return m, nil
end
return Demux
+528
View File
@@ -0,0 +1,528 @@
--!strict
-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc
-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC
-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn /
-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer.
-- Never throws.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Box = require("@rosetta/containers/IsoBmff/Box")
local readstring = buffer.readstring
local Meta = {}
local function reader(b: buffer, box: Box.Box): Bytes.Reader
return Bytes.reader(b, box.data, box.stop - box.data)
end
local function uint(r: Bytes.Reader, size: number): number
if size == 0 then
return 0
elseif size == 4 then
return r:u32be()
elseif size == 8 then
return r:u64be()
elseif size == 2 then
return r:u16be()
elseif size == 1 then
return r:u8()
end
r:fail(Err.CORRUPT, "bad iloc field size " .. size)
return 0
end
-- ------------------------------------------------------------------------------------------------ HEIF items
export type Property = { type: string, box: Box.Box, [string]: any }
export type Item = {
id: number,
type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ...
name: string,
contentType: string?,
hidden: boolean,
construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item)
baseOffset: number,
extents: { { offset: number, length: number } },
properties: { Property }, -- in ipma order
essential: { [number]: boolean }, -- by index into properties
refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...)
}
export type Items = {
primary: number?,
items: { [number]: Item },
order: { number }, -- item ids in iinf order
idat: Box.Box?,
properties: { Property }, -- ipco, in order
}
local function property(b: buffer, box: Box.Box): Property
local p: Property = { type = box.type, box = box }
local r = reader(b, box)
local t = box.type
if t == "ispe" then
r:skip(4)
p.width, p.height = r:u32be(), r:u32be()
elseif t == "pixi" then
r:skip(4)
local n = r:u8()
local bits = {}
for i = 1, math.min(n, 16) do
bits[i] = r:u8()
end
p.bits = bits
elseif t == "colr" then
local ct = r:string(4)
p.colourType = ct
if ct == "nclx" then
p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be()
p.fullRange = bit32.band(r:u8(), 0x80) ~= 0
elseif ct == "rICC" or ct == "prof" then
p.icc = r:bytes(r:remaining())
end
elseif t == "irot" then
p.angle = bit32.band(r:u8(), 3) * 90
elseif t == "imir" then
p.axis = bit32.band(r:u8(), 1)
elseif t == "clap" then
local function frac(): number
local n, d = r:i32be(), r:u32be()
return if d == 0 then 0 else n / d
end
p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac()
elseif t == "auxC" then
r:skip(4)
p.auxType = r:cstring()
else
local n = box.stop - box.data
local cfg = buffer.create(math.max(0, n))
if n > 0 then
buffer.copy(cfg, 0, b, box.data, n)
end
p.config = cfg
end
return p
end
-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box)
function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?)
local out: Items = { items = {}, order = {}, properties = {} }
local pitm = Box.child(meta, "pitm")
if pitm then
local r = reader(b, pitm)
local v = r:u8()
r:skip(3)
out.primary = if v == 0 then r:u16be() else r:u32be()
end
local iinf = Box.child(meta, "iinf")
if iinf then
for _, infe in Box.childrenOf(iinf, "infe") do
local r = reader(b, infe)
local v = r:u8()
local flags = r:u24be()
local it: Item = {
id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0,
extents = {}, properties = {}, essential = {}, refs = {},
}
if v >= 2 then
it.id = if v == 2 then r:u16be() else r:u32be()
r:skip(2)
it.type = r:string(4)
it.name = r:cstring()
if it.type == "mime" and r:remaining() > 0 then
it.contentType = r:cstring()
end
else
it.id = r:u16be()
r:skip(2)
it.name = r:cstring()
it.contentType = r:cstring()
it.type = "mime"
end
if r.err and it.id == 0 then
return nil, r.err
end
out.items[it.id] = it
table.insert(out.order, it.id)
end
end
local iloc = Box.child(meta, "iloc")
if iloc then
local r = reader(b, iloc)
local v = r:u8()
r:skip(3)
local a, c = r:u8(), r:u8()
local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4)
local idxSize = if v >= 1 then bit32.band(c, 15) else 0
local n = if v < 2 then r:u16be() else r:u32be()
if r.err then
return nil, r.err
end
for _ = 1, n do
local id = if v < 2 then r:u16be() else r:u32be()
local method = 0
if v >= 1 then
method = bit32.band(r:u16be(), 15)
end
r:skip(2) -- data reference index
local base = uint(r, baseSize)
local ne = r:u16be()
if r.err then
return nil, r.err
end
if ne * (offSize + lenSize + idxSize) > r:remaining() then
return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start)
end
local extents = {}
for k = 1, ne do
if idxSize > 0 then
uint(r, idxSize)
end
extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) }
end
if r.err then
return nil, r.err
end
local it = out.items[id]
if not it then
it = {
id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {},
properties = {}, essential = {}, refs = {},
} :: Item
out.items[id] = it
table.insert(out.order, id)
end
it.construction, it.baseOffset, it.extents = method, base, extents
end
end
local iref = Box.child(meta, "iref")
if iref then
local v = Box.fullHeader(b, iref)
for _, ref in (iref.children or {}) :: { Box.Box } do
local r = reader(b, ref)
local from = if v == 0 then r:u16be() else r:u32be()
local n = r:u16be()
local to = {}
for k = 1, n do
to[k] = if v == 0 then r:u16be() else r:u32be()
end
local it = out.items[from]
if it and not r.err then
it.refs[ref.type] = to
end
end
end
local ipco = Box.path(meta, "iprp/ipco")
if ipco and ipco.children then
for i, pb in ipco.children :: { Box.Box } do
out.properties[i] = property(b, pb)
end
end
local ipma = Box.path(meta, "iprp/ipma")
if ipma then
local r = reader(b, ipma)
local v = r:u8()
local flags = r:u24be()
local n = r:u32be()
for _ = 1, n do
if r.err then
break
end
local id = if v < 1 then r:u16be() else r:u32be()
local na = r:u8()
local it = out.items[id]
for _ = 1, na do
local idx, ess
if bit32.band(flags, 1) ~= 0 then
local x = r:u16be()
idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000
else
local x = r:u8()
idx, ess = bit32.band(x, 0x7F), x >= 0x80
end
local p = out.properties[idx]
if it and p and not r.err then
table.insert(it.properties, p)
if ess then
it.essential[#it.properties] = true
end
end
end
end
end
out.idat = Box.child(meta, "idat")
return out, nil
end
-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit
-- bound the file in the buffer
function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?)
local it = items.items[id]
if not it then
return nil, Err.new(Err.CORRUPT, "no item " .. id)
end
local origin, stop
if it.construction == 0 then
origin, stop = base, limit
elseif it.construction == 1 then
local idat = items.idat
if not idat then
return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat")
end
origin, stop = idat.data, idat.stop
else
return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction)
end
local total = 0
for _, e in it.extents do
local len = e.length
if len == 0 then -- the whole rest of the file
len = stop - origin - e.offset
end
if e.offset < 0 or len < 0 or origin + e.offset + len > stop then
return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end")
end
total += len
end
if total > 2 ^ 30 then
return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big")
end
local out = buffer.create(total)
local p = 0
for _, e in it.extents do
local len = if e.length == 0 then stop - origin - e.offset else e.length
buffer.copy(out, p, b, origin + e.offset, len)
p += len
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ iTunes tags
-- ilst item -> standard tag name
local TAG: { [string]: string } = {
["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date",
["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder",
["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription",
sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort",
tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate",
["\169pub"] = "publisher", ["\169xyz"] = "location",
}
local TAG_ATOM: { [string]: string } = {}
for atom, name in TAG do
TAG_ATOM[name] = atom
end
Meta.TAG = TAG
Meta.TAG_ATOM = TAG_ATOM
-- freeform (----) names: tags keys are lower case; these keep their usual spelling when written back
local FREEFORM: { [string]: string } = { itunsmpb = "iTunSMPB", itunnorm = "iTunNORM", itunes_cddb_ids = "iTunes_CDDB_IDs" }
-- the ID3v1 genres gnre indexes (1-based in gnre)
local GENRES = {
"Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age",
"Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska",
"Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion",
"Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock",
"Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic",
"Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult",
"Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
"Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro",
"Musical", "Rock & Roll", "Hard Rock",
}
export type Picture = { mime: string, data: buffer }
-- tags(buf, ilst) -> Tags, { Picture }
function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture })
local tags: { [string]: string } = {}
local pics: { Picture } = {}
if not ilst or not ilst.children then
return tags, pics
end
for _, item in ilst.children :: { Box.Box } do
local typ = item.type
local freeName: string? = nil
if typ == "----" then
local nm = Box.child(item, "name")
if nm and nm.data + 4 <= nm.stop then
freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4)
end
end
for _, d in Box.childrenOf(item, "data") do
if d.data + 8 > d.stop then
continue
end
local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF)
local p, n = d.data + 8, d.stop - d.data - 8
if typ == "trkn" or typ == "disk" then
if n >= 6 then
local num = Box.be32(b, p) % 65536
local total = Box.be32(b, p + 2) % 65536
local key = if typ == "trkn" then "track" else "disc"
if num > 0 then
tags[key] = tostring(num)
end
if total > 0 then
tags[key .. "total"] = tostring(total)
end
end
elseif typ == "gnre" then
if n >= 2 then
local g = GENRES[Box.be32(b, p - 2) % 65536]
if g and not tags.genre then
tags.genre = g
end
end
elseif typ == "tmpo" then
if n >= 2 then
tags.bpm = tostring(Box.be32(b, p - 2) % 65536)
end
elseif typ == "cpil" or typ == "pgap" then
if n >= 1 then
tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p))
end
elseif typ == "covr" then
local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg"
local data = buffer.create(n)
buffer.copy(data, 0, b, p, n)
table.insert(pics, { mime = mime, data = data })
elseif kind == 1 or kind == 0 then
local s = readstring(b, p, n)
local key = if freeName then string.lower(freeName) else TAG[typ] or string.lower(typ)
if typ == "\169gen" or not tags[key] then
tags[key] = s
end
end
end
end
return tags, pics
end
-- ------------------------------------------------------------------------------------------------ ilst writer
local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ())
local start = w:tell()
w:u32be(0)
w:string(typ)
body(w)
w:setU32be(start, w:tell() - start)
end
Meta.box = box
local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer)
box(w, "data", function()
w:u32be(kind)
w:u32be(0)
if type(value) == "string" then
w:string(value)
else
w:bytes(value)
end
end)
end
local function num(s: string?): number
local v = tonumber(s or "")
if not v then
return 0
end
return math.clamp(math.floor(v), 0, 65535)
end
-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----'
-- freeform com.apple.iTunes items) and cover pictures
function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "ilst", function()
local keys = {}
for k in tags do
table.insert(keys, k)
end
table.sort(keys)
local done: { [string]: boolean } = {}
for _, k in keys do
local v = tags[k]
if type(v) ~= "string" or done[k] then
continue
end
if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then
local base = if k == "track" or k == "tracktotal" then "track" else "disc"
if done[base] then
continue
end
done[base] = true
local atom = if base == "track" then "trkn" else "disk"
local n, total = num(tags[base]), num(tags[base .. "total"])
box(w, atom, function()
box(w, "data", function()
w:u32be(0)
w:u32be(0)
w:u16be(0)
w:u16be(n)
w:u16be(total)
if atom == "trkn" then
w:u16be(0)
end
end)
end)
elseif k == "bpm" then
box(w, "tmpo", function()
box(w, "data", function()
w:u32be(21)
w:u32be(0)
w:u16be(num(v))
end)
end)
elseif k == "compilation" or k == "gapless" then
box(w, if k == "compilation" then "cpil" else "pgap", function()
box(w, "data", function()
w:u32be(21)
w:u32be(0)
w:u8(if num(v) ~= 0 then 1 else 0)
end)
end)
elseif TAG_ATOM[k] then
box(w, TAG_ATOM[k], function()
dataBox(w, 1, v)
end)
else
box(w, "----", function()
box(w, "mean", function()
w:u32be(0)
w:string("com.apple.iTunes")
end)
box(w, "name", function()
w:u32be(0)
w:string(FREEFORM[k] or k)
end)
dataBox(w, 1, v)
end)
end
done[k] = true
end
if pictures and #pictures > 0 then
box(w, "covr", function()
for _, p in pictures :: { Picture } do
dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data)
end
end)
end
end)
end
-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst
function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?)
box(w, "udta", function()
box(w, "meta", function()
w:u32be(0)
box(w, "hdlr", function()
w:u32be(0)
w:u32be(0)
w:string("mdir")
w:string("appl")
w:u32be(0)
w:u32be(0)
w:u8(0)
end)
Meta.writeIlst(w, tags, pictures)
end)
end)
end
return Meta
+519
View File
@@ -0,0 +1,519 @@
--!strict
-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak
-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks
-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample
-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... +
-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Meta = require("@rosetta/containers/IsoBmff/Meta")
local Mux = {}
export type MuxTrack = {
kind: "audio" | "video" | "subtitle" | "data",
entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ...
timescale: number, -- ticks per second (audio: the sample rate)
samples: { buffer }?, -- one buffer per sample, or
data: buffer?, -- the samples back to back, with
sizes: { number }?, -- their sizes
durations: { number } | number, -- ticks per sample (or one constant)
cts: { number }?, -- composition offsets (video with B-frames)
sync: { [number]: boolean }?, -- sync samples (nil: all)
sampleRate: number?,
channels: number?,
bitsPerSample: number?, -- default 16
width: number?,
height: number?,
config: buffer?, -- the codec configuration, written as the entry's configuration box
configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC)
objectType: number?, -- esds objectTypeIndication (default 0x40, AAC)
bitrate: number?, -- esds average bitrate
boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads)
language: string?, -- ISO 639-2, default "und"
name: string?, -- hdlr name
skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming)
playDuration: number?, -- media ticks to play (edit list)
}
export type MuxSpec = {
brand: string?, -- default "isom"
minor: number?,
compatible: { string }?,
timescale: number?, -- movie timescale, default 1000
tracks: { MuxTrack },
tags: { [string]: string }?,
pictures: { Meta.Picture }?,
chunkDuration: number?, -- seconds of samples per chunk, default 1
}
local DEFAULT_CONFIG_BOX: { [string]: string } = {
mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC",
hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3",
}
local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true }
local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" }
local box = Meta.box
local function lang(s: string?): number
local l = s or "und"
if #l ~= 3 then
l = "und"
end
local v = 0
for i = 1, 3 do
v = v * 32 + bit32.band(string.byte(l, i) - 96, 31)
end
return v
end
local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ())
local inner = Bytes.writer(64)
body(inner)
local n = inner:tell()
w:u8(tag)
-- 4-byte expandable length (the common iTunes / ffmpeg form)
w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127))
w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127))
w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127))
w:u8(bit32.band(n, 127))
w:bytes(inner.buf, 0, n)
end
local function esds(w: Bytes.Writer, t: MuxTrack)
box(w, "esds", function()
w:u32be(0)
descriptor(w, 3, function(d)
d:u16be(0) -- ES_ID
d:u8(0)
descriptor(d, 4, function(c)
c:u8(t.objectType or 0x40)
c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1
c:u24be(0)
c:u32be(t.bitrate or 0)
c:u32be(t.bitrate or 0)
if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info)
descriptor(c, 5, function(s)
s:bytes(t.config :: buffer)
end)
end
end)
descriptor(d, 6, function(s)
s:u8(2)
end)
end)
end)
end
local function sampleEntry(w: Bytes.Writer, t: MuxTrack)
box(w, t.entry, function()
w:fill(0, 6)
w:u16be(1) -- data reference index
if t.kind == "audio" then
w:u16be(0) -- version
w:u16be(0)
w:u32be(0)
w:u16be(t.channels or 2)
w:u16be(t.bitsPerSample or 16)
w:u16be(0)
w:u16be(0)
local sr = t.sampleRate or t.timescale
w:u32be(if sr < 65536 then sr * 65536 else 0)
elseif t.kind == "video" then
w:fill(0, 16)
w:u16be(t.width or 0)
w:u16be(t.height or 0)
w:u32be(0x00480000)
w:u32be(0x00480000)
w:u32be(0)
w:u16be(1) -- frame count
w:fill(0, 32) -- compressor name
w:u16be(0x18)
w:i16be(-1)
end
local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry]
if t.config and cb then
if cb == "esds" then
esds(w, t)
else
box(w, cb, function()
if FULL_BOX[cb] then
w:u32be(0)
end
w:bytes(t.config :: buffer)
end)
end
end
for _, x in t.boxes or {} do
box(w, x.type, function()
w:bytes(x.data)
end)
end
end)
end
type Chunk = { track: number, first: number, count: number, time: number, offset: number }
-- runs of equal values: { { count, value } }
local function runs(n: number, value: (number) -> number): { { number } }
local out = {}
for i = 1, n do
local v = value(i)
local last = out[#out]
if last and last[2] == v then
last[1] += 1
else
table.insert(out, { 1, v })
end
end
return out
end
type Prepared = {
t: MuxTrack,
n: number,
sizes: { number },
dur: (number) -> number,
total: number, -- media ticks
chunks: { Chunk },
sample: (number) -> (buffer, number), -- buffer, offset
}
local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean)
local mts = spec.timescale or 1000
local function toMovie(p: Prepared, ticks: number): number
return math.floor(ticks * mts / p.t.timescale + 0.5)
end
local movieDur = 0
for _, p in prep do
local play = p.t.playDuration or (p.total - (p.t.skip or 0))
movieDur = math.max(movieDur, toMovie(p, play))
end
box(w, "moov", function()
box(w, "mvhd", function()
w:u32be(0)
w:u32be(0)
w:u32be(0)
w:u32be(mts)
w:u32be(movieDur)
w:u32be(0x00010000)
w:u16be(0x0100)
w:fill(0, 10)
for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
w:u32be(v)
end
w:fill(0, 24)
w:u32be(#prep + 1)
end)
for id, p in prep do
local t = p.t
local play = t.playDuration or (p.total - (t.skip or 0))
box(w, "trak", function()
box(w, "tkhd", function()
w:u32be(3) -- enabled, in movie
w:u32be(0)
w:u32be(0)
w:u32be(id)
w:u32be(0)
w:u32be(toMovie(p, play))
w:fill(0, 8)
w:u16be(0)
w:u16be(0)
w:u16be(if t.kind == "audio" then 0x0100 else 0)
w:u16be(0)
for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do
w:u32be(v)
end
w:u32be((t.width or 0) * 65536)
w:u32be((t.height or 0) * 65536)
end)
if t.skip or t.playDuration then
box(w, "edts", function()
box(w, "elst", function()
w:u32be(0)
w:u32be(1)
w:u32be(toMovie(p, play))
w:u32be(t.skip or 0)
w:u32be(0x00010000)
end)
end)
end
box(w, "mdia", function()
box(w, "mdhd", function()
w:u32be(0)
w:u32be(0)
w:u32be(0)
w:u32be(t.timescale)
w:u32be(p.total)
w:u16be(lang(t.language))
w:u16be(0)
end)
box(w, "hdlr", function()
w:u32be(0)
w:u32be(0)
w:string(HANDLER[t.kind] or "meta")
w:fill(0, 12)
w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler"))
end)
box(w, "minf", function()
if t.kind == "audio" then
box(w, "smhd", function()
w:u32be(0)
w:u32be(0)
end)
elseif t.kind == "video" then
box(w, "vmhd", function()
w:u32be(1)
w:fill(0, 8)
end)
else
box(w, "nmhd", function()
w:u32be(0)
end)
end
box(w, "dinf", function()
box(w, "dref", function()
w:u32be(0)
w:u32be(1)
box(w, "url ", function()
w:u32be(1) -- self-contained
end)
end)
end)
box(w, "stbl", function()
box(w, "stsd", function()
w:u32be(0)
w:u32be(1)
sampleEntry(w, t)
end)
local stts = runs(p.n, p.dur)
box(w, "stts", function()
w:u32be(0)
w:u32be(#stts)
for _, r in stts do
w:u32be(r[1])
w:u32be(r[2])
end
end)
local cts = t.cts
if cts then
local cr = runs(p.n, function(i)
return cts[i] or 0
end)
box(w, "ctts", function()
w:u32be(0x01000000) -- version 1: signed offsets
w:u32be(#cr)
for _, r in cr do
w:u32be(r[1])
w:i32be(r[2])
end
end)
end
local sync = t.sync
if sync then
local list = {}
for i = 1, p.n do
if sync[i] then
table.insert(list, i)
end
end
box(w, "stss", function()
w:u32be(0)
w:u32be(#list)
for _, i in list do
w:u32be(i)
end
end)
end
local stsc = runs(#p.chunks, function(i)
return p.chunks[i].count
end)
box(w, "stsc", function()
w:u32be(0)
w:u32be(#stsc)
local c = 1
for _, r in stsc do
w:u32be(c)
w:u32be(r[2])
w:u32be(1)
c += r[1]
end
end)
box(w, "stsz", function()
w:u32be(0)
local fixed = p.sizes[1] or 0
for i = 2, p.n do
if p.sizes[i] ~= fixed then
fixed = -1
break
end
end
if fixed >= 0 and p.n > 0 then
w:u32be(fixed)
w:u32be(p.n)
else
w:u32be(0)
w:u32be(p.n)
for i = 1, p.n do
w:u32be(p.sizes[i])
end
end
end)
box(w, if co64 then "co64" else "stco", function()
w:u32be(0)
w:u32be(#p.chunks)
for _, c in p.chunks do
if co64 then
w:u64be(c.offset)
else
w:u32be(c.offset)
end
end
end)
end)
end)
end)
end)
end
if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then
Meta.writeUdta(w, spec.tags or {}, spec.pictures)
end
end)
end
-- mux(spec) -> buffer | nil, Err
function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?)
if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then
return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }")
end
local prep: { Prepared } = {}
local all: { Chunk } = {}
for k, t in spec.tracks do
if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale")
end
if not HANDLER[t.kind] then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind))
end
local n, sizes, sample
if t.samples then
local list = t.samples
n = #list
sizes = table.create(n, 0)
for i = 1, n do
if type(list[i]) ~= "buffer" then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer")
end
sizes[i] = buffer.len(list[i])
end
sample = function(i: number): (buffer, number)
return list[i], 0
end
elseif t.data and t.sizes then
n = #t.sizes
sizes = t.sizes
local starts = table.create(n, 0)
local o = 0
for i = 1, n do
starts[i] = o
o += sizes[i]
end
if o > buffer.len(t.data) then
return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data")
end
local data = t.data
sample = function(i: number): (buffer, number)
return data, starts[i]
end
else
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes")
end
local durs = t.durations
local dur
if type(durs) == "number" then
dur = function(_: number): number
return durs
end
elseif type(durs) == "table" then
dur = function(i: number): number
return durs[i] or 0
end
else
return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations")
end
local total = 0
local chunks: { Chunk } = {}
local per = (spec.chunkDuration or 1) * t.timescale
local cur: Chunk? = nil
for i = 1, n do
if not cur or total - cur.time >= per then
cur = { track = k, first = i, count = 0, time = total, offset = 0 }
table.insert(chunks, cur :: Chunk)
table.insert(all, cur :: Chunk)
end
(cur :: Chunk).count += 1
total += dur(i)
end
prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample }
end
-- interleave the chunks by time
table.sort(all, function(a: Chunk, b: Chunk): boolean
local ta = a.time / prep[a.track].t.timescale
local tb = b.time / prep[b.track].t.timescale
if ta ~= tb then
return ta < tb
end
if a.track ~= b.track then
return a.track < b.track
end
return a.first < b.first
end)
local mdatSize = 0
for _, c in all do
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
mdatSize += p.sizes[i]
end
end
local co64 = mdatSize > 4294967295 - 2 ^ 24
-- ftyp
local w = Bytes.writer(mdatSize + 4096)
box(w, "ftyp", function()
w:string(spec.brand or "isom")
w:u32be(spec.minor or 0x200)
for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do
w:string(string.sub(c .. " ", 1, 4))
end
end)
-- moov twice: the first pass measures it, the second has the real chunk offsets
local probe = Bytes.writer(4096)
moov(probe, spec, prep, co64)
local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8
local o = w:tell() + probe:tell() + mdatHeader
for _, c in all do
c.offset = o
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
o += p.sizes[i]
end
end
moov(w, spec, prep, co64)
if mdatHeader == 16 then
w:u32be(1)
w:string("mdat")
w:u64be(mdatSize + 16)
else
w:u32be(mdatSize + 8)
w:string("mdat")
end
for _, c in all do
local p = prep[c.track]
for i = c.first, c.first + c.count - 1 do
local b, off = p.sample(i)
w:bytes(b, off, p.sizes[i])
end
end
return w:finish(), nil
end
return Mux
@@ -0,0 +1,120 @@
--!strict
-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime
-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0).
-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1,
-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey
-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the
-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps).
--
-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec)
-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil
--
-- Never throws.
local readu8, writeu32 = buffer.readu8, buffer.writeu32
local function readu16(b: buffer, o: number): number -- big-endian
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function readu32(b: buffer, o: number): number
return readu16(b, o) * 65536 + readu16(b, o + 2)
end
local QtPalette = {}
local function rgb(r: number, g: number, b: number): number
return r + g * 256 + b * 65536 + 0xFF000000
end
-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette)
local SMALL: { [number]: { number } } = {
[1] = { 0xFFFFFF, 0x000000 },
[2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 },
[4] = {
0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA,
0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000,
},
}
local function defaultTable(bits: number): buffer
local pal = buffer.create(1024)
local small = SMALL[bits]
if small then
for i, c in small do
writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256))
end
return pal
end
local i = 0
for r = 5, 0, -1 do
for g = 5, 0, -1 do
for b = 5, 0, -1 do
if i < 215 then
writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51))
end
i += 1
end
end
end
-- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black
local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 }
i = 215
for ch = 0, 3 do
for _, v in RAMP do
local r = if ch == 0 or ch == 3 then v else 0
local g = if ch == 1 or ch == 3 then v else 0
local b = if ch == 2 or ch == 3 then v else 0
writeu32(pal, i * 4, rgb(r, g, b))
i += 1
end
end
writeu32(pal, 255 * 4, rgb(0, 0, 0))
return pal
end
-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size
-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it.
function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?)
if start + 86 > stop or stop > buffer.len(b) then
return nil, nil
end
local raw = readu16(b, start + 82)
local id = readu16(b, start + 84)
local bits = raw % 32
local grey = raw >= 32 and (raw // 32) % 2 == 1
if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then
return raw, nil
end
if grey and codec == "cinepak" then
return raw, nil
end
if grey and bits > 1 and id ~= 0 then
local pal = buffer.create(1024)
local count = 2 ^ bits
local step = 256 // (count - 1)
local v = 255
for i = 0, count - 1 do
writeu32(pal, i * 4, rgb(v, v, v))
v = math.max(0, v - step)
end
return bits, pal
elseif id ~= 0 then
return bits, defaultTable(bits)
end
local pal = buffer.create(1024)
if start + 94 <= stop then
local first = readu32(b, start + 86)
local last = readu16(b, start + 92)
if first <= 255 and last <= 255 then
for i = first, last do
local o = start + 94 + (i - first) * 8
if o + 8 > stop then
break
end
writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6)))
end
end
end
return bits, pal
end
return QtPalette
+188
View File
@@ -0,0 +1,188 @@
--!strict
-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime)
-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4,
-- mov, heif, avif build on it. Written from the specifications; no third-party code.
--
-- local IsoBmff = require("@rosetta/containers/IsoBmff")
-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables)
-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s)
-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta)
-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs
-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes
-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... })
--
-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit
-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave',
-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls),
-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Box = require("@rosetta/containers/IsoBmff/Box")
local Demux = require("@rosetta/containers/IsoBmff/Demux")
local Meta = require("@rosetta/containers/IsoBmff/Meta")
local Mux = require("@rosetta/containers/IsoBmff/Mux")
local IsoBmff = {}
IsoBmff.Box = Box
IsoBmff.Demux = Demux
IsoBmff.Meta = Meta
export type Track = Demux.Track
export type Movie = Demux.Movie
export type Items = Meta.Items
export type Item = Meta.Item
export type MuxSpec = Mux.MuxSpec
export type MuxTrack = Mux.MuxTrack
export type Picture = Meta.Picture
local TOP: { [string]: boolean } = {
ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true,
styp = true, sidx = true, meta = true, uuid = true, PICT = true,
}
-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box,
-- nil when it is not an ISO BMFF file
function IsoBmff.sniff(r: Bytes.Reader): string?
local head = r:peek(12)
if #head < 8 then
return nil
end
local typ = string.sub(head, 5, 8)
if typ == "ftyp" then
return if #head >= 12 then string.sub(head, 9, 12) else ""
end
if TOP[typ] then
local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4)
if size == 1 or size == 0 or size >= 8 then
return ""
end
end
return nil
end
-- parse(r, opts?) -> Movie | nil, Err
function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?)
return Demux.parse(r, opts)
end
-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta)
function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture })
local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst")
return Meta.tags(r.buf, ilst)
end
-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file)
function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?)
local meta = Box.path(movie.boxes, "meta")
if not meta then
return nil, Err.new(Err.CORRUPT, "no top-level meta box")
end
return Meta.items(r.buf, meta)
end
-- itemData(r, items, id) -> buffer | nil, Err
function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?)
return Meta.itemData(r.buf, r.base, r.limit, items, id)
end
-- sample(r, track, i) -> a copy of sample i (1-based)
function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer?
if i < 1 or i > t.sampleCount then
return nil
end
local n = t.sizes[i]
local out = buffer.create(n)
buffer.copy(out, 0, r.buf, t.offsets[i], n)
return out
end
-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts /
-- dts / duration in their track's timescale ticks and a copy of the sample bytes.
function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?)
local movie, err = Demux.parse(r, opts)
if not movie then
return nil, err
end
local cursor: { [number]: number } = {}
local byId: { [number]: Track } = {}
for _, t in movie.tracks do
cursor[t.id] = 1
byId[t.id] = t
end
local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie }
local function packet(t: Track, i: number): any
local dts = t.dts[i]
local cts = t.cts
return {
track = t.id,
dts = dts,
pts = dts + (if cts then cts[i] or 0 else 0),
duration = t.durations[i],
keyframe = t.sync == nil or (t.sync :: any)[i] == true,
data = IsoBmff.sample(r, t, i),
index = i,
}
end
function dmx.packets(_self: any, trackId: number?): () -> any
return function(): any
if trackId then
local t = byId[trackId]
if not t then
return nil
end
local i = cursor[trackId]
if i > t.sampleCount then
return nil
end
cursor[trackId] = i + 1
return packet(t, i)
end
-- all tracks in file order
local best: Track? = nil
local bestOff = math.huge
for _, t in movie.tracks do
local i = cursor[t.id]
if i <= t.sampleCount and t.offsets[i] < bestOff then
best, bestOff = t, t.offsets[i]
end
end
if not best then
return nil
end
local i = cursor[best.id]
cursor[best.id] = i + 1
return packet(best, i)
end
end
-- seek(seconds): every track to its last sync sample at or before the time
function dmx.seek(_self: any, seconds: number)
for _, t in movie.tracks do
local target = seconds * t.timescale
local lo, hi = 1, t.sampleCount
local found = 1
while lo <= hi do
local mid = (lo + hi) // 2
if t.dts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if t.sync then
while found > 1 and not (t.sync :: any)[found] do
found -= 1
end
end
cursor[t.id] = found
end
end
return dmx, nil
end
-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux)
function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?)
return Mux.mux(spec)
end
return IsoBmff
+158
View File
@@ -0,0 +1,158 @@
--!strict
-- containers/MacFile: classic Mac OS files (a data fork, a resource fork and Finder info) as Archive entries, shared by
-- the Mac encodings (archive/binhex, archive/macbinary, archive/applesingle). The convention (unar's "visible forks"):
-- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with
-- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix
-- seconds) and comment. Writers pair them back with collect().
--
-- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" })
-- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string
-- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes
-- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped)
-- New code. Never throws.
local Err = require("@rosetta/core/Err")
local Archive = require("@rosetta/containers/Archive")
local MacFile = {}
export type Info = {
name: string,
data: buffer,
rsrc: buffer,
type: string, -- 4 bytes ("\0\0\0\0" when unknown)
creator: string,
flags: number, -- Finder flags (16 bits)
created: number?, -- unix seconds
modified: number?,
comment: string?,
}
local MAC_EPOCH = 2082844800 -- seconds from 1904-01-01 to 1970-01-01
function MacFile.fromMac(s: number): number?
return if s == 0 then nil else s - MAC_EPOCH
end
function MacFile.toMac(unix: number?): number
if type(unix) ~= "number" or unix ~= unix then
return 0
end
return math.clamp(math.floor(unix + MAC_EPOCH), 0, 0xFFFFFFFF)
end
-- Mac OS Roman bytes 0x80..0xFF
local ROMAN = {
0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8,
0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC,
0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8,
0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8,
0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153,
0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02,
0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4,
0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7,
}
local FROM_UNICODE: { [number]: number } = {}
for i, u in ROMAN do
FROM_UNICODE[u] = 127 + i
end
-- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through)
function MacFile.name(s: string): string
if not string.find(s, "[\128-\255]") then
return s
end
local out = table.create(#s)
for i = 1, #s do
local c = string.byte(s, i)
out[i] = if c < 128 then string.char(c) else utf8.char(ROMAN[c - 127])
end
return table.concat(out)
end
-- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes)
function MacFile.roman(s: string): string
if not string.find(s, "[\128-\255]") or not utf8.len(s) then
return s
end
local out = {}
for _, c in utf8.codes(s) do
table.insert(out, if c < 128 then string.char(c) else string.char(FROM_UNICODE[c] or 63))
end
return table.concat(out)
end
local function four(s: any): string
if type(s) ~= "string" then
return "\0\0\0\0"
end
return string.sub(s .. "\0\0\0\0", 1, 4)
end
-- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and
-- there is a resource fork) and, when non-empty, the resource fork entry
function MacFile.put(a: any, f: Info, noData: boolean?)
local common = {
macType = f.type,
macCreator = f.creator,
finderFlags = f.flags,
created = f.created,
mtime = f.modified,
comment = f.comment,
dir = false,
}
local e: any = table.clone(common)
e.name, e.size, e.data, e.fork = f.name, buffer.len(f.data), f.data, "data"
if not noData and (buffer.len(f.data) > 0 or buffer.len(f.rsrc) == 0) then
Archive.put(a, e)
end
if buffer.len(f.rsrc) > 0 then
local r: any = table.clone(common)
r.name, r.size, r.data, r.fork = f.name .. ".rsrc", buffer.len(f.rsrc), f.rsrc, "resource"
Archive.put(a, r)
end
end
-- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a
-- buffer or a string (one data fork named name, default "data")
function MacFile.collect(value: any, name: string?): ({ Info }?, Err.Err?)
local files, err = Archive.files(value, name)
if not files then
return nil, err
end
local out: { Info } = {}
local byName: { [string]: Info } = {}
local function get(n: string, e: any): Info
local f = byName[n]
if not f then
f = {
name = n,
data = buffer.create(0),
rsrc = buffer.create(0),
type = four(e.macType),
creator = four(e.macCreator),
flags = if type(e.finderFlags) == "number" then bit32.band(e.finderFlags, 0xFFFF) else 0,
created = if type(e.created) == "number" then e.created else nil,
modified = if type(e.mtime) == "number" then e.mtime else nil,
comment = if type(e.comment) == "string" then e.comment else nil,
}
byName[n] = f
table.insert(out, f)
end
return f :: Info
end
-- data forks first, so a resource fork finds its file whatever the order
for _, it in files do
if it.entry.fork ~= "resource" then
get(it.name, it.entry).data = it.data
end
end
for _, it in files do
if it.entry.fork == "resource" then
local base = string.match(it.name, "^(.*)%.rsrc$") or it.name
get(base, it.entry).rsrc = it.data
end
end
return out, nil
end
return MacFile
+173
View File
@@ -0,0 +1,173 @@
--!strict
-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in rosetta.
-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it,
-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence
-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws.
local readu8 = buffer.readu8
local MpegEs = {}
-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil
function MpegEs.findStart(b: buffer, p: number, limit: number): number?
local i = p
while i + 3 <= limit do
local c = readu8(b, i + 2)
if c > 1 then
i += 3
elseif c == 1 then
if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then
return i
end
i += 3
else -- c == 0: the start code may begin at i + 1 or i + 2
i += 1
end
end
return nil
end
local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 }
export type Picture = {
offset: number, -- start of the access unit (its first header's start code)
size: number,
type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown)
temporal: number, -- temporal_reference
gop: boolean, -- a GOP header precedes the picture
sequence: boolean, -- a sequence header precedes the picture
structure: number, -- MPEG-2 picture_structure: 1 top field, 2 bottom field, 3 frame (MPEG-1: 3)
fields: number?, -- 2: a frame coded as two field pictures (both in this unit)
}
export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean }
-- info(b, off, limit) -> the first sequence header's facts | nil
function MpegEs.info(b: buffer, off: number, limit: number): Info?
local p = MpegEs.findStart(b, off, limit)
local info: Info? = nil
local count = 0
while p and count < 64 do
count += 1
local code = if p + 3 < limit then readu8(b, p + 3) else -1
if code == 0xB3 and p + 11 < limit and not info then
local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16
local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6)
local fr = readu8(b, p + 7) % 16
info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false }
elseif code == 0xB5 and info then
info.mpeg2 = true
return info
elseif code == 0x00 and info then
return info
end
p = MpegEs.findStart(b, p + 4, limit)
end
return info
end
-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0
function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number)
local p = MpegEs.findStart(b, off, limit)
local count = 0
while p and count < 32 do
count += 1
if p + 5 < limit and readu8(b, p + 3) == 0x00 then
local x = readu8(b, p + 4) * 256 + readu8(b, p + 5)
return (x // 8) % 8, x // 64
end
p = MpegEs.findStart(b, p + 4, limit)
end
return 0, 0
end
-- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture
-- coding extension (3 = frame when there is none: MPEG-1)
function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number
local q = MpegEs.findStart(b, p + 4, limit)
local count = 0
while q and count < 8 do
count += 1
local code = if q + 6 < limit then readu8(b, q + 3) else -1
if code == 0xB5 then
if readu8(b, q + 4) // 16 == 8 then
local st = readu8(b, q + 6) % 4
return if st == 0 then 3 else st
end
elseif code ~= 0xB2 then
break
end
q = MpegEs.findStart(b, q + 4, limit)
end
return 3
end
-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its
-- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures
-- is one unit (fields = 2)
function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture }
local out: { Picture } = {}
local unitStart: number? = nil
local seq, gop = false, false
local cur: Picture? = nil
local p = MpegEs.findStart(b, off, limit)
while p do
local code = if p + 3 < limit then readu8(b, p + 3) else -1
local st = if code == 0x00 then MpegEs.pictureStructure(b, p, limit) else 3
if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then
-- the second field of the current frame: same unit
cur.fields = 2
elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then
-- a sequence / GOP header or a picture after a picture closes it
if cur and (code ~= 0xB7) then
cur.size = p - cur.offset
table.insert(out, cur)
cur = nil
end
if code == 0xB3 then
unitStart = unitStart or p
seq = true
elseif code == 0xB8 then
unitStart = unitStart or p
gop = true
elseif code == 0x00 then
local t, tr = 0, 0
if p + 5 < limit then
local x = readu8(b, p + 4) * 256 + readu8(b, p + 5)
t, tr = (x // 8) % 8, x // 64
end
cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture
unitStart, seq, gop = nil, false, false
elseif code == 0xB7 and cur then
cur.size = p + 4 - cur.offset
table.insert(out, cur)
cur = nil
end
end
p = MpegEs.findStart(b, p + 4, limit)
end
if cur then
cur.size = limit - cur.offset
table.insert(out, cur)
end
return out
end
-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5)
function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean
local p = MpegEs.findStart(b, off, limit)
local count = 0
while p and count < 64 do
count += 1
if p + 3 < limit then
local t = readu8(b, p + 3) % 32
if t == 5 then
return true
elseif t == 1 then
return false
end
end
p = MpegEs.findStart(b, p + 3, limit)
end
return false
end
return MpegEs
+224
View File
@@ -0,0 +1,224 @@
--!strict
-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams:
-- .mpg / .mpeg / .vob). New in rosetta. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program
-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private
-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts,
-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync).
--
-- local ps, err = MpegPs.read(buf, base, limit)
-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or
-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance
--
-- Never throws: malformed packets are skipped and counted in ps.errors.
local Err = require("@rosetta/core/Err")
local MpegEs = require("@rosetta/containers/MpegEs")
local readu8 = buffer.readu8
local MpegPs = {}
export type Pes = { pts: number?, dts: number?, offset: number, size: number }
export type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } }
export type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number }
local WRAP = 8589934592 -- 2^33
-- PSM stream_type -> kind, codec
local TYPES: { [number]: { string } } = {
[0x01] = { "video", "mpeg1" },
[0x02] = { "video", "mpeg2" },
[0x03] = { "audio", "mp2" },
[0x04] = { "audio", "mp2" },
[0x0F] = { "audio", "aac" },
[0x10] = { "video", "mpeg4" },
[0x1B] = { "video", "h264" },
[0x24] = { "video", "hevc" },
[0x81] = { "audio", "ac3" },
}
local function ts(b: buffer, p: number): number
local a = readu8(b, p)
local v = (a // 2) % 8
v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2
v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2
return v
end
-- read(buf, base, limit) -> File | nil, Err
function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?)
local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 }
local types: { [number]: number } = {}
local last: { [number]: number } = {}
local wrap: { [number]: number } = {}
local packs = 0
local p = MpegEs.findStart(b, base, limit)
local function unwrap(id: number, v: number): number
local off = wrap[id] or 0
local prev = last[id]
local t = v + off
if prev and t < prev - WRAP / 2 then
off += WRAP
wrap[id] = off
t = v + off
end
last[id] = t
return t
end
while p do
if p + 4 > limit then
break
end
local code = readu8(b, p + 3)
local nextP = p + 4
if code == 0xBA then
packs += 1
if p + 5 > limit then
break
end
local m = readu8(b, p + 4)
if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing
file.mpeg2 = true
if p + 14 > limit then
break
end
nextP = p + 14 + readu8(b, p + 13) % 8
else
nextP = p + 12
end
elseif code == 0xB9 then
nextP = p + 4
elseif code >= 0xBB then
if p + 6 > limit then
break
end
local len = readu8(b, p + 4) * 256 + readu8(b, p + 5)
local stop = p + 6 + len
if stop > limit then
stop = limit
end
nextP = stop
if code == 0xBC and len >= 10 then -- program stream map
local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9)
local q = p + 10 + infoLen
if q + 2 <= stop then
local mapLen = readu8(b, q) * 256 + readu8(b, q + 1)
q += 2
local e = math.min(stop, q + mapLen)
while q + 4 <= e do
local st, sid = readu8(b, q), readu8(b, q + 1)
local il = readu8(b, q + 2) * 256 + readu8(b, q + 3)
types[sid] = st
q += 4 + il
end
end
elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then
-- a PES packet
local q = p + 6
local pts, dts: number? = nil, nil
local ok = true
if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header
if q + 3 > stop then
ok = false
else
local flags = readu8(b, q + 1)
local hlen = readu8(b, q + 2)
local h = q + 3
if flags >= 0x80 and h + 5 <= stop then
pts = ts(b, h)
if flags // 64 == 3 and h + 10 <= stop then
dts = ts(b, h + 5)
end
end
q = h + hlen
end
else -- MPEG-1 packet header
local n = 0
while q < stop and readu8(b, q) == 0xFF and n < 16 do
q += 1
n += 1
end
if q < stop and readu8(b, q) // 64 == 1 then
q += 2
end
if q < stop then
local c = readu8(b, q) // 16
if c == 2 and q + 5 <= stop then
pts = ts(b, q)
q += 5
elseif c == 3 and q + 10 <= stop then
pts = ts(b, q)
dts = ts(b, q + 5)
q += 10
elseif readu8(b, q) == 0x0F then
q += 1
else
ok = false
end
end
end
if ok and q <= stop then
local id = code
local kind, codec = "other", "unknown"
if code == 0xBD then
if q >= stop then
ok = false
else
local sub = readu8(b, q)
id = 0xBD00 + sub
if sub >= 0x80 and sub <= 0x87 then
kind, codec = "audio", "ac3"
q += 4
elseif sub >= 0x88 and sub <= 0x8F then
kind, codec = "audio", "dts"
q += 4
elseif sub >= 0xA0 and sub <= 0xA7 then
kind, codec = "audio", "pcm_dvd"
q += 7
elseif sub >= 0x20 and sub <= 0x3F then
kind, codec = "subtitle", "dvdsub"
q += 1
else
q += 1
end
end
elseif code >= 0xE0 then
kind, codec = "video", "mpeg1"
else
kind, codec = "audio", "mp2"
end
local st = types[code]
if st and TYPES[st] then
kind, codec = TYPES[st][1], TYPES[st][2]
end
if ok and q <= stop then
local s = file.streams[id]
if not s then
s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } :: Stream
file.streams[id] = s
table.insert(file.order, id)
end
table.insert(s.pes, {
pts = if pts then unwrap(id, pts) else nil,
dts = if dts then unwrap(id + 0x10000, dts) else nil,
offset = q,
size = stop - q,
})
end
end
if not ok then
file.errors += 1
end
end
else
-- a start code that is not a system one (stray ES data between packets): resync
file.errors += 1
end
p = MpegEs.findStart(b, nextP, limit)
end
if packs == 0 and #file.order == 0 then
return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base)
end
return file, nil
end
return MpegPs
+815
View File
@@ -0,0 +1,815 @@
--!strict
--!native
-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same
-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a
-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections
-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity
-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS.
--
-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... }
-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed
--
-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is
-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised.
local Crc32 = require("@rosetta/core/Crc32")
local MpegTs = {}
export type Stream = {
pid: number,
streamType: number, -- PMT stream_type (0 when the stream was found without a PMT)
kind: string, -- "video" | "audio" | "other"
codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ...
program: number, -- program_number (0 without a PMT)
language: string?, -- ISO 639 language descriptor, when present
}
export type Unit = {
pid: number,
kind: string,
codec: string,
streamType: number,
streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio)
pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID)
dts: number?, -- seconds; equals pts when the PES carries no DTS
pts90: number?, -- the same in 90 kHz ticks
dts90: number?,
data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio)
ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit
randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set
discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set
}
export type Stats = {
packets: number,
syncLosses: number, -- resyncs (bytes skipped to find 0x47 again)
skippedBytes: number,
teiErrors: number, -- transport_error_indicator packets (dropped)
ccErrors: number, -- continuity counter gaps
duplicates: number, -- duplicate packets (same CC), dropped
crcErrors: number, -- PSI sections with a bad CRC (ignored)
pesErrors: number, -- PES units without a valid header (dropped)
scrambled: number, -- scrambled packets (dropped)
pcr: number?, -- last PCR seen, seconds
}
export type Demuxed = {
video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order
audio: { Unit }, -- units of the selected audio PID
streams: { Stream }, -- every elementary stream, PMT order
units: { Unit }, -- every unit of every PID, in completion order
videoPid: number?,
audioPid: number?,
stats: Stats,
}
type PesState = {
buf: buffer,
len: number,
active: boolean,
expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start)
hdrChecked: boolean,
ccError: boolean,
randomAccess: boolean,
discontinuity: boolean,
lastPts: number, -- for 33-bit wrap unwrapping
wrapOffset: number,
}
type SectionState = { buf: buffer, len: number, active: boolean }
local TS_SIZE = 188
local SYNC = 0x47
local MAX_SECTION = 4096 + 188
local WRAP = 8589934592 -- 2^33
local readu8 = buffer.readu8
local band = bit32.band
local bor = bit32.bor
local lshift = bit32.lshift
local rshift = bit32.rshift
local CODECS: { [number]: { string } } = {
[0x01] = { "video", "mpeg1video" },
[0x02] = { "video", "mpeg2video" },
[0x03] = { "audio", "mpegaudio" },
[0x04] = { "audio", "mpegaudio" },
[0x0F] = { "audio", "aac" },
[0x10] = { "video", "mpeg4" },
[0x11] = { "audio", "aac_latm" },
[0x1B] = { "video", "h264" },
[0x24] = { "video", "hevc" },
[0x81] = { "audio", "ac3" },
[0x87] = { "audio", "eac3" },
}
-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0
local function crc32(b: buffer, off: number, n: number): number
return Crc32.msb(b, off, n, 0xFFFFFFFF)
end
MpegTs.crc32 = crc32
local function u16(b: buffer, p: number): number
return readu8(b, p) * 256 + readu8(b, p + 1)
end
-- 33-bit timestamp from the 5-byte PES encoding at p
local function readTs(b: buffer, p: number): number
local b0 = readu8(b, p)
local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30
local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15
local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0
return hi + mid * 32768 + lo
end
local Demuxer = {}
Demuxer.__index = Demuxer
export type Demuxer = typeof(setmetatable(
{} :: {
_pend: buffer,
_pendLen: number,
_pmtPids: { [number]: number },
_streams: { [number]: Stream },
_pes: { [number]: PesState },
_sections: { [number]: SectionState },
_cc: { [number]: number },
_queue: { Unit },
_qhead: number,
_qtail: number,
streams: { Stream },
stats: Stats,
},
Demuxer
))
function MpegTs.new(): Demuxer
local self = setmetatable({
_pend = buffer.create(64 * 1024),
_pendLen = 0,
_pmtPids = {},
_streams = {},
_pes = {},
_sections = {},
_cc = {},
_queue = {},
_qhead = 1,
_qtail = 0,
streams = {},
stats = {
packets = 0,
syncLosses = 0,
skippedBytes = 0,
teiErrors = 0,
ccErrors = 0,
duplicates = 0,
crcErrors = 0,
pesErrors = 0,
scrambled = 0,
pcr = nil,
} :: Stats,
}, Demuxer)
return self
end
-- PSI ---------------------------------------------------------------------------------------------------------
local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?)
local info = CODECS[streamType]
local s = self._streams[pid]
if s == nil then
s = {
pid = pid,
streamType = streamType,
kind = if info then info[1] else "other",
codec = if info then info[2] else "unknown",
program = program,
language = language,
}
self._streams[pid] = s
table.insert(self.streams, s)
else
s.streamType = streamType
s.kind = if info then info[1] else "other"
s.codec = if info then info[2] else "unknown"
s.program = program
s.language = language
end
end
local function parseSection(self: Demuxer, pid: number, b: buffer, n: number)
-- n >= 3 bytes: table_id, section_length (n = 3 + section_length)
if n < 12 then
return
end
if band(readu8(b, 1), 0x80) == 0 then
return -- no section_syntax_indicator: not a PAT / PMT
end
if crc32(b, 0, n) ~= 0 then
self.stats.crcErrors += 1
return
end
if band(readu8(b, 5), 1) == 0 then
return -- current_next_indicator = 0: a future table
end
local tid = readu8(b, 0)
local stop = n - 4
if tid == 0x00 and pid == 0 then
local p = 8
while p + 4 <= stop do
local prog = u16(b, p)
local pmt = band(u16(b, p + 2), 0x1FFF)
if prog ~= 0 then
self._pmtPids[pmt] = prog
end
p += 4
end
elseif tid == 0x02 and self._pmtPids[pid] ~= nil then
local program = u16(b, 3)
local p = 12 + band(u16(b, 10), 0x0FFF)
while p + 5 <= stop do
local st = readu8(b, p)
local epid = band(u16(b, p + 1), 0x1FFF)
local esl = band(u16(b, p + 3), 0x0FFF)
local d = p + 5
local dend = math.min(d + esl, stop)
local language: string? = nil
while d + 2 <= dend do
local tag, len = readu8(b, d), readu8(b, d + 1)
if tag == 0x0A and len >= 3 and d + 5 <= dend then
language = buffer.readstring(b, d + 2, 3)
end
d += 2 + len
end
addStream(self, epid, st, program, language)
p += 5 + esl
end
end
end
local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number)
local n = to - from
if n <= 0 then
return
end
if s.len + n > MAX_SECTION then
s.active = false
s.len = 0
return
end
buffer.copy(s.buf, s.len, src, from, n)
s.len += n
-- every complete section in the buffer
while s.active and s.len >= 3 do
if readu8(s.buf, 0) == 0xFF then
s.active = false -- stuffing: no more sections until the next unit start
s.len = 0
return
end
local need = 3 + band(u16(s.buf, 1), 0x0FFF)
if s.len < need then
return
end
parseSection(self, pid, s.buf, need)
local rest = s.len - need
if rest > 0 then
buffer.copy(s.buf, 0, s.buf, need, rest)
end
s.len = rest
end
end
local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number)
local s = self._sections[pid]
if s == nil then
s = { buf = buffer.create(MAX_SECTION), len = 0, active = false }
self._sections[pid] = s
end
if pusi then
if pos >= stop then
return
end
local ptr = readu8(b, pos)
pos += 1
local tail = math.min(pos + ptr, stop)
if s.active then
sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section
end
s.active = true
s.len = 0
pos = tail
elseif not s.active then
return
end
sectionBytes(self, pid, s, b, pos, stop)
end
-- PES ---------------------------------------------------------------------------------------------------------
local function completePes(self: Demuxer, pid: number, st: PesState)
st.active = false
local b, len = st.buf, st.len
if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then
self.stats.pesErrors += 1
return
end
local sid = readu8(b, 3)
local stop = if st.expected > 0 then math.min(st.expected, len) else len
local start = 6
local pts: number?, dts: number? = nil, nil
if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then
if stop < 9 then
self.stats.pesErrors += 1
return
end
if band(readu8(b, 6), 0xC0) == 0x80 then
-- MPEG-2 PES header
local flags = readu8(b, 7)
local hl = readu8(b, 8)
start = 9 + hl
if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then
pts = readTs(b, 9)
if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then
dts = readTs(b, 14)
end
end
else
-- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS
local p = 6
local k = 0
while p < stop and readu8(b, p) == 0xFF and k < 16 do
p += 1
k += 1
end
if p < stop and band(readu8(b, p), 0xC0) == 0x40 then
p += 2
end
if p < stop then
local c = band(readu8(b, p), 0xF0)
if c == 0x20 and p + 5 <= stop then
pts = readTs(b, p)
p += 5
elseif c == 0x30 and p + 10 <= stop then
pts = readTs(b, p)
dts = readTs(b, p + 5)
p += 10
else
p += 1
end
end
start = p
end
end
if start > stop then
self.stats.pesErrors += 1
return
end
-- unwrap the 33-bit clock (per PID)
if pts ~= nil then
pts += st.wrapOffset
if st.lastPts >= 0 then
if pts < st.lastPts - WRAP / 2 then
st.wrapOffset += WRAP
pts += WRAP
elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then
st.wrapOffset -= WRAP
pts -= WRAP
end
end
st.lastPts = pts
if dts ~= nil then
dts += st.wrapOffset
if dts > pts + WRAP / 2 then
dts -= WRAP
elseif dts < pts - WRAP / 2 then
dts += WRAP
end
else
dts = pts
end
end
local n = stop - start
local data = buffer.create(n)
if n > 0 then
buffer.copy(data, 0, b, start, n)
end
local s = self._streams[pid]
local kind, codec, streamType
if s then
kind, codec, streamType = s.kind, s.codec, s.streamType
elseif sid >= 0xE0 and sid <= 0xEF then
kind, codec, streamType = "video", "unknown", 0
elseif sid >= 0xC0 and sid <= 0xDF then
kind, codec, streamType = "audio", "mpegaudio", 0
else
kind, codec, streamType = "other", "unknown", 0
end
local unit: Unit = {
pid = pid,
kind = kind,
codec = codec,
streamType = streamType,
streamId = sid,
pts = if pts then pts / 90000 else nil,
dts = if dts then dts / 90000 else nil,
pts90 = pts,
dts90 = dts,
data = data,
ccError = st.ccError,
randomAccess = st.randomAccess,
discontinuity = st.discontinuity,
}
local tail = self._qtail + 1
self._qtail = tail
self._queue[tail] = unit
end
local function pesPayload(
self: Demuxer,
pid: number,
pusi: boolean,
b: buffer,
pos: number,
stop: number,
ccError: boolean,
randomAccess: boolean,
discontinuity: boolean
)
local st = self._pes[pid]
-- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored
local startCode = pusi
and stop - pos >= 3
and readu8(b, pos) == 0
and readu8(b, pos + 1) == 0
and readu8(b, pos + 2) == 1
if st == nil then
if not startCode then
return
end
st = {
buf = buffer.create(16 * 1024),
len = 0,
active = false,
expected = 0,
hdrChecked = false,
ccError = false,
randomAccess = false,
discontinuity = false,
lastPts = -1,
wrapOffset = 0,
}
self._pes[pid] = st
end
if ccError and st.active then
st.ccError = true -- packets of the unit in progress were lost
end
if pusi then
if st.active then
completePes(self, pid, st)
end
if not startCode then
if self._streams[pid] ~= nil then
self.stats.pesErrors += 1
end
return
end
st.active = true
st.len = 0
st.expected = 0
st.hdrChecked = false
st.ccError = false
st.randomAccess = randomAccess
st.discontinuity = discontinuity
elseif not st.active then
return
end
local n = stop - pos
if n <= 0 then
return
end
if st.len + n > buffer.len(st.buf) then
local cap = buffer.len(st.buf) * 2
while cap < st.len + n do
cap *= 2
end
if cap > 64 * 1024 * 1024 then
st.active = false -- runaway unit (no unit start for 64 MB): drop it
st.len = 0
self.stats.pesErrors += 1
return
end
local nb = buffer.create(cap)
buffer.copy(nb, 0, st.buf, 0, st.len)
st.buf = nb
end
buffer.copy(st.buf, st.len, b, pos, n)
st.len += n
if not st.hdrChecked and st.len >= 6 then
st.hdrChecked = true
local plen = u16(st.buf, 4)
if plen > 0 then
st.expected = 6 + plen
end
end
if st.expected > 0 and st.len >= st.expected then
completePes(self, pid, st)
end
end
-- packets -----------------------------------------------------------------------------------------------------
local function packet(self: Demuxer, b: buffer, pk: number)
local stats = self.stats
stats.packets += 1
local b1 = readu8(b, pk + 1)
if band(b1, 0x80) ~= 0 then
stats.teiErrors += 1
return
end
local pusi = band(b1, 0x40) ~= 0
local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2)
if pid == 0x1FFF then
return
end
local b3 = readu8(b, pk + 3)
if band(b3, 0xC0) ~= 0 then
stats.scrambled += 1
return
end
local afc = band(rshift(b3, 4), 3)
local cc = band(b3, 15)
if afc == 0 then
return
end
local pos = pk + 4
local stop = pk + TS_SIZE
local discontinuity, randomAccess = false, false
if afc >= 2 then
local afl = readu8(b, pos)
pos += 1
if afl > 183 then
return
end
if afl > 0 then
local flags = readu8(b, pos)
discontinuity = band(flags, 0x80) ~= 0
randomAccess = band(flags, 0x40) ~= 0
if band(flags, 0x10) ~= 0 and afl >= 7 then
local base = readu8(b, pos + 1) * 33554432
+ readu8(b, pos + 2) * 131072
+ readu8(b, pos + 3) * 512
+ readu8(b, pos + 4) * 2
+ rshift(readu8(b, pos + 5), 7)
local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6)
stats.pcr = base / 90000 + ext / 27000000
end
end
pos += afl
if afc == 2 then
if discontinuity then
self._cc[pid] = nil
end
return -- adaptation field only: the counter does not advance
end
end
-- continuity counter
local ccError = false
local last = self._cc[pid]
if last ~= nil and not discontinuity then
if cc == last then
stats.duplicates += 1
return
elseif cc ~= band(last + 1, 15) then
ccError = true
stats.ccErrors += 1
end
end
self._cc[pid] = cc
if pid == 0 or self._pmtPids[pid] ~= nil then
sectionPayload(self, pid, pusi, b, pos, stop)
elseif pid >= 0x10 then
pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity)
end
end
-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for
-- pull(). Returns false for a bad argument.
function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
src = buffer.fromstring(data)
elseif type(data) == "buffer" then
src = data
else
return false
end
local off = math.max(0, math.floor(offset or 0))
local total = buffer.len(src)
if off > total then
return false
end
local n = math.min(math.floor(len or (total - off)), total - off)
if n < 0 then
return false
end
-- append to the pending bytes
local need = self._pendLen + n
if need > buffer.len(self._pend) then
local cap = buffer.len(self._pend)
while cap < need do
cap *= 2
end
local nb = buffer.create(cap)
buffer.copy(nb, 0, self._pend, 0, self._pendLen)
self._pend = nb
end
if n > 0 then
buffer.copy(self._pend, self._pendLen, src, off, n)
end
self._pendLen = need
local b, avail = self._pend, self._pendLen
local p = 0
while p + TS_SIZE <= avail do
if readu8(b, p) ~= SYNC then
-- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data)
self.stats.syncLosses += 1
local q = p + 1
local found = -1
local waitAt = -1
while q < avail do
if readu8(b, q) == SYNC then
if q + TS_SIZE < avail then
if readu8(b, q + TS_SIZE) == SYNC then
found = q
break
end
elseif q + TS_SIZE == avail then
found = q
break
else
waitAt = q -- not enough bytes to confirm: wait for more
break
end
end
q += 1
end
if found >= 0 then
self.stats.skippedBytes += found - p
p = found
elseif waitAt >= 0 then
self.stats.skippedBytes += waitAt - p
p = waitAt
break
else
self.stats.skippedBytes += avail - p
p = avail
break
end
else
packet(self, b, p)
p += TS_SIZE
end
end
local rest = avail - p
if rest > 0 and p > 0 then
buffer.copy(b, 0, b, p, rest)
end
self._pendLen = rest
return true
end
-- The next completed unit (any PID), or nil.
function Demuxer.pull(self: Demuxer): Unit?
local q = self._queue
local h = self._qhead
local u = q[h]
if u == nil then
return nil
end
q[h] = nil :: any
h += 1
if h > self._qtail then
table.clear(q)
h = 1
self._qtail = 0
end
self._qhead = h
return u
end
-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next
-- unit start). Units still queue up for pull().
function Demuxer.flush(self: Demuxer)
local pids = {}
for pid, st in self._pes do
if st.active then
table.insert(pids, pid)
end
end
table.sort(pids)
for _, pid in pids do
completePes(self, pid, self._pes[pid])
end
self._pendLen = 0
end
-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek).
function Demuxer.reset(self: Demuxer)
self._pendLen = 0
for _, st in self._pes do
st.active = false
st.len = 0
st.lastPts = -1
st.wrapOffset = 0
end
for _, s in self._sections do
s.active = false
s.len = 0
end
table.clear(self._cc)
table.clear(self._queue)
self._qhead = 1
self._qtail = 0
end
-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT).
function Demuxer.streamFor(self: Demuxer, kind: string): Stream?
for _, s in self.streams do
if s.kind == kind then
return s
end
end
return nil
end
export type DemuxOptions = { videoPid: number?, audioPid: number? }
-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid /
-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video /
-- audio (PES stream_id). Never throws; a bad argument gives empty lists.
function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed
local d = MpegTs.new()
d:push(data)
d:flush()
local units = {}
while true do
local u = d:pull()
if u == nil then
break
end
table.insert(units, u)
end
local videoPid = opts and opts.videoPid
local audioPid = opts and opts.audioPid
if videoPid == nil then
local s = d:streamFor("video")
videoPid = if s then s.pid else nil
end
if audioPid == nil then
local s = d:streamFor("audio")
audioPid = if s then s.pid else nil
end
for _, u in units do
if videoPid == nil and u.kind == "video" then
videoPid = u.pid
end
if audioPid == nil and u.kind == "audio" then
audioPid = u.pid
end
end
local video, audio = {}, {}
for _, u in units do
if u.pid == videoPid then
table.insert(video, u)
elseif u.pid == audioPid then
table.insert(audio, u)
end
end
return {
video = video,
audio = audio,
streams = d.streams,
units = units,
videoPid = videoPid,
audioPid = audioPid,
stats = d.stats,
}
end
-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open).
function MpegTs.concat(units: { Unit }): buffer
local n = 0
for _, u in units do
n += buffer.len(u.data)
end
local out = buffer.create(n)
local p = 0
for _, u in units do
local l = buffer.len(u.data)
buffer.copy(out, p, u.data, 0, l)
p += l
end
return out
end
return MpegTs
+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 rosetta.
-- 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("@rosetta/core/Err")
local Page = require("@rosetta/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
+175
View File
@@ -0,0 +1,175 @@
--!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 Crc32 = require("@rosetta/core/Crc32")
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 (core/Crc32)
local CRC = Crc32.MSB_TABLE
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("@rosetta/core/Err")
local Page = require("@rosetta/containers/Ogg/Page")
local Mux = require("@rosetta/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
+343
View File
@@ -0,0 +1,343 @@
--!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), now the RIFF layout of containers/Chunks; 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("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Chunks = require("@rosetta/containers/Chunks")
local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring
local Riff = {}
export type Chunk = {
id: string,
start: number, -- absolute offset of the chunk header
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 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(b, p, limit, be, opts, ds64) -> the chunks of [p, limit): containers/Chunks with the RIFF layout (padding to 2,
-- lenient missing pad bytes, open-ended ids, RF64 sizes from ds64)
local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any): { Chunk }
local layout: Chunks.Layout = {
bigEndian = be,
pad = 2,
lenientPad = true,
openEnded = opts and opts.openEnded,
maxChunks = opts and opts.maxChunks,
resize = if ds64
then function(id: string, declared: number): number?
if declared ~= 0xFFFFFFFF then
return nil
end
return if id == "data" then ds64.dataSize else ds64.table[id]
end
else nil,
}
return Chunks.walk(b, p, limit, layout) :: any
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
f.chunks = walk(b, base + 12, limit, be, opts, f.ds64)
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
+426
View File
@@ -0,0 +1,426 @@
--!strict
-- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles
-- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path,
-- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields,
-- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar
-- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more,
-- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX
-- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi-
-- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes).
--
-- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } }
-- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts)
--
-- Never throws: bad data returns nil, Err.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Tar = {}
export type Entry = {
name: string,
size: number,
type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ...
dir: boolean,
mode: number,
uid: number,
gid: number,
mtime: number,
link: string?,
uname: string?,
gname: string?,
offset: number, -- absolute offset of the data in the buffer
pax: { [string]: string }?,
}
local BLOCK = 512
local function zeros(b: buffer, o: number): boolean
for i = 0, BLOCK - 1, 4 do
if buffer.readu32(b, o + i) ~= 0 then
return false
end
end
return true
end
-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte)
local function number(b: buffer, o: number, n: number): number?
local first = buffer.readu8(b, o)
if first >= 0x80 then
local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative
for i = 1, n - 1 do
v = v * 256 + buffer.readu8(b, o + i)
end
return v
end
local s = buffer.readstring(b, o, n)
s = string.match(s, "^[ %z]*([0-7]*)") or ""
if s == "" then
return 0
end
return tonumber(s, 8)
end
local function str(b: buffer, o: number, n: number): string
local s = buffer.readstring(b, o, n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local function checksum(b: buffer, o: number): (number, number)
local u, s = 0, 0
for i = 0, BLOCK - 1 do
local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i)
u += v
s += if v >= 128 then v - 256 else v
end
return u, s
end
-- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum
function Tar.valid(b: buffer, o: number): boolean
if o + BLOCK > buffer.len(b) or zeros(b, o) then
return false
end
local want = number(b, o + 148, 8)
local u, s = checksum(b, o)
return want == u or want == s
end
-- pax records "len key=value\n" -> { key = value }
local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean
local s = buffer.readstring(b, o, n)
local p = 1
while p <= #s do
if string.byte(s, p) == 0 then
break
end
local len = string.match(s, "^(%d+) ", p)
if not len then
return false
end
local l = tonumber(len) :: number
if l < #len + 3 or p + l - 1 > #s then
return false
end
local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline
local eq = string.find(rec, "=", 1, true)
if not eq then
return false
end
into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1)
p += l
end
return true
end
export type ReadOptions = { maxEntries: number? } -- default 1e6
-- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err
function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?)
local o = offset or 0
local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
local maxEntries = (opts and opts.maxEntries) or 1e6
local out: { Entry } = {}
local global: { [string]: string } = {}
local nextPax: { [string]: string }? = nil
local longName: string? = nil
local longLink: string? = nil
local p = o
while true do
if p + BLOCK > e then
if p == e then
break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning)
end
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
if zeros(b, p) then
break -- end of archive (one or two zero blocks; what follows is padding)
end
local want = number(b, p + 148, 8)
local u, s = checksum(b, p)
if want ~= u and want ~= s then
return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148)
end
local typ = buffer.readstring(b, p + 156, 1)
if typ == "\0" then
typ = "0"
end
local size = number(b, p + 124, 12)
if not size or size < 0 then
return nil, Err.new(Err.CORRUPT, "bad size field", p + 124)
end
local data = p + BLOCK
local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK
local ustar = buffer.readstring(b, p + 257, 5) == "ustar"
-- meta records: pax / GNU long names
if typ == "x" or typ == "g" or typ == "L" or typ == "K" then
if data + size > e then
return nil, Err.new(Err.TRUNCATED, "extended header past the end", data)
end
if typ == "x" or typ == "g" then
local into = if typ == "g" then global else (nextPax or {})
if not pax(b, data, size, into) then
return nil, Err.new(Err.CORRUPT, "bad pax record", data)
end
if typ == "x" then
nextPax = into
end
elseif typ == "L" then
longName = str(b, data, size)
else
longLink = str(b, data, size)
end
p = nextHeader
continue
end
local name = str(b, p, 100)
if ustar then
local prefix = str(b, p + 345, 155)
if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times)
name = prefix .. "/" .. name
end
end
local entry: Entry = {
name = name,
size = size,
type = typ,
dir = typ == "5",
mode = number(b, p + 100, 8) or 0,
uid = number(b, p + 108, 8) or 0,
gid = number(b, p + 116, 8) or 0,
mtime = number(b, p + 136, 12) or 0,
link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil,
uname = if ustar then str(b, p + 265, 32) else nil,
gname = if ustar then str(b, p + 297, 32) else nil,
offset = data,
pax = nil,
}
if longName then
entry.name = longName
end
if longLink then
entry.link = longLink
end
local px = nextPax
for _, rec in { global, px } do
if rec then
if rec.path then
entry.name = rec.path
end
if rec.linkpath then
entry.link = rec.linkpath
end
if rec.size then
local sz = tonumber(rec.size)
if not sz or sz < 0 or sz % 1 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad pax size", p)
end
entry.size = sz
end
if rec.mtime then
entry.mtime = tonumber(rec.mtime) or entry.mtime
end
if rec.uid then
entry.uid = tonumber(rec.uid) or entry.uid
end
if rec.gid then
entry.gid = tonumber(rec.gid) or entry.gid
end
if rec.uname then
entry.uname = rec.uname
end
if rec.gname then
entry.gname = rec.gname
end
end
end
if px then
entry.pax = px
end
if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then
entry.dir = true
end
-- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir)
local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size
if typ == "5" or typ == "1" or typ == "2" then
entry.size = 0
end
nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK
if typ ~= "5" and data + dataSize > e then
return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data)
end
table.insert(out, entry)
if #out > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
nextPax, longName, longLink = nil, nil, nil
p = nextHeader
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WriteEntry = {
name: string,
data: buffer?,
dir: boolean?,
type: string?, -- default "0" ("5" for dir)
link: string?,
mode: number?, -- default 0o644 (0o755 for directories)
uid: number?,
gid: number?,
uname: string?,
gname: string?,
mtime: number?, -- unix seconds (default 0)
}
export type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed)
local function octal(w: buffer, o: number, n: number, v: number): boolean
-- n - 1 octal digits and a NUL; false when it does not fit
local s = string.format("%o", v)
if v < 0 or v % 1 ~= 0 or #s > n - 1 then
return false
end
buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s)
buffer.writeu8(w, o + n - 1, 0)
return true
end
local function field(w: buffer, o: number, n: number, s: string)
buffer.writestring(w, o, string.sub(s, 1, n))
end
local function ascii(s: string): boolean
return not string.find(s, "[\128-\255]")
end
local function paxRecord(key: string, value: string): string
local body = " " .. key .. "=" .. value .. "\n"
local n = #body + 1
while #tostring(n) + #body ~= n do
n = #tostring(n) + #body
end
return tostring(n) .. body
end
-- one header block (the checksum filled in)
local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer
local h = buffer.create(BLOCK)
field(h, 0, 100, name)
local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4)
octal(h, 100, 8, mode % 0x200000)
octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF))
octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF))
octal(h, 124, 12, size)
octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1))
field(h, 148, 8, " ")
field(h, 156, 1, typ)
field(h, 157, 100, link)
field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000")
field(h, 265, 32, e.uname or "")
field(h, 297, 32, e.gname or "")
field(h, 345, 155, prefix)
local u = checksum(h, 0)
field(h, 148, 8, string.format("%06o", u) .. "\0 ")
return h
end
-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil
local function split(path: string): (string?, string?)
if #path <= 100 then
return "", path
end
for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile
if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then
return string.sub(path, 1, i - 1), string.sub(path, i + 1)
end
end
return nil, nil
end
-- write(entries, opts?) -> buffer | nil, Err
function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
local fmt = (opts and opts.format) or "pax"
local w = Bytes.writer(BLOCK * (2 * #entries + 2))
for i, e in entries do
if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
end
local data = e.data or buffer.create(0)
local typ = e.type or (if e.dir then "5" else "0")
local name: string = e.name
if typ == "5" and string.sub(name, -1) ~= "/" then
name ..= "/"
end
local size = if typ == "0" or typ == "7" then buffer.len(data) else 0
local link = e.link or ""
-- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole
local prefix, short
if fmt == "ustar" then
prefix, short = split(name)
elseif #name <= 100 then
prefix, short = "", name
end
local paxRecs: { string } = {}
-- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII
local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name))
local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link))
if needName or needLink then
if fmt == "ustar" then
return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar")
elseif fmt == "gnu" then
if needName then
local ln = buffer.fromstring(name .. "\0")
w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true))
w:bytes(ln)
w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK)
end
if needLink then
local ll = buffer.fromstring(link .. "\0")
w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true))
w:bytes(ll)
w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK)
end
else
if needName then
table.insert(paxRecs, paxRecord("path", name))
end
if needLink then
table.insert(paxRecs, paxRecord("linkpath", link))
end
end
end
if size >= 8 ^ 11 then
if fmt ~= "pax" then
return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax")
end
table.insert(paxRecs, paxRecord("size", tostring(size)))
end
local mt = e.mtime or 0
if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then
table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", "")))
end
if #paxRecs > 0 then
local body = buffer.fromstring(table.concat(paxRecs))
w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false))
w:bytes(body)
w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK)
end
if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then
-- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile)
local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?")
prefix, short = "", string.sub(stand, 1, 100)
end
w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu"))
if size > 0 then
w:bytes(data)
w:fill(0, (BLOCK - size % BLOCK) % BLOCK)
end
end
w:fill(0, BLOCK * 2)
return w:finish(), nil
end
return Tar
+658
View File
@@ -0,0 +1,658 @@
--!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/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/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("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Deflate = require("@rosetta/codecs/compress/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 = table.create(math.min(count, 65536)) :: { any }
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 civil = Types.Date.civilFromDays
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