From e3f9d0fb3875c6160701d423c4ea85f9d6b34606 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:26:39 -0500 Subject: [PATCH] absorb: containers/Ogg (demuxer from ogg-luau be9f604, Err values, Reader input) + a new muxer (page writer); tests vs opusenc / flac / ffmpeg fixtures --- licenses/NOTICE.md | 1 + src/Formats/containers/Ogg/Mux.luau | 208 ++++++++++++ src/Formats/containers/Ogg/Page.luau | 185 +++++++++++ src/Formats/containers/Ogg/init.luau | 456 +++++++++++++++++++++++++++ tests/containers/ogg.luau | 263 +++++++++++++++ tools/fixtures/ogg.py | 209 ++++++++++++ 6 files changed, 1322 insertions(+) create mode 100644 src/Formats/containers/Ogg/Mux.luau create mode 100644 src/Formats/containers/Ogg/Page.luau create mode 100644 src/Formats/containers/Ogg/init.luau create mode 100644 tests/containers/ogg.luau create mode 100644 tools/fixtures/ogg.py diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..bc841c1 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -4,6 +4,7 @@ |---|---|---| | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | +| `src/Formats/containers/Ogg/` (init, Page) | ogg-luau be9f604 (same author), written from RFC 3533 | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/containers/Ogg/Mux.luau b/src/Formats/containers/Ogg/Mux.luau new file mode 100644 index 0000000..1e5ea79 --- /dev/null +++ b/src/Formats/containers/Ogg/Mux.luau @@ -0,0 +1,208 @@ +--!strict +--!native +--!optimize 2 +-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in formats-luau. +-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or +-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last +-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages +-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. +-- +-- local mux = Mux.new({ pageSize = 4096 }) +-- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...) +-- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page +-- s:packet(tags, 0, { flush = true }) +-- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate) +-- local out = mux:finish() -- closes every stream with an eos page +-- +-- Never throws: a bad argument returns false, Err. +local Err = require("@formats/core/Err") +local Page = require("@formats/containers/Ogg/Page") + +local CRC = Page.CRC_TABLE +local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32 +local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift + +local Mux = {} +Mux.__index = Mux +local Stream = {} +Stream.__index = Stream + +export type Options = { + pageSize: number?, -- close a page once its data reaches this many bytes (default 4096; at most 255 * 255) +} +export type PacketOptions = { + flush: boolean?, -- close the page after this packet (headers; default false) + eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed) +} + +-- new(opts?) -> Mux +function Mux.new(opts: Options?): any + local size = opts and opts.pageSize or 4096 + if type(size) ~= "number" or size < 1 then + size = 4096 + end + return setmetatable({ + pageSize = math.min(size, 255 * 255), + chunks = {} :: { buffer }, + total = 0, + streams = {} :: { any }, + nextSerial = 1, + }, Mux) +end + +-- stream(serial?) -> Stream (serials must be unique in the file) +function Mux.stream(self: any, serial: number?): any + local sr = serial or self.nextSerial + self.nextSerial = math.max(self.nextSerial, sr + 1) + local s = setmetatable({ + mux = self, + serial = sr % 4294967296, + seq = 0, + lacing = {} :: { number }, + parts = {} :: { any }, -- buffer, offset, length triples of the page data + dataLen = 0, + granule = -1, + continued = false, -- the page being built starts with the tail of a packet + first = true, + ended = false, + lastGranule = -1, + }, Stream) + table.insert(self.streams, s) + return s +end + +-- the CRC of a page (the crc field written as zero) +local function crc(b: buffer, n: number): number + local c = 0 + for i = 0, n - 1 do + c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1]) + end + return c +end + +-- close the page being built (also when empty, for eos) +function Stream._flush(self: any, eos: boolean) + local nseg = #self.lacing + local n = 27 + nseg + self.dataLen + local b = buffer.create(n) + buffer.writestring(b, 0, "OggS") + local flags = (if self.continued then 1 else 0) + (if self.first then 2 else 0) + (if eos then 4 else 0) + writeu8(b, 5, flags) + local g = self.granule + if g < 0 then + writeu32(b, 6, 0xFFFFFFFF) + writei32(b, 10, -1) + else + writeu32(b, 6, g % 4294967296) + writeu32(b, 10, (g // 4294967296) % 4294967296) + end + writeu32(b, 14, self.serial) + writeu32(b, 18, self.seq % 4294967296) + writeu8(b, 26, nseg) + for i = 1, nseg do + writeu8(b, 26 + i, self.lacing[i]) + end + local o = 27 + nseg + local parts = self.parts + for i = 1, #parts, 3 do + buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2]) + o += parts[i + 2] + end + writeu32(b, 22, crc(b, n)) + local m = self.mux + table.insert(m.chunks, b) + m.total += n + self.seq += 1 + self.first = false + self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1 + self.continued = false + if eos then + self.ended = true + end +end + +-- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet +-- (-1: unknown, not recommended); offset / length select a range of data. +function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) + if self.ended then + return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return false, Err.new(Err.ARG, "packet: data must be a buffer or a string") + end + if type(granule) ~= "number" then + return false, Err.new(Err.ARG, "packet: granule must be a number") + end + local off = offset or 0 + local len = length or (buffer.len(b) - off) + if off < 0 or len < 0 or off + len > buffer.len(b) then + return false, Err.new(Err.ARG, "packet: range outside the buffer") + end + local pageSize = self.mux.pageSize + local left = len + local pos = off + -- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255) + while true do + if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then + self:_flush(false) + self.continued = pos > off -- the next page starts inside this packet + end + local seg = math.min(left, 255) + table.insert(self.lacing, seg) + if seg > 0 then + table.insert(self.parts, b) + table.insert(self.parts, pos) + table.insert(self.parts, seg) + end + self.dataLen += seg + pos += seg + left -= seg + if seg < 255 then + break + end + end + if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page + self.granule = granule + self.lastGranule = granule + end + local eos = opts and opts.eos or false + if eos then + self:_flush(true) + elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then + self:_flush(false) + end + return true, nil +end + +-- flush(): close the current page now (if it holds anything) +function Stream.flush(self: any) + if not self.ended and #self.lacing > 0 then + self:_flush(false) + end +end + +-- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written) +function Mux.finish(self: any): buffer + for _, s in self.streams do + if not s.ended then + if #s.lacing == 0 then + s.granule = s.lastGranule + end + s:_flush(true) + end + end + local out = buffer.create(self.total) + local o = 0 + for _, c in self.chunks do + buffer.copy(out, o, c, 0, buffer.len(c)) + o += buffer.len(c) + end + return out +end + +return Mux diff --git a/src/Formats/containers/Ogg/Page.luau b/src/Formats/containers/Ogg/Page.luau new file mode 100644 index 0000000..acf9125 --- /dev/null +++ b/src/Formats/containers/Ogg/Page.luau @@ -0,0 +1,185 @@ +--!strict +--!native +--!optimize 2 +-- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header +-- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset, +-- forwards or backwards). Nothing here throws: invalid or truncated data gives nil. +-- +-- A page header (27 bytes + segment table): +-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) +-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 +local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift + +local Page = {} + +export type Info = { + offset: number, -- byte offset of "OggS" + size: number, -- header + segment table + data + headerSize: number, -- 27 + segment count + nsegs: number, + flags: number, + continued: boolean, + bos: boolean, + eos: boolean, + granule: number, -- -1 when no packet finishes on this page + serial: number, + sequence: number, +} + +-- CRC table, MSB-first +local CRC = table.create(256, 0) +for i = 0, 255 do + local r = lshift(i, 24) + for _ = 1, 8 do + if band(r, 0x80000000) ~= 0 then + r = bxor(lshift(r, 1), 0x04C11DB7) + else + r = lshift(r, 1) + end + end + CRC[i + 1] = r +end +Page.CRC_TABLE = CRC + +-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc +local function crcRange(b: buffer, from: number, to: number, crc: number): number + for i = from, to - 1 do + crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) + end + return crc +end + +-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +function Page.crc32(b: buffer, offset: number?, len: number?): number + local o = offset or 0 + local n = len or (buffer.len(b) - o) + if o < 0 or n < 0 or o + n > buffer.len(b) then + return 0 + end + return crcRange(b, o, o + n, 0) +end + +-- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic", +-- "version", "crc"). verify = false skips the CRC check. +function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) + local size = buffer.len(b) + if pos < 0 or pos + 27 > size then + return nil, "short" + end + if readu32(b, pos) ~= 0x5367674F then -- "OggS" + return nil, "magic" + end + if readu8(b, pos + 4) ~= 0 then + return nil, "version" + end + local nsegs = readu8(b, pos + 26) + local hsize = 27 + nsegs + if pos + hsize > size then + return nil, "short" + end + local dlen = 0 + for i = pos + 27, pos + hsize - 1 do + dlen += readu8(b, i) + end + local total = hsize + dlen + if pos + total > size then + return nil, "short" + end + if verify ~= false then + local c = crcRange(b, pos, pos + 22, 0) + for _ = 1, 4 do + c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1]) + end + c = crcRange(b, pos + 26, pos + total, c) + if c ~= readu32(b, pos + 22) then + return nil, "crc" + end + end + local flags = readu8(b, pos + 5) + return { + offset = pos, + size = total, + headerSize = hsize, + nsegs = nsegs, + flags = flags, + continued = band(flags, 1) ~= 0, + bos = band(flags, 2) ~= 0, + eos = band(flags, 4) ~= 0, + granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6), + serial = readu32(b, pos + 14), + sequence = readu32(b, pos + 18), + }, nil +end + +-- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the +-- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped. +function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lim = math.min(limit or size, size - 27 + 1) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos += 1 + end + return nil +end + +-- The last valid page starting at an offset in [floor, pos] (searching backwards). +function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lo = math.max(floor or 0, 0) + if pos > size - 27 then + pos = size - 27 + end + while pos >= lo do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos -= 1 + end + return nil +end + +-- The identification of a codec from a stream's first packet (the bos page's packet) +function Page.codec(b: buffer, off: number, len: number): string + local function is(s: string, at: number): boolean + if at + #s > len then + return false + end + for i = 1, #s do + if readu8(b, off + at + i - 1) ~= string.byte(s, i) then + return false + end + end + return true + end + if is("OpusHead", 0) then + return "opus" + elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then + return "flac" + elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then + return "vorbis" + elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then + return "theora" + elseif is("Speex ", 0) then + return "speex" + elseif is("fishead", 0) then + return "skeleton" + elseif is("fLaC", 0) then + return "flac-old" -- pre-1.1.1 Ogg FLAC mapping + end + return "unknown" +end + +return Page diff --git a/src/Formats/containers/Ogg/init.luau b/src/Formats/containers/Ogg/init.luau new file mode 100644 index 0000000..367f468 --- /dev/null +++ b/src/Formats/containers/Ogg/init.luau @@ -0,0 +1,456 @@ +--!strict +--!native +--!optimize 2 +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604 +-- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and +-- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture +-- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial); +-- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad +-- input gives nil, err). +-- +-- local demux, err = Ogg.open(buf) +-- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end +-- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator +-- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil +-- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target) +-- +-- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux) +-- local s = mux:stream(serial?) -- one logical stream +-- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages +-- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes +-- local file = mux:finish() -- every stream ends with an eos page +local Err = require("@formats/core/Err") +local Page = require("@formats/containers/Ogg/Page") +local Mux = require("@formats/containers/Ogg/Mux") + +local readu8 = buffer.readu8 +type PageInfo = any -- Page.Info (the sibling module is untyped here: required through `script` in Roblox) + +local Ogg = {} +Ogg.Page = Page +Ogg.Mux = Mux +Ogg.muxer = Mux.new + +export type Packet = { + data: buffer, -- the packet bytes are data[offset .. offset + size - 1] + offset: number, + size: number, + granule: number, -- the page granule if this is the last packet finishing on its page, else -1 + pageGranule: number, -- the granule of the page the packet finishes on (may be -1) + bos: boolean, -- first packet of the stream + eos: boolean, -- last packet of the stream (last packet finishing on an eos page) + pageOffset: number, -- byte offset of the page the packet finishes on + gap: boolean, -- data was lost before this packet (a missing page / bad CRC in between) +} + +export type Stream = { + serial: number, + codec: string, -- "opus" | "flac" | "vorbis" | "theora" | "speex" | "skeleton" | "flac-old" | "unknown" + firstPacket: buffer, -- a copy of the identification packet + bosOffset: number, -- byte offset of the bos page + lastGranule: number, -- the last known granule of the stream (-1 if none) +} + +-- Reader: the packet cursor of one logical stream +local Reader = {} +Reader.__index = Reader + +local function newReader(d: any, serial: number, start: number): any + return setmetatable({ + demux = d, + buf = d.buf, + serial = serial, + start = start, -- the bos page offset + pagePos = start, -- where to look for the next page + page = nil :: PageInfo?, + seg = 0, -- next segment index on the page + dataPos = 0, -- byte offset of the next segment's data + lastComplete = -1, -- index of the last segment ending a packet on this page + firstPacketOnPage = true, + parts = {} :: { number }, -- pending partial packet: offset, len pairs + partLen = 0, + lastSeq = -1, + gap = false, + ended = false, + total = 0, + }, Reader) +end + +-- Load the next page of this serial; false at the end of the data +function Reader._nextPage(self: any): boolean + local b, d = self.buf, self.demux + while true do + local p = Page.find(b, self.pagePos, nil, d.verify) + if not p then + return false + end + self.pagePos = p.offset + p.size + if p.serial == self.serial then + if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then + -- a page is missing: drop the partial packet + self.parts, self.partLen = {}, 0 + self.gap = true + end + self.lastSeq = p.sequence + self.page = p + self.seg = 0 + self.dataPos = p.offset + p.headerSize + self.firstPacketOnPage = true + local lc = -1 + local base = p.offset + 27 + for i = 0, p.nsegs - 1 do + if readu8(b, base + i) < 255 then + lc = i + end + end + self.lastComplete = lc + if p.continued then + if self.partLen == 0 and #self.parts == 0 then + -- the start of this packet is not ours (after a seek or a loss): skip its tail + local s = 0 + while s < p.nsegs do + local l = readu8(b, base + s) + self.dataPos += l + s += 1 + if l < 255 then + break + end + end + self.seg = s + self.firstPacketOnPage = false + end + elseif #self.parts > 0 then + -- a fresh packet while one was pending: the pending one is lost + self.parts, self.partLen = {}, 0 + self.gap = true + end + return true + end + end +end + +-- The next packet, or nil at the end of the stream +function Reader.nextPacket(self: any): Packet? + if self.ended then + return nil + end + local b = self.buf + while true do + local p = self.page + if p and self.seg < p.nsegs then + local base = p.offset + 27 + local start = self.dataPos + local len = 0 + local s = self.seg + local complete = false + while s < p.nsegs do + local l = readu8(b, base + s) + s += 1 + len += l + if l < 255 then + complete = true + break + end + end + self.seg = s + self.dataPos = start + len + if complete then + local data, off, size = b, start, len + local parts = self.parts + if #parts > 0 then + size = self.partLen + len + data = buffer.create(size) + off = 0 + local o = 0 + for i = 1, #parts, 2 do + buffer.copy(data, o, b, parts[i], parts[i + 1]) + o += parts[i + 1] + end + buffer.copy(data, o, b, start, len) + self.parts, self.partLen = {}, 0 + end + local last = (s - 1) == self.lastComplete + local pkt = { + data = data, + offset = off, + size = size, + granule = if last then p.granule else -1, + pageGranule = p.granule, + bos = p.bos and self.firstPacketOnPage, + eos = p.eos and last, + pageOffset = p.offset, + gap = self.gap, + } + self.firstPacketOnPage = false + self.gap = false + self.total += 1 + if pkt.eos then + self.ended = true + end + return pkt + else + -- the packet continues on a later page + table.insert(self.parts, start) + table.insert(self.parts, len) + self.partLen += len + end + else + if p and p.eos then + self.ended = true + return nil + end + if not self:_nextPage() then + self.ended = true + return nil + end + end + end +end + +-- Back to the start of the stream (the identification packet comes next) +function Reader.rewind(self: any) + self.pagePos = self.start + self.page = nil + self.seg = 0 + self.parts, self.partLen = {}, 0 + self.lastSeq = -1 + self.gap = false + self.ended = false +end + +-- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them +function Reader._at(self: any, p: PageInfo) + self:rewind() + self.pagePos = p.offset + self:_nextPage() -- loads p (it is a valid page of this serial) + local b = self.buf + local base = p.offset + 27 + local dp = p.offset + p.headerSize + for i = 0, self.lastComplete do + dp += readu8(b, base + i) + end + self.seg = self.lastComplete + 1 + self.dataPos = dp + self.parts, self.partLen = {}, 0 + self.firstPacketOnPage = false + self.gap = false + self.ended = false +end + +-- Seek so that the next packet is the first one that starts at or before granule g: positions after the last +-- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the +-- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start +-- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil). +function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) + local b, d = self.buf, self.demux + local serial = self.serial + local verify = d.verify + local function nextOf(pos: number, limit: number?): PageInfo? + while true do + local p = Page.find(b, pos, limit, verify) + if not p then + return nil + end + if p.serial == serial and p.granule ~= -1 then + return p + end + pos = p.offset + p.size + end + end + local lo, hi = self.start, buffer.len(b) + local best: PageInfo? = nil + while hi - lo > 65536 do + local mid = (lo + hi) // 2 + local p = nextOf(mid, hi) + if p and p.granule <= g then + best = p + lo = p.offset + else + hi = mid + end + end + local pos = lo + while true do + local p = nextOf(pos) + if not p or p.granule > g then + break + end + best = p + pos = p.offset + p.size + end + if not best then + self:rewind() + return -1, nil + end + self:_at(best) + return best.granule, nil +end + +-- Demux +local Demux = {} +Demux.__index = Demux + +-- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied +-- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll = +-- true lists every bos page in the file (chained streams), not just the first group +function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) + local buf: buffer + if type(src) == "buffer" then + buf = src + elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + buf = src.buf + else + local n = math.max(0, src.limit - src.base) + buf = buffer.create(n) + buffer.copy(buf, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader") + end + local verify = not (opts and opts.verify == false) + local first = Page.find(buf, 0, nil, verify) + if not first then + return nil, Err.new(Err.CORRUPT, "no Ogg page found") + end + local d = setmetatable({ + buf = buf, + size = buffer.len(buf), + verify = verify, + _streams = {} :: { Stream }, + _bySerial = {} :: { [number]: Stream }, + _readers = {} :: { [number]: any }, + _lastDone = false, + }, Demux) + -- the bos pages (at the start of the file, and later ones for chains if scanAll) + local pos = first.offset + local scanAll = opts and opts.scanAll + while true do + local p = Page.find(buf, pos, nil, verify) + if not p then + break + end + if p.bos and not d._bySerial[p.serial] then + local st = { + serial = p.serial, + codec = "unknown", + firstPacket = buffer.create(0), + bosOffset = p.offset, + lastGranule = -1, + } + table.insert(d._streams, st) + d._bySerial[p.serial] = st + local r = newReader(d, p.serial, p.offset) + local pk = r:nextPacket() + if pk then + local c = buffer.create(pk.size) + buffer.copy(c, 0, pk.data, pk.offset, pk.size) + st.firstPacket = c + st.codec = Page.codec(c, 0, pk.size) + end + elseif not p.bos and not scanAll then + break + end + pos = p.offset + p.size + end + if #d._streams == 0 then + return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page") + end + return d, nil +end + +-- Scan backwards from the end for each stream's last granule +function Demux._scanLast(self: any) + if self._lastDone then + return + end + self._lastDone = true + local b = self.buf + local need = #self._streams + local pos = self.size - 27 + while need > 0 do + local p = Page.findBack(b, pos, 0, self.verify) + if not p then + break + end + local st = self._bySerial[p.serial] + if st and st.lastGranule == -1 and p.granule ~= -1 then + st.lastGranule = p.granule + need -= 1 + end + pos = p.offset - 1 + end +end + +-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule } +function Demux.streams(self: any): { Stream } + self:_scanLast() + return self._streams +end + +function Demux.stream(self: any, serial: number): Stream? + self:_scanLast() + return self._bySerial[serial] +end + +-- The serial of the first stream of a codec, or nil +function Demux.find(self: any, codec: string): number? + for _, s in self._streams do + if s.codec == codec then + return s.serial + end + end + return nil +end + +-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err +function Demux.reader(self: any, serial: number): (any, Err.Err?) + local r = self._readers[serial] + if r then + return r, nil + end + local st = self._bySerial[serial] + if not st then + return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial)) + end + r = newReader(self, serial, st.bosOffset) + self._readers[serial] = r + return r, nil +end + +function Demux.nextPacket(self: any, serial: number): Packet? + local r = self:reader(serial) + return if r then r:nextPacket() else nil +end + +function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?) + local r, err = self:reader(serial) + if not r then + return nil, err + end + return r:seekGranule(g) +end + +function Demux.rewind(self: any, serial: number) + local r = self:reader(serial) + if r then + r:rewind() + end +end + +-- for p in demux:packets(serial) do ... end (continues from the stream's current position) +function Demux.packets(self: any, serial: number): () -> Packet? + local r = self:reader(serial) + return function() + return if r then r:nextPacket() else nil + end +end + +-- Copy a packet's bytes into a fresh buffer of its own +function Ogg.copy(p: Packet): buffer + local c = buffer.create(p.size) + buffer.copy(c, 0, p.data, p.offset, p.size) + return c +end + +return Ogg diff --git a/tests/containers/ogg.luau b/tests/containers/ogg.luau new file mode 100644 index 0000000..0df5c7c --- /dev/null +++ b/tests/containers/ogg.luau @@ -0,0 +1,263 @@ +-- containers/Ogg tests: real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files, +-- checked packet by packet against the independent Python parser of tools/fixtures/ogg.py; seeking on each; a big +-- multiplexed file written with the muxer (bisection seeks); muxer edge cases (lacing at 255 multiples, page breaks, +-- continued packets, flush, eos); a sub-range Reader; truncated / garbage input never throws. The muxer was also +-- checked by hand against opus-tools: an opusenc file remuxed through it passes opusinfo and decodes identically. +-- Ported from ogg-luau tests/ogg.luau. Fixtures: tools/fixtures/ogg.py. +local T = require("@tests/T") +local Ogg = require("@formats/containers/Ogg") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/ogg_cases") + +local t = T.suite("ogg") + +-- seek expectations from a packet list: { size, crc, granule, bos, eos } +local function expectSeek(list: { any }, g: number): (number, number) + local start, idx = -1, 1 + for i, p in list do + if p[3] ~= -1 and p[3] <= g then + start, idx = p[3], i + 1 + end + end + return start, idx +end + +local samples = {} +for _, fx in Cases do + local buf = buffer.fromstring(fx.data) + table.insert(samples, fx.data) + local d, err = Ogg.open(buf) + t:check(d, fx.name .. ": open " .. tostring(err)) + local streams = d:streams() + t:eq(#streams, #fx.streams, fx.name .. ": stream count") + for si, es in fx.streams do + local s = streams[si] + t:eq(s.serial, es.serial, fx.name .. ": serial") + t:eq(s.codec, es.codec, fx.name .. ": codec") + t:eq(s.lastGranule, es.lastGranule, fx.name .. ": lastGranule") + t:eq(buffer.len(s.firstPacket), es.packets[1][1], fx.name .. ": first packet") + local n, gaps = 0, 0 + for p in d:packets(s.serial) do + n += 1 + if p.gap then + gaps += 1 + end + local e = es.packets[n] + t:check(e, fx.name .. ": too many packets") + t:eq(p.size, e[1], fx.name .. ": packet " .. n .. " size") + t:eq(Crc32.of(p.data, p.offset, p.size), e[2], fx.name .. ": packet " .. n .. " bytes") + t:eq(p.granule, e[3], fx.name .. ": packet " .. n .. " granule") + t:check(p.bos == e[4] and p.eos == e[5], fx.name .. ": packet " .. n .. " bos/eos") + end + t:eq(n, #es.packets, fx.name .. ": packet count") + t:eq(gaps, if fx.name == "mux_lost" and s.serial == 7 then 1 else 0, fx.name .. ": gap flags") + t:check(d:nextPacket(s.serial) == nil, fx.name .. ": end stays at end") + end + if #fx.streams > 1 then + local counts = {} + for i in streams do + counts[i] = 0 + end + local d2 = Ogg.open(buf) + local live = #streams + while live > 0 do + live = 0 + for i, s in streams do + local p = d2:nextPacket(s.serial) + if p then + live += 1 + counts[i] += 1 + t:eq(p.size, fx.streams[i].packets[counts[i]][1], fx.name .. ": interleaved read") + end + end + end + for i in streams do + t:eq(counts[i], #fx.streams[i].packets, fx.name .. ": interleaved count") + end + end + -- seeking + for _, es in fx.streams do + local serial = es.serial + local last = es.lastGranule + local targets = { -5, 0, 1, last // 3, last // 2, last - 1, last, last + 100 } + for _, p in es.packets do + if p[3] > 0 then + table.insert(targets, p[3]) + table.insert(targets, p[3] - 1) + end + end + for _, g in targets do + local start = d:seekGranule(serial, g) + local eStart, eIdx = expectSeek(es.packets, g) + if start == -1 then + eIdx = 1 -- rewound: the identification packet comes next + end + t:eq(start, eStart, fx.name .. ": seek " .. g .. " start") + local p = d:nextPacket(serial) + local e = es.packets[eIdx] + if e then + t:check(p and p.size == e[1] and Crc32.of(p.data, p.offset, p.size) == e[2], fx.name .. ": packet after seek " .. g) + else + t:check(p == nil, fx.name .. ": seek past the end") + end + end + end + -- a Reader over a sub-range of a bigger buffer + local big = buffer.create(#fx.data + 20) + buffer.writestring(big, 11, fx.data) + local ds = Ogg.open(Bytes.reader(big, 11, #fx.data)) + t:check(ds and #ds:streams() == #fx.streams, fx.name .. ": open from a sub-range Reader") + local n = 0 + for _ in ds:packets(fx.streams[1].serial) do + n += 1 + end + t:eq(n, #fx.streams[1].packets, fx.name .. ": packets from a sub-range Reader") + t:note("%-14s ok (%d streams)", fx.name, #streams) +end + +-- the muxer: a big file with 3 streams, random packet sizes, page breaks by size and count; read back + seeks +do + local rand = T.rng(12345) + local mux = Ogg.muxer({ pageSize = 4096 }) + local S = {} + for k = 1, 3 do + S[k] = { stream = mux:stream(1000 + k), serial = 1000 + k, granNow = 0, pk = {} } + end + local npk = 2500 + for i = 1, npk do + for k, st in S do + local size = if i == 1 then 30 else (if rand(50) == 0 then rand(3000) else rand(300)) + local tag = rand(256) + local b = buffer.create(size) + for j = 0, size - 1 do + buffer.writeu8(b, j, (tag + j + 1) % 256) + end + st.granNow += if i == 1 then 0 else (k * 120) + local ok, e = st.stream:packet(b, st.granNow, { flush = i == 1, eos = i == npk }) + t:check(ok, "mux packet: " .. tostring(e)) + table.insert(st.pk, { size, tag, st.granNow, Crc32.of(b) }) + end + end + local file = mux:finish() + local d = Ogg.open(file) + t:check(d and #d:streams() == 3, "big: 3 streams") + for _, st in S do + t:eq(d:stream(st.serial).lastGranule, st.granNow, "big: lastGranule") + local n = 0 + for p in d:packets(st.serial) do + n += 1 + local e = st.pk[n] + t:check(p.size == e[1] and Crc32.of(p.data, p.offset, p.size) == e[4], "big: packet " .. n) + t:check(p.bos == (n == 1) and p.eos == (n == npk), "big: bos / eos " .. n) + end + t:eq(n, npk, "big: count") + for q = 0, 100 do + local g = math.floor(st.granNow * q / 100) + local start = d:seekGranule(st.serial, g) + local p = d:nextPacket(st.serial) + t:check(start and start <= g and start >= 0, "big: seek start") + local idx + for i, e in st.pk do + if e[3] == start then + idx = i + 1 + break + end + end + local e = st.pk[idx] + if e then + t:check(p and p.size == e[1], "big: packet after seek") + else + t:check(p == nil, "big: end after seek") + end + end + end + t:note("muxer: 3 x %d packets, %d bytes, read back and seeked", npk, buffer.len(file)) + table.insert(samples, buffer.readstring(file, 0, math.min(buffer.len(file), 20000))) +end + +-- muxer edge cases: lacing at multiples of 255, a packet over 255 segments (continued pages), empty packets, +-- headers alone on their pages, finish() without eos, eos twice +do + local mux = Ogg.muxer({ pageSize = 1000 }) + local s = mux:stream(42) + local sizes = { 19, 0, 255, 510, 254, 256, 255 * 255, 255 * 255 + 1, 70000, 1, 0, 3000 } + local crcs = {} + for i, n in sizes do + local b = buffer.create(n) + for j = 0, n - 1 do + buffer.writeu8(b, j, (j * 7 + i) % 256) + end + crcs[i] = Crc32.of(b) + t:check(s:packet(b, i * 10, { flush = i <= 2 }), "edge: packet " .. i) + end + local file = mux:finish() + local ok, e = s:packet("late", 999) + t:check(not ok and e and e.code == Err.ARG, "edge: packet after the end is Err.ARG") + local d = Ogg.open(file) :: any + local i = 0 + local pages = 0 + local pos = 0 + while true do + local p = Ogg.Page.find(file, pos) + if not p then + break + end + pages += 1 + t:check(p.nsegs <= 255, "edge: segments per page") + if pages == 1 then + t:check(p.bos and p.nsegs == 1 and p.granule == 10, "edge: the first packet alone on the bos page") + end + pos = p.offset + p.size + end + for p in d:packets(42) do + i += 1 + t:eq(p.size, sizes[i], "edge: size " .. i) + t:eq(Crc32.of(p.data, p.offset, p.size), crcs[i], "edge: bytes " .. i) + t:eq(p.eos, i == #sizes, "edge: eos " .. i) + end + t:eq(i, #sizes, "edge: packet count") + t:check(pages > 70, "edge: page breaks (" .. pages .. " pages)") + t:eq(d:stream(42).lastGranule, #sizes * 10, "edge: last granule") + t:eq(d:stream(42).codec, "unknown", "edge: codec") + -- strings, ranges and bad arguments + local m2 = Ogg.muxer() + local s2 = m2:stream() + t:check(s2:packet("OpusHead" .. string.rep("\0", 11), 0, { flush = true }), "string packet") + t:check(s2:packet(buffer.fromstring("xxabcxx"), 5, nil, 2, 3), "range packet") + t:check(not s2:packet(buffer.create(3), 5, nil, 2, 3), "bad range") + t:check(not s2:packet(42 :: any, 5), "bad data") + local d2 = Ogg.open(m2:finish()) :: any + t:eq(d2:streams()[1].codec, "opus", "codec of a muxed OpusHead") + t:eq(d2:streams()[1].serial, 1, "default serial") + d2:nextPacket(1) + local p = d2:nextPacket(1) + t:eq(buffer.readstring(p.data, p.offset, p.size), "abc", "range packet bytes") + t:check(d2:nextPacket(1) == nil, "empty eos page ends the stream") +end + +-- errors and garbage +do + local _, e1 = Ogg.open(buffer.create(0)) + t:check(e1 and e1.code == Err.CORRUPT, "empty: " .. tostring(e1)) + t:check(Ogg.open(buffer.fromstring(string.rep("OggS", 100))) == nil, "garbage") + local _, e2 = Ogg.open(42 :: any) + t:check(e2 and e2.code == Err.ARG, "not a buffer: " .. tostring(e2)) +end + +-- fuzz: open + read every packet + seek never throws +t:fuzz("open + read + seek", function(b: buffer) + local d = Ogg.open(b) + if d then + for _, s in d:streams() do + for _ in d:packets(s.serial) do + end + d:seekGranule(s.serial, s.lastGranule // 2) + d:nextPacket(s.serial) + end + end + return d +end, samples, { mutations = 6 }) + +t:done() diff --git a/tools/fixtures/ogg.py b/tools/fixtures/ogg.py new file mode 100644 index 0000000..3698da6 --- /dev/null +++ b/tools/fixtures/ogg.py @@ -0,0 +1,209 @@ +# Ogg fixtures (tools/fixtures.py): containers/Ogg. Ported from ogg-luau tools/gen_fixtures.py. +# tests/gen/ogg_cases.luau real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files +# (lacing edge cases, junk, a corrupt page copy, a lost page), each with the packet list +# from the small independent parser below: { size, crc32, granule, bos, eos } +import math, os, random, struct, tempfile, wave, zlib + +# --- CRC + writer ----------------------------------------------------------------------------------------- +def _crc_table(): + t = [] + for i in range(256): + r = i << 24 + for _ in range(8): + r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1) + r &= 0xFFFFFFFF + t.append(r) + return t + + +CRC = _crc_table() + + +def ogg_crc(data): + c = 0 + for x in data: + c = ((c << 8) & 0xFFFFFFFF) ^ CRC[(c >> 24) ^ x] + return c + + +def page(serial, seq, granule, flags, segs, data): + h = struct.pack("<4sBBqIIIB", b"OggS", 0, flags, granule, serial, seq, 0, len(segs)) + bytes(segs) + p = bytearray(h + data) + struct.pack_into(" 0) + segs.append(l) + data += pkt[pos:pos + l] + pos += l + gran = g + if i == 0 or (i % 7 == 3): # bos page holds only the first packet; break pages now and then + flush() + flush(eos=True) + return pages + + +# --- reference parser --------------------------------------------------------------------------------------- +def parse(data): + """{serial: [ (bytes, granule, bos, eos) ]} with resync + CRC check, like the library.""" + out, partial, order, seqs = {}, {}, [], {} + pos = 0 + while True: + i = data.find(b"OggS", pos) + if i < 0 or i + 27 > len(data): + break + nseg = data[i + 26] + segs = data[i + 27:i + 27 + nseg] + total = 27 + nseg + sum(segs) + if len(segs) < nseg or i + total > len(data): + pos = i + 1 + continue + p = bytearray(data[i:i + total]) + crc = struct.unpack_from("