From e5a8e62fbc9d49e3d52eeac55b4980df2c4f60dd Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 01:51:39 -0500 Subject: [PATCH] comments: containers Chunks / MacFile / MpegEs / Ogg / IsoBmff (part) down to specs --- src/Rosetta/containers/Chunks.luau | 15 +++----------- src/Rosetta/containers/IsoBmff/Box.luau | 7 ------- src/Rosetta/containers/IsoBmff/QtPalette.luau | 7 +------ src/Rosetta/containers/IsoBmff/init.luau | 20 ------------------- src/Rosetta/containers/MacFile.luau | 11 ---------- src/Rosetta/containers/MpegEs.luau | 9 --------- src/Rosetta/containers/Ogg/Mux.luau | 15 -------------- src/Rosetta/containers/Ogg/Page.luau | 16 ++++----------- 8 files changed, 8 insertions(+), 92 deletions(-) diff --git a/src/Rosetta/containers/Chunks.luau b/src/Rosetta/containers/Chunks.luau index c119cff..cb4260e 100644 --- a/src/Rosetta/containers/Chunks.luau +++ b/src/Rosetta/containers/Chunks.luau @@ -1,14 +1,7 @@ --!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") --- +-- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and +-- padding): RIFF / RIFX / RF64, IFF / AIFF / AIFC, PNG (size first, CRC trailer), CAF (64-bit sizes). New in rosetta +-- (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). -- 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 @@ -65,7 +58,6 @@ local function u32(b: buffer, o: number, be: boolean): number 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 @@ -129,7 +121,6 @@ function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Ch 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 diff --git a/src/Rosetta/containers/IsoBmff/Box.luau b/src/Rosetta/containers/IsoBmff/Box.luau index acb2ee5..fd127e4 100644 --- a/src/Rosetta/containers/IsoBmff/Box.luau +++ b/src/Rosetta/containers/IsoBmff/Box.luau @@ -42,7 +42,6 @@ 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) @@ -79,8 +78,6 @@ function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) 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 } = {} @@ -133,7 +130,6 @@ function Box.list(b: buffer, p: number, limit: number, parentType: string?, dept 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 @@ -146,7 +142,6 @@ function Box.child(box: Box?, typ: string): Box? 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 @@ -159,7 +154,6 @@ function Box.childrenOf(box: Box?, typ: string): { Box } 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 @@ -181,7 +175,6 @@ function Box.path(root: any, path: string): Box? 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 diff --git a/src/Rosetta/containers/IsoBmff/QtPalette.luau b/src/Rosetta/containers/IsoBmff/QtPalette.luau index 91b4524..b33a821 100644 --- a/src/Rosetta/containers/IsoBmff/QtPalette.luau +++ b/src/Rosetta/containers/IsoBmff/QtPalette.luau @@ -5,10 +5,6 @@ -- 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 @@ -71,8 +67,7 @@ local function defaultTable(bits: number): buffer 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. +-- 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 diff --git a/src/Rosetta/containers/IsoBmff/init.luau b/src/Rosetta/containers/IsoBmff/init.luau index f151e5a..320a594 100644 --- a/src/Rosetta/containers/IsoBmff/init.luau +++ b/src/Rosetta/containers/IsoBmff/init.luau @@ -2,15 +2,6 @@ -- 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), @@ -40,8 +31,6 @@ local TOP: { [string]: boolean } = { 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 @@ -60,18 +49,15 @@ function IsoBmff.sniff(r: Bytes.Reader): string? 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 @@ -80,12 +66,10 @@ function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) 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 @@ -96,8 +80,6 @@ function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? 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 @@ -137,7 +119,6 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) 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 @@ -180,7 +161,6 @@ function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) 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 diff --git a/src/Rosetta/containers/MacFile.luau b/src/Rosetta/containers/MacFile.luau index 87f5e4e..04ca010 100644 --- a/src/Rosetta/containers/MacFile.luau +++ b/src/Rosetta/containers/MacFile.luau @@ -4,11 +4,6 @@ -- 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") @@ -56,7 +51,6 @@ 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 @@ -69,7 +63,6 @@ function MacFile.name(s: string): string 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 @@ -88,8 +81,6 @@ local function four(s: any): string 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, @@ -112,8 +103,6 @@ function MacFile.put(a: any, f: Info, noData: boolean?) 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 diff --git a/src/Rosetta/containers/MpegEs.luau b/src/Rosetta/containers/MpegEs.luau index c91bdb8..1aed523 100644 --- a/src/Rosetta/containers/MpegEs.luau +++ b/src/Rosetta/containers/MpegEs.luau @@ -7,7 +7,6 @@ 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 @@ -40,7 +39,6 @@ export type Picture = { } 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 @@ -64,7 +62,6 @@ function MpegEs.info(b: buffer, off: number, limit: number): Info? 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 @@ -79,8 +76,6 @@ function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, num 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 @@ -100,9 +95,6 @@ function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number 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 @@ -151,7 +143,6 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } 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 diff --git a/src/Rosetta/containers/Ogg/Mux.luau b/src/Rosetta/containers/Ogg/Mux.luau index e27d100..74a99f9 100644 --- a/src/Rosetta/containers/Ogg/Mux.luau +++ b/src/Rosetta/containers/Ogg/Mux.luau @@ -6,14 +6,6 @@ -- 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") @@ -35,7 +27,6 @@ export type PacketOptions = { 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 @@ -50,7 +41,6 @@ function Mux.new(opts: Options?): any }, 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) @@ -80,7 +70,6 @@ local function crc(b: buffer, n: number): number 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 @@ -121,8 +110,6 @@ function Stream._flush(self: any, eos: boolean) 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) @@ -179,14 +166,12 @@ function Stream.packet(self: any, data: any, granule: number, opts: PacketOption 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 diff --git a/src/Rosetta/containers/Ogg/Page.luau b/src/Rosetta/containers/Ogg/Page.luau index 6ce30b4..b35bc11 100644 --- a/src/Rosetta/containers/Ogg/Page.luau +++ b/src/Rosetta/containers/Ogg/Page.luau @@ -1,10 +1,9 @@ --!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. --- +-- containers/Ogg/Page: Ogg pages (RFC 3533): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the crc field read as +-- zero), header parsing and the capture-pattern resync. Absorbed from ogg-luau be9f604 (same author, no third-party +-- code). Never 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 @@ -32,7 +31,6 @@ export type Info = { 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]) @@ -40,7 +38,7 @@ local function crcRange(b: buffer, from: number, to: number, crc: number): numbe return crc end --- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +-- the Ogg CRC-32 of arbitrary data (the crc field is not zeroed) function Page.crc32(b: buffer, offset: number?, len: number?): number local o = offset or 0 local n = len or (buffer.len(b) - o) @@ -50,8 +48,6 @@ function Page.crc32(b: buffer, offset: number?, len: number?): number 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 @@ -102,8 +98,6 @@ function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) }, 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) @@ -122,7 +116,6 @@ function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): In 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) @@ -141,7 +134,6 @@ function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?) 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